Another useful tool on Windows is Powershell, but it seems that every time I use it I have to Google the right way of doing things. Probably because I don’t use it every day (or week). Anyhow, it’s a very useful piece of software for those odd tasks that show up sometimes.

What’s great about powershell is that it combines all the usual shell goodness (pipes, redirects, and more) with more or less the whole .NET Framework! Many people have used it for years to automate all sorts of tasks.

Dead easy powershell  commands for working with text data:

Replacing strings (example replaces semicolon with win newlines):

 "one;two;three" -replace ";", "`r`n"

And if you want to keep the semicolons as well:

 "one;two;three" -replace ";", "$&`r`n"

Sorting files, which is also dead easy:

 type .\messy_file.txt | sort > sorted_file.txt

But there is a catch! sorted_file.txt will end up with unicode encoding, which is not always what you want. Luckily it turns out that the redirect operator > is just syntactic sugar anyway, and the whole thing can be written as

 type .\messy_file.txt | sort | out-file -encoding unicode -filepath sorted_file.txt

The list of supported output encodings are in the docs, but I do believe it supports these at least:

unicode  — (16-bit)

Recursively deleting certain files with powershell

 ls -recurse -filter *.obj | rm

Find X latest modified files

 ls -recurse | sort -property LastWriteTime -descending | select -first 20

Count lines in a file matching pattern

Here i Count all the .cpp files in a Visual Studio 2012 project file:

 Get-Content MyProject.vcxproj
 | Where-Object {$_ -match "<ClCompile.*.cpp`""}
 | Measure-Object

Powershell has the Measure-Object cmdlet, which is much like “wc” in Unix.
The grave accent character ( ` ) is the Powershell escape character.

Find files or directories having a certain name

The Where-Object cmdlet also be used to for matching file or directorynames.

This is an example of finding all the GIT repositories in a directory tree:

ls -recurse -force | where {$_.Name -eq ".git"}

It is important to include the “-force” switch to powershell “ls”, because .git directories are hidden and will not be found unless that switch is included.

Powershell grep : list files containing pattern

 ls -recurse | select-string -pattern "something" -list | select Filename

This simple command will list each file once which contain a specific pattern. The final select is not necessary, but avoids outputting context around each match which is often very useful when searching binary or autogenerated files.