Saturday, June 30, 2018

Use PowerShell to Search Text Files for Strings

PowerShell can quickly search text files for a string of characters:

Select-String -Path .\servers.txt -Pattern "abc"

 


For this example, we used Select-String to search a list of server names in a text file called 'servers.txt', then used the -Pattern parameter to designate the string we're looking for.

PowerShell returned the filename, the line number where the pattern was found, and the full line. 

Note: case is not sensitive here. A search for "ABC" will return the same result. 
 

Use PowerShell to create a Zip archive

PowerShell can easily create zip archives of files and folders using the Write-Zip cmdlet.

Get-ChildItem C:\MyScripts\*.ps1 | Write-Zip -OutputPath C:\Temp\PS-scripts.zip

Here we zipped up all the PowerShell scripts written or downloaded for archive purposes:



Get-ChildItem also has a -Recurse parameter if we want to zip up subfolders, and the Write-Zip cmdlet has a -IncludeEmptyDirectories parameter if we want to, well, include empty directories.

Friday, June 8, 2018

Use PowerShell to Multiply Strings

Long, long ago, computers mastered the art of multiplying numbers. A more interesting trick is to multiply string. PowerShell can do this easily:

"winner " * 3







Note the trailing space at the end of the string. Without it, the text would all run together in an unbroken line.

 

Use PowerShell to send a Beep to the Console

PowerShell can send beeps to the console:

[console]::beep[500,300]

It's nice to throw two or three of these at the end of a long-running script to alert when the script is finished.

The first number is the pitch of the beep, and the second number is the duration of the beep in milliseconds.