PowerShell Commands

PowerShell is similar to the DOS terminal in Windows (and will run all the same commands as the DOS terminal) but has many enhanced capabilities. I have not used the DOS terminal enough to really be able to differentiate what one does over the other. PowerShell is my preferred terminal on Windows, and while using it, I have developed several commands that have been very helpful for automating mindless tasks in programming or just in general computer maintenance. Following is a list of commands I have found helpful for several situations I’ve found myself in.

PowerShell Grep

The following represents an example of the “grep” equivalent in PowerShell. In the following example, we get all strings containing “Joe” in the Users.csv file.

Select-String -Path "Users\*.csv" -Pattern "Joe"

PowerShell Recursive Text Replacement

I had a large number of text files for a program that had a specific string of text that needed to be updated. This update was going to be the same for all of these files, and they all lived in subdirectories under the directory that this command was run in. This saved a couple of hours of time since the number of files that need to be changed was in the hundreds.

Get-ChildItem -Recurse *.txt | foreach { (Get-Content $_ | foreach { $_ -replace "old", "new" }) | Set-Content $_ }

PowerShell Rename Several Files With Similar Pattern

I had several files with similar names, and I needed to remove common characters from them to fit a format I needed. The following command allowed me to do that.

Get-ChildItem | Where-Object { $_ -match "<regex_pattern_to_match>" } | Rename-Item -NewName { $_.Name -replace "<regex_pattern_to_replace>", "<new_name_to_replace_matched_pattern>" } 

File Content Diff

Occasionally I need to compare the contents of two different files to determine if there is any difference, and what those differences are. This is outside of source-controlled files (that have their own tools for seeing diffs). If no differences exist, the output of this command is nothing. If there are diffs, it will list all the differences between both files in the console output.

Compare-Object (Get-Content one.txt) (Get-Content two.txt)