Skip to main content

Posts

Use Python to add a file's modification time to the front of the file name

# Add a file's modified time to the front of the name of the file in the format # YYYY-MM-DD-<original-filenam>. # # Works for files in the current directory. from os import listdir from os.path import isfile, join import os import time mypath = "." onlyfiles = [f for f in listdir(mypath) if isfile(join(mypath, f))] for file in onlyfiles:   newname = time.strftime('%Y-%m-%d-', time.gmtime(os.path.getmtime(file))) + file   print("Renaming file: " + file + " to: " newname)   os.rename(file, time.strftime('%Y-%m-%d-', time.gmtime(os.path.getmtime(file))) + file)

Use Robocopy To Backup Files

robocopy C:\Users\username\Documents\ E:\Backup\ /MIR /XJD > Backup.log echo "DONE" >> Backup.log Dry Run: robocopy C:\Users\username\Documents\ E:\Backup\ /MIR /XJD /L > Backup.log rem Copy files to backup volume rem /MIR - Mirror files (delete files on destination that aren't on the source) rem /XJD - Exclude junction points for directories (may cause infinite loops) rem /sl - Don't follow symbolic links and instead create a copy of the link. rem /FFT - 2 second difference when comparing timestamps rem /R:3 - Only retry 3 times (default is 1 million) rem /W:10 - Wait time between retries (default is 30) rem /Z - Copies files in restart mode (NOTE: This WILL slow down copying) rem /B - Backup mode - allows copy of open files (must run as Admin) rem NOTE: /Z and /B can be combined as /ZB rem /NP - Don't output progress of copy operation rem /log:backup.log - Logs to backup.log, overwriting old log file (use /log+: to append) rem /...

How to get information about a running process in Windows

wmic allows you to get a lot of information about processes running on a Windows computer. Here are some useful examples To get a list of all running processes: C:\> wmic process list brief To get information about a process with a specific PID: C:\> wmic process where processid=1120 Or to just get the command line: C:\> wmic process where processid=1120 get commandline

IIS and Windows 2012 Notes

Shut down IIS: net stop was /y Start IIS: net start w3svc Show active http bindings: netsh http show servicestate Config file schemas can be found here: C:\Windows\system32\inetsrv\config\schema\IIS_schema.xml Internet Information Services: What’s New in Window Server 2012 R2

Windows 8 Keyboard Shortcuts

http://www.pcworld.com/article/2012885/20-must-know-windows-8-tips-and-tricks.html The Windows key + I opens the settings menu, giving you quick access to the Control Panel, Personalization, and your Power button, among other features. The Windows key + Pause opens the system properties page to show you a quick rundown of your specs.

A simple IIS HTTP module to log request headers and post data

This is a simple http module that hijacks the incoming request and logs it to a file. Using this module prevents the application from getting the post data because the input stream can only be read once. With .NET 4.0 the module could be much smaller, and could allow the application to read the data. To compile this, create a new "Class Library" application called PostDataLogger. Most of this class is pieced together from stolen code (stack overflow, etc.) using System; using System.IO; using System.Web; /// /// Dump PostDataLogger.DLL in your bin, and put this in your web.config inside of /// /// /// /// public class SimpleLogger : IHttpModule { private HttpApplication _ctx; public void Init(HttpApplication context) { _ctx = context; context.BeginRequest += new EventHandler(Context_BeginRequest); } void Context_BeginRequest(object sender, EventArgs e) { string GUID = Guid.NewGuid().ToString(); string filename = @"d:\temp\adeber...

Working with Git and Git-Flow on Windows

To install Git-Flow on Windows Download the "Binaries Zip" file (util-linux-ng-2.14.1-bin.zip) from http://gnuwin32.sourceforge.net/packages/util-linux-ng.htm Extract util-linux-ng-2.14.1-bin.zip\bin\getopt.exe to "C:\Program Files (x86)\Git\bin" Download the "Dependencies Zip" file (util-linux-ng-2.14.1-dep.zip) from http://gnuwin32.sourceforge.net/packages/util-linux-ng.htm Extract util-linux-ng-2.14.1-dep.zip\bin\libintl3.dll to "C:\Program Files (x86)\Git\bin" Run "git clone --recursive git://github.com/nvie/gitflow.git" cd into gitflow/contrib/ Run msysgit-install.cmd "C:\Program Files (x86)\Git" Run "git flow" in a cmd window to make sure it worked (adapted from http://xinyustudio.wordpress.com/2012/03/26/installing-git-flow-in-windows/ ) Git Configuration After installing Git, set up the configuration: C:\> git config --global user.name "Your Name" C:\> git config --glo...

Running PowerShell commands from Linux

There are several options for running PowerShell commands from Linux. Run the PowerShell script over a REST interface Unless you need a remote shell, the easiest option is to set up a REST interface for your PowerShell scripts. More information here . Using the winrm Ruby Gem https://github.com/WinRb/WinRM Using a WS-Management client on Linux Set up Windows for remote access: https://github.com/Openwsman/openwsman/wiki/winrm-over-openwsman-setup Install OpenWSMAN on Linux: http://openwsman.github.io/ Use Openwsman Command-Line Client: https://github.com/Openwsman/openwsman/wiki/openwsman-command-line-client OR - Use Ruby client bindings: http://users.suse.com/~kkaempf/openwsman/ Install an SSH server on Windows Install a Salt Minion on Windows Install Salt Master on Linux Install Python on Windows Install Salt Minion on Windows Open firewall on Windows for Salt access On Linux, run: # salt "winServer" cmd.run "powersh...

How to log C# exception information including all inner exceptions

/// /// Logs a type and message for and exception (and all inner exceptions) on multiple log lines. /// Lines all contain a unique ID so they can be found if other lines get between them. /// /// Method name, or whatever you want. /// Custom message for the first log line /// Exception to log public static void LogException(string tag, string message, Exception ex) { string logItemId = Guid.NewGuid().ToString("N"); Log(tag, false, logItemId + " " + message); Log(tag, false, logItemId + " Exception: " + ex.GetType().Name + ": " + ex.Message); Exception Inner = ex.InnerException; int innerNumber = 1; while( Inner != null ) { Log(tag, false, logItemId + " Inner Exception " + innerNumber + " " + Inner.GetType().Name + ": " + Inner.Message); Inner = Inner.InnerException; innerNumber++; } }

Parse and organize command line options using C#

This class will parse, organize and collect command line options. I couldn't find anything like it, so I wrote one. This works all the way down to .NET 1.1 if you are lucky enough to still be using that. Save this as ArgDictionary.cs, change the namespace as needed, and feel free to use it in your projects. using System; using System.Collections.Generic; namespace Utilities { /// /// Implements a Dictionary object for handling command line options. /// Supports options with prefixes -, --, or /. /// Supports Boolean, String, or Int32 option values. /// String options are in the following format: /// /stringOption value /// Int32 options are in the following format: /// /intOption 200 /// Boolean options are in the following format: /// /boolOption /// NOTE: if the Boolean option is present in the command line, it is true. /// /// Supports both a long and short version for each option (e.g. /a and /Account /// can be mapped to the same value). /// NOTE: When ...

How to make an HTTP request with PowerShell

If you are making an HTTP request to a RESTful web service, you can use the PowerShell  Invoke-RestMethod cmdlet. This provides a very simple HTTP REST interface, and will also format the result into a PowerShell object. If you would like to use your own functions, you can follow the instructions below. This is a helper function to format (indent) an XML response from a web service. function Format-XML { Param ([string]$xml) $out = New-Object System.IO.StringWriter $Doc=New-Object system.xml.xmlDataDocument $doc.LoadXml($xml) $writer=New-Object system.xml.xmltextwriter($out) $writer.Formatting = [System.xml.formatting]::Indented $doc.WriteContentTo($writer) $writer.Flush() $out.flush() Write-Output $out.ToString() } Here is the function to make the http call. It dumps the response data on the terminal and also returns it as a string to the caller. If there is an error it will dump the HTTP status code and comment on the terminal and return the re...

How to delete a file in C# that might be in use

int retries = 5; while (retries-- >= 0) { try { retries = -1; System.IO.File.Delete(@"C:\deleteme.txt"); } catch (System.IO.IOException ex) // "The specified file is in use." { // File is locked? Sleep and try again. System.Threading.Thread.Sleep(100); // Wait 100ms if (retries >= 0) continue; // go back to while loop throw ex; // give up } } This will also work for writing to a file, etc. This should be enclosed in a try/catch block to catch the other exceptions thrown by the System.IO.File.Delete method.

How to Self-Sign an SSL Certificate

To self-sign SSL certificates using openssl, you will need to set up your own certificate authority using the following steps. Generate a key for your certificate authority openssl genrsa -des3 -out server.key 2048 Remove the password from your server's key. This step is optional, but is required to get the below Perl script to work. Obviously you wouldn't do this to a real key that you had signed by a real certificate authority. cp server.key server.key.org openssl rsa -in server.key.org -out server.key Generate a CSR for your certificate authority. openssl req -new -nodes -key server.key -out server.csr Sign your certificate request openssl x509 -req -days 365 -in server.csr -signkey server.key -out server.crt Now you can sign certificate requests. Here is an example for a CSR named test.csr openssl x509 -req -days 365 -in test.csr -out test.crt -CA server.crt -CAkey server.key -set_serial 01 Optional: Add your certificate authority to your browser so you don'...

Getting Next and Previous Item by ID From MySQL Database With PHP

If you know the ID of an item you want to get from a MySQL database with PHP, but you also want to get the next and previous items when the IDs are in numerical order but may contain gaps due to deleted items, you can do something like this: $curID = NULL; $curRow = NULL; $prevID = NULL; $nextID = NULL; $lastID = NULL; // Get the latest one (for the "Last" link) $result = mysql_query("SELECT itemID FROM tableName ORDER BY itemID desc LIMIT 1"); $row = mysql_fetch_array( $result ); $lastID = $row['itemID']; // Get the ID for the requested item if (isset($_GET['curID'])) { // if $_GET['curID'] defined, use it as curID $curID = $_GET['curID']; } else { // Use the latest one $curID = $lastID; } // Get requested row and next/prev rows if they are there $sql = " SELECT * FROM tableName WHERE tableName.itemID IN ( (select itemID from tableName where itemID < $curID order by i...

Cmd.exe - Using For Loops To Simulate "grep -r */Filename" on Windows

FOR %variable IN (set) DO command [command-parameters] %variable Specifies a single letter replaceable parameter. (set) Specifies a set of one or more files. Wildcards may be used. command Specifies the command to carry out for each file. command-parameters Specifies parameters or switches for the specified command. To perform a grep operation on all files with a certain name in subdirectories of the current directory, although this will try to grep Folder\Filename.ext even if Filename.ext doesn't exist in the folder. for /d %I in (*.*) do grep grepString %~sI\Filename.ext This is slower, but it won't pass files that don't exist to grep, and will recursively search all subdirectories under the current directory. The first example only goes one level deep. for /f "usebackq delims=;" %I in (`dir /s/b Filename.ext`) do grep grepString "%I" The "delims=;" (you can use almost anything for the ;) is required if there are spaces in t...

Get your current IP Address with Powershell

There are lots of ways to do this, but I haven't found an elegant one that works well. Here is my approach that queries the registry: [array] $IPArray = @() $Adapters = Get-Childitem "HKLM:\SYSTEM\CurrentControlSet\Services\Tcpip\Parameters\Adapters" foreach ($uid in $Adapters) { if ($uid.PSChildName -ne "NdisWanIp") { $Interface = "HKLM:\SYSTEM\CurrentControlSet\Services\Tcpip\Parameters\Interfaces\" + $uid.PSChildName ## Write-Host "Checking: $Interface" $IPs = Get-ItemProperty $Interface $IPArray += $IPs.DhcpIPAddress } } $IPArray You can change "$IPs.DhcpIPAddress" to "$IPs.IPAddress" if you have a static IP.

Google dictionary for Bash

For Bash, use Google to get word definitions on the command line by putting this in your .bashrc file: def () { lynx -cfg=/dev/null -dump "http://www.google.com/search?q=define%3A$*" | less; } (Make sure that is all on one line) Then type "def word" to get a definition for "word". You can also create a shell script like so: #!/bin/csh -f lynx -cfg=/dev/null -dump "http://www.google.com/search?q=define%3A${1}" | less This will work if you aren't using Bash. Make the script executable and put it in your search path (~/bin is a good place). You need a copy of lynx (or better yet links ) for this to work. The "-cfg=/dev/null" is optional for lynx, but should be removed if you are using links.