PowerShell

Boilerplate

Searching each file in a directory for a pattern

gci -Recurse | foreach { sls -InputObject $_ -Pattern "somePattern" }

Searching for the name of a file within a directory

gci -Recurse | foreach { $_.FullName | sls "somePattern" }

Execute a command 100 times (for-loop)

foreach ($i in (1 .. 100)) { echo $i }

Files

History file

PSReadLine maintains a history file containing all the commands and data you have entered from the command line. The history files is a file named $($host.Name)_history.txt. On Windows systems the history file is stored at $env:APPDATA\Microsoft\Windows\PowerShell\PSReadLine. On non-Windows systems, the history files is stored at $env:XDG_DATA_HOME/powershell/PSReadLine or $env:HOME/.local/share/powershell/PSReadLine.

Scripting

Invoking a script block inline

Use Invoke-Command -ScriptBlock
Example:

Invoke-Command -ScriptBlock {
  $Text = Get-Content myfile.txt
  foreach ($i in (1 .. 100)) { Add-Content mylist.txt "$i,$Text" }
}

Getting the exit code

In powershell, the exit code is stored in $LASTEXITCODE.
Example:

bcp dbo.TABLE in data.csv -f format.xml -S database.server.com -d my_database -G -T
if ($LASTEXITCODE == 0) {
  echo "Successfully uploaded data to SQL server, proceeding with action X..."
  actionx
} else {
  echo "Error when uploading data to SQL server. Quitting"
  exit 1
}

Get the path of the currently executing script

$MyInvocation.MyCommand.Path
This gives the full path.

Defining parameters for a .ps1 script

param (
  $InputFile = $(throw "Need an input file!"),
  $Directory = $(Split-Path $MyInvocation.MyCommand.Path -Parent),
  $OutputFile = "DefaultOutput.txt"
)
Get-Content "$Directory/$InputFile" > $OutputFile

Remoting

Copying files

From remote to local

$Session = New-PSSession -ComputerName "windowsserver01.intra.net" -Credential "FOO\bar"
Copy-Item "C:\Users\bar\myfile.txt" -Destination myfile.txt -FromSession $Session

From local to remote

$Session = New-PSSession -ComputerName "windowsserver01.intra.net" -Credential "FOO\bar"
Copy-Item myfile.txt -Destination "C:\Users\bar\myfile.txt" -ToSession $Session

By specifying both FromSession and ToSession, you can issue a command that copies from one remote to another.

Sessions

Creating a session

$Session = New-PSSession -ComputerName "windowsserver01.intra.net" -Credential "FOO\bar"

Invoking a command in a session

Invoke-Command -Session $Session -ScriptBlock { Get-Location } # Get the working directory of the session
# You can also invoke a remote command by creating a temporary session with ComputerName
Invoke-Command -ComputerName "windowsserver01.intra.net" -Credential "FOO\bar" -ScriptBlock { Get-Location }

Interactive sessions

# Use an existing session
Enter-PSSession -Session $Session
# Create a temporary session and enter it
Enter-PSSession -ComputerName "windowsserver01.intra.net" -Credential "FOO\bar"
# Exiting the interactive session can be done using the 'exit' command

Removing a session

# Disconnect the session, you can connect to it again with Connect-PSSession
Disconnect-PSSession -Session $Session
# Remove the session, releasing all resources it was using
Remove-PSSession -Session $Session

Security

Secure Strings

Creating a secure string from keyboard input

$password = Read-Host -AsSecureString
*****************
# $password now contains the typed in password as a secure string

Using a secure string with supported commandlets

# New-LocalUser takes a secure string as the argument to the password
New-LocalUser -Name "tagg" -Password $password

Decrypting a secure string for use with an unsupported commandlet

function Convert-SecureStringToPlainText {
  param ( $SecureString = $(throw "need secure string") )
  $ptr = [System.Runtime.InteropServices.Marshal]::SecureStringToCoTaskMemUnicode($SecureString)
  $result = [System.Runtime.InteropServices.Marshal]::PtrToStringUni($ptr)
  [System.Runtime.InteropServices.Marshal]::ZeroFreeCoTaskMemUnicode($ptr)
  $result
}
$plaintext = Convert-SecureStringToPlainText $password

Storing a secure string as encrypted text

# Store to password.enc
ConvertFrom-SecureString $password | Set-Content password.enc
# Get from password.enc
$password = Get-Content password.enc | ConvertTo-SecureString