Powershell Essential Commands
Essential Commands
Variables, Functions, Arrays and Loops
Variables: $a , $b
Operators: -replace, -in, -ne, -eq, -le, -ge, -gt, -lt, -match, -join eg: "wel", "in" -join "come", -split, -is, -as, -and, -or etc
Types : $a="sahil" $a.GetType()
Here String: @" Hello World "@
Type Casting/Conversion: $a=2+3.33 [int] $a returns 5
Array: $array=1,2,3,4 $array.length , $array[0] etc / empty array $emptyarray=@() /
Loops: For, foreach, While /Loop-cmdlet: ForEach-Object , Where-Object /
Get-Process | ForEach-Object {$_.Name} // similar to Get-Process |ft Name //
Get-ChildItem | Where-Object {$_.Name -match "ss.txt"}
String Comparison
$FirstName = 'Trevor'
$FirstName -like 'T*' # Perform string comparison using the -like operator, which supports the wildcard (*) character. Returns $true
Operators
$a = 2 # Basic variable assignment operator
$a += 1 # Incremental assignment operator
$a -= 1 # Decrement assignment operator
$a -eq 0 # Equality comparison operator
$a -ne 5 # Not-equal comparison operator
$a -gt 2 # Greater than comparison operator
$a -lt 3 # Less than comparison operator
Function Example
function add($a,$b) {
$a+$b
}
// You can Directly call function without parenthesis like : add 1 2 //
SWITCH:
function add($a,$b,[switch]$file) {
if($file) { $a-$b } ; puts a value in b and b value in a
$a+$b
}
Regular Expressions
'Trevor' -match '^T\w*' # Perform a regular expression match against a string value. # Returns $true and populates $matches variable
$matches[0] # Returns 'Trevor', based on the above match
@('Trevor', 'Billy', 'Bobby') -match '^B' # Perform a regular expression match against an array of string values. Returns Billy, Bobby
Flow Control
if (1 -eq 1) { } # Do something if 1 is equal to 1
do { 'hi' } while ($false) # Loop while a condition is true (always executes at least once)
while ($false) { 'hi' } # While loops are not guaranteed to run at least once
while ($true) { } # Do something indefinitely
while ($true) { if (1 -eq 1) { break } } # Break out of an infinite while loop conditionally
for ($i = 0; $i -le 10; $i++) { Write-Host $i } # Iterate using a for..loop
foreach ($item in (Get-Process)) { } # Iterate over items in an array
switch ('test') { 'test' { 'matched'; break } } # Use the switch statement to perform actions based on conditions. Returns string 'matched'
switch -regex (@('Trevor', 'Daniel', 'Bobby')) { # Use the switch statement with regular expressions to match inputs
'o' { $PSItem; break } # NOTE: $PSItem or $_ refers to the "current" item being matched in the array
}
switch -regex (@('Trevor', 'Daniel', 'Bobby')) { # Switch statement omitting the break statement. Inputs can be matched multiple times, in this scenario.
'e' { $PSItem }
'r' { $PSItem }
}
Working with Modules
Get-Command -Name *module* -Module mic*core # Which commands can I use to work with modules?
Get-Module -ListAvailable # Show me all of the modules installed on my system (controlled by $env:PSModulePath)
Get-Module # Show me all of the modules imported into the current session
$PSModuleAutoLoadingPreference = 0 # Disable auto-loading of installed PowerShell modules, when a command is invoked
Import-Module -Name NameIT # Explicitly import a module, from the specified filesystem path or name (must be present in $env:PSModulePath)
Remove-Module -Name NameIT # Remove a module from the scope of the current PowerShell session
New-ModuleManifest # Helper function to create a new module manifest. You can create it by hand instead.
New-Module -Name trevor -ScriptBlock { # Create an in-memory PowerShell module (advanced users)
function Add($a,$b) { $a + $b } }
New-Module -Name trevor -ScriptBlock { # Create an in-memory PowerShell module, and make it visible to Get-Module (advanced users)
function Add($a,$b) { $a + $b } } | Import-Module
Module Management
Get-Command -Module PowerShellGet # Explore commands to manage PowerShell modules
Find-Module -Tag cloud # Find modules in the PowerShell Gallery with a "cloud" tag
Find-Module -Name ps* # Find modules in the PowerShell Gallery whose name starts with "PS"
Install-Module -Name NameIT -Scope CurrentUser -Force # Install a module to your personal directory (non-admin)
Install-Module -Name NameIT -Force # Install a module to your personal directory (admin / root)
Install-Module -Name NameIT -RequiredVersion 1.9.0 # Install a specific version of a module
Uninstall-Module -Name NameIT # Uninstall module called "NameIT", only if it was installed via Install-Module
Register-PSRepository -Name <repo> -SourceLocation <uri> # Configure a private PowerShell module registry
Unregister-PSRepository -Name <repo> # Deregister a PowerShell Repository
Filesystem
New-Item -Path c:\test -ItemType Directory # Create a directory
mkdir c:\test2 # Create a directory (short-hand)
New-Item -Path c:\test\myrecipes.txt # Create an empty file
Set-Content -Path c:\test.txt -Value '' # Create an empty file
[System.IO.File]::WriteAllText('testing.txt', '') # Create an empty file using .NET Base Class Library
Remove-Item -Path testing.txt # Delete a file
[System.IO.File]::Delete('testing.txt') # Delete a file using .NET Base Class Library
Windows Management Instrumentation (WMI) (Windows only)
Get-CimInstance -ClassName Win32_BIOS # Retrieve BIOS information
Get-CimInstance -ClassName Win32_DiskDrive # Retrieve information about locally connected physical disk devices
Get-CimInstance -ClassName Win32_PhysicalMemory # Retrieve information about install physical memory (RAM)
Get-CimInstance -ClassName Win32_NetworkAdapter # Retrieve information about installed network adapters (physical + virtual)
Get-CimInstance -ClassName Win32_VideoController # Retrieve information about installed graphics / video card (GPU)
Get-CimClass -Namespace root\cimv2 # Explore the various WMI classes available in the root\cimv2 namespace
Get-CimInstance -Namespace root -ClassName __NAMESPACE # Explore the child WMI namespaces underneath the root\cimv2 namespace