PowerShell Scripting Cheatsheet
Input/Output | Objects Everywhere | String Quotes |
#Basic Input/Output
$Name = Read-Host "Your Name Plz"
Write-Host "Hello $Name"
|
$my_string = "Hello"
$my_string.Length #=> 5
$my_string.ToUpper() #=> HELLO
|
$NAME="John"
Write-Host "Hi $NAME" #=> Hi John
Write-Host 'Hi $NAME' #=> Hi $NAME
|
# Conditional Structure
if-else | switch-case | expressions |
if($expression -eq $true){
Write-Host "Cond. True"
}
elseif{
Write-Host "2nd True"
}
else{
Write-Host "Cond. False"
}
|
switch ($x)
{
'value1' {}
{$_ -in 'A','B','C'} {}
'value3' {}
Default {}
}
|
$true #=> True
1 #=> True
$null #=> False
$empty = "" #=> False
CmdLet-ReturnsFalse #=> False
|
# Loop Structure
do-while | do-until | For Loop | ForEach Loop |
do
{
# Code
}
while ($x -gt 0)
|
do
{
# Code
}
until ($x -gt 0)
|
for ($i = 1; $i -lt 99; $i++){
# Code
}
|
foreach($item in $collection){
Write-Output $item
}
|
# Arrays
Defining Arrays | Working with Arrays |
$my_numbers = 1..100
$Fruits = 'Apple', 'Banana', 'Orange'
$Fruits = @('Apple', 'Banana', 'Orange')
$Fruits[0] = "Apple"
$Fruits[1] = "Banana"
$Fruits[2] = "Orange"
|
Write-Host $Fruits[0] # Element #0
Write-Host $Fruits.Count # Number of elements
Write-Host $Fruits[0].Length # String length of the 1st element
Write-Host $Fruits[0..1] # Array from first to Nth element
Write-Host $Fruits[-2] # Second last element of the Array
|
Hash Table or Dictionary |
$my_vm_config = @{
"hostname" = "vm00002314";
"pvt_ip" = "10.48.3.12";
"domain"= "vikiscripts.github.io"
}
Write-Host $my_vm_config.pvt_ip #=> 10.48.3.12
|
# Execute PowerShell Script from GitHub
Execute a Remote Script |
</td>
iex ((New-Object System.Net.WebClient).DownloadString('https://gist.githubusercontent.com/hclpandv/76739cc615f3eee0d4722243379d324f/raw/9573fa17aadee9f0b5fb71d38cccefde8b4a220b/CheckSumCalc.ps1'))
| </tr>