if ((-not [string]::IsNullOrEmpty($string))) { ... }
if (($nr -gt 5) -and ($string -eq '')) { ... }
switch ($exitCode) {
0 { break }
1 { throw "Error!" }
2 { throw "Another error!" }
default { throw "That's unexpected!" }
}
try {
throw "My exception"
} catch {
Write-Output "Caught exception!"
}
function My-Function {
param (
[string]$param1,
[string]$param2
)
# Code comes here
}
Fetching
$tmp = $env:SOME_ENV_VAR
$env:Path = [Environment]::GetEnvironmentVariable('Path',[System.EnvironmentVariableTarget]::Machine)
Setting env var on global level
[System.Environment]::SetEnvironmentVariable('MYVAR','some value', [System.EnvironmentVariableTarget]::Machine)
Building a filename
$filename = Join-Path $directory 'some.exe'
Checking for a file
if (!(Test-Path $myfile -PathType Leaf)) {
}
Create directory
New-Item "$mydir" -ItemType Directory -Force
Removing files/directories
Remove-Item "$somepath" -Force -Recurse
Set-ExecutionPolicy Bypass -Scope Process -Force
Set-ExecutionPolicy RemoteSigned -Scope CurrentUser
Invoke-WebRequest -useb http://example.com/somefile
Invoke-WebRequest -useb http://example.com/someexe | Invoke-Expression # Download and execute it
if ($PSVersionTable.PSVersion.Major -lt 5) {
# ...
}
$env:https_proxy='<server>:<port>'