Round to the Nearest Half
[math]::Round($number * 2, [MidpointRounding]::AwayFromZero) / 2
Elevate Script to Run As Administrator
# Request elevation with administration rights If (-NOT ([Security.Principal.WindowsPrincipal][Security.Principal.WindowsIdentity]::GetCurrent()).IsInRole([Security.Principal.WindowsBuiltInRole] "Administrator")) { $arguments = "& '" + $myinvocation.mycommand.definition + "'" Start-Process powershell -Verb runAs -ArgumentList $arguments Break } else { # Code to run elevated here }
Switch Statement
switch ($value) { 1 {"It is one."} 2 {"It is two."} 3 {"It is three."} 4 {"It is four."} }
If/ElseIf/Else Statement
# If $value equals 1 write True 1, else if it equals 2 write True 2, else write False if($value -eq 1){ Write-Host "True 1" } elseif($value -eq 2){ Write-Host "True 2" } else { Write-Host "False" }
If/Else Statement
# If $value equals 1 write True, else write False if($value -eq 1){ Write-Host "True" } else { Write-Host "False" }
Run Multiple Commands on Remote Machine
# Create a persistent connection to remote machine $Session = New-PSSession -ComputerName $Computer -Credential $Credential # Runs on remote machine Invoke-Command -Session $Session -ScriptBlock {Stop-Service -Name Bits} # Run on local machine Get-Service # Runs on remote machine again Invoke-Command -Session $Session -ScriptBlock {Start-Service -Name Bits}
Run Command on Remote Machine with Credentials
$Credential = Get-Credential Invoke-Command -ComputerName $Computer -ScriptBlock {Stop-Service -Name Bits} -Credential $Credential
Run Command on Remote Machine
$Credential = Get-Credential Invoke-Command -ComputerName $Computer -ScriptBlock {Stop-Service -Name Bits}