powershell_cheat_sheet
This is an old revision of the document!
Table of Contents
Powershell Cheat Sheet
Text Processing
Simple replace (supports regexs)
'1234abcd' -replace '\d', '*' # ****abcd
Simple match (supports regexs)
'123.456.789.123' -match '\d+(?:\.\d+){2}' # returns true if there is a match. $Matches.Values # = '123.456.789'
Filter lines by regex
$inputText = '!! Match me Not me !! Match me too Not me tho' $regex=[regex] '(?m)^!!.+?$' $regex.matches($inputText) | Foreach-Object { $_.Value } # Returns a string, one match per line.
Reformatting by using regex groups
# Filter lines by regex. $inputText = ' .. . . left:10 . .. right:10 ... .. . . left:20 . .. right:20 ... .. . left:30 . . ... .. right:30 ... left:40right:40' -replace "`r`n", "`n" $regex=[regex] '(?m)^[ \.]*(?<left>left:\d+)[ \.]*(?<right>right:\d+)[ \.]*$' $regex.matches($inputText) | Foreach-Object { $_.Groups["left"].value + ' - ' + $_.Groups["right"].value} # Returns a string: #left:10 - right:10 #left:20 - right:20 #left:30 - right:30 #left:40 - right:40
Regex replace with groups
# $1 = group 1, $2 = group 2, etc. '123 456 789' -replace '(\d+ )(\d+)( \d+)', '$1!$2!$3' # = '123 !456! 789'
Searching in files
Get-ChildItem -Recurse -Path C:\Temp -Include *.txt | Select-String 'This', 'OR that' | Select-String 'AND this' | Format-Table -property path, line -autosize | Out-String -Width 4096
Search and replace in a file
(Get-Content $filename) -replace 'heise', 'Heise' | Set-Content $filename
Parameters
param ( [parameter(Mandatory=$true)] [string]$targetServer, [parameter(Mandatory=$true)] [string]$targetWebConfig )
Search installed certs for thumbprint
powershell_cheat_sheet.1568242158.txt.gz · Last modified: 2019/09/12 23:49 (external edit)