PowerShell code fragements
Get current execution environment info
- $ScriptPath = $MyInvocation.MyCommand.Path
- $ScriptDir = split-path -parent $ScriptPath
- $ScriptName = [system.io.path]::GetFilenameWithoutExtension($ScriptPath)
Command line variables
param([type]$param)
Pipeline variables
Param([Parameter(Mandatory=$True,ValueFromPipeline=$True,ValueFromPipelinebyPropertyName=$True)][string[]]$computername)
Error action
- -ErrorAction SilentlyContinue -- per line of code
- $ErrorActionPreference = "SilentlyContinue" -- global
Processing Structure
begin { }process { }
end { }
Create arrays of objects
$report = @()
Create Hash Table
$hash = @{"name" = "value";"name2" = "value2"}
Create object
$temp = "" | Select Computer, Username
To read a whole file in as one string
[Io.File]::ReadAllText($path)
get-content reads it in as an array of strings.
get-content -raw reads it as one string v3
To quickly copy one large file to another
get-content .\infile.txt -readcount 500 | Add-Content .\outfile.txt
The readcount reads 500 lines at a time and sends it down the pipeline instead of 1
get-content .\infile.bin -readcount 500 -encoding byte| Add-Content .\outfile.bin
Use this for a binary file
Get Powershell Version
$PSVersionTable.PSVersion