Powershell

Powershell Cheat Sheet

PowerShell is a task automation and configuration management program from Microsoft, consisting of a command-line shell and the associated scripting language.

PowerShell Variables

COMMAND DESCRIPTION
New-Variable var1 Create a new variable var1 without defining its value
Get-Variable my* Lists all variables in use beginning with “my*”
Remove-Variable bad_variable Delete the variable called “bad_variable” 
$var = "string" Assign the value "string" to a variable $var
$a,$b = 0 Assign the value 0 to the variables $a, $b
$a,$b,$c = 'a','b','c' Assign the characters 'a', 'b', 'c' to respectively-named variables
$a,$b = $b,$a Swap the values of the variables $a and $b
$var = [int]5 Force the variable $var to be strongly typed and only admit integer values

PowerShell Parameters

RISK MITIGATION PARAMETER DESCRIPTION EXAMPLE
-Confirm Prompt whether to take action. Creating a new item called test.txt:
ni test.txt -Confirm
-WhatIf Displays what a certain command would do. Removal of an item called test.txt:
del test.txt -WhatIf

Useful PowerShell Commands

COMMAND NAME ALIAS DESCRIPTION
Get-Help Get-Command (None) Display help information about PowerShell command Get-Command (which lists all PowerShell commands).
You may replace Get-Command with any PowerShell command of your choice.
Get-ChildItem dir, ls, gci Lists all files and folders in the current working directory
Get-Location pwd, gl Get the current working directory
Set-Location cd, chdir, sl Sets the current working location to a specified location
Get-Content cat, gc, type Gets the content of the item at the specified location
Copy-Item copy, cp, cpi Copies an item from one location to another
Remove-Item del, erase, rd, ri, rm, rmdir Deletes the specified items
Move-Item mi, move, mv Moves an item from one location to another
New-Item ni Creates a new item
Out-File >, >> Send output to a file.
When you wish to specify parameters, stick to Out-File.
Invoke-WebRequest curl, iwr, wget Get content from a web page on the Internet
Write-Output echo, write Sends the specified objects to the next command in the pipeline.
If Write-Output is the last command in the pipeline, the console displays the objects.
Clear-Host cls, clear Clear console