{"id":9626,"date":"2023-08-07T14:26:24","date_gmt":"2023-08-07T12:26:24","guid":{"rendered":"https:\/\/via-internet.de\/blog\/?p=9626"},"modified":"2023-08-07T17:15:36","modified_gmt":"2023-08-07T15:15:36","slug":"power-shell-cheatsheet","status":"publish","type":"post","link":"https:\/\/via-internet.de\/blog\/2023\/08\/07\/power-shell-cheatsheet\/","title":{"rendered":"Power Shell | Cheat Sheets"},"content":{"rendered":"\n<h2 class=\"wp-block-heading\">Cheat Sheet 1<\/h2>\n\n\n\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"powershell\" data-enlighter-theme=\"\" data-enlighter-highlight=\"\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\">Get-Command                                    # List of all the commands available to PowerShell\n                                               # (native binaries in $env:PATH + cmdlets \/ functions from PowerShell modules)\nGet-Command -Module Microsoft*                 # Lst of all the PowerShell commands exported from modules named Microsoft*\nGet-Command -Name *item                        # List of all commands ending in \"item\"\n\nGet-Help                                       # Get all help topics\nGet-Help -Name about_Variables                 # Get help for a specific about_* topic (aka. man page)\nGet-Help -Name Get-Command                     # Get help for a specific PowerShell function\nGet-Help -Name Get-Command -Parameter Module   # Get help for a specific parameter on a specific command<\/pre>\n\n\n\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"powershell\" data-enlighter-theme=\"\" data-enlighter-highlight=\"\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\">###################################################\n# Operators\n###################################################\n\n$a = 2                                                    # Basic variable assignment operator\n$a += 1                                                   # Incremental assignment operator\n$a -= 1                                                   # Decrement assignment operator\n\n$a -eq 0                                                  # Equality comparison operator\n$a -ne 5                                                  # Not-equal comparison operator\n$a -gt 2                                                  # Greater than comparison operator\n$a -lt 3                                                  # Less than comparison operator\n\n$FirstName = 'Trevor'\n$FirstName -like 'T*'                                     # Perform string comparison using the -like operator, which supports the wildcard (*) character. Returns $true\n\n$BaconIsYummy = $true\n$FoodToEat = $BaconIsYummy ? 'bacon' : 'beets'            # Sets the $FoodToEat variable to 'bacon' using the ternary operator\n\n'Celery' -in @('Bacon', 'Sausage', 'Steak', 'Chicken')    # Returns boolean value indicating if left-hand operand exists in right-hand array\n'Celery' -notin @('Bacon', 'Sausage', 'Steak')            # Returns $true, because Celery is not part of the right-hand list\n\n5 -is [string]                                            # Is the number 5 a string value? No. Returns $false.\n5 -is [int32]                                             # Is the number 5 a 32-bit integer? Yes. Returns $true.\n5 -is [int64]                                             # Is the number 5 a 64-bit integer? No. Returns $false.\n'Trevor' -is [int64]                                      # Is 'Trevor' a 64-bit integer? No. Returns $false.\n'Trevor' -isnot [string]                                  # Is 'Trevor' NOT a string? No. Returns $false.\n'Trevor' -is [string]                                     # Is 'Trevor' a string? Yes. Returns $true.\n$true -is [bool]                                          # Is $true a boolean value? Yes. Returns $true.\n$false -is [bool]                                         # Is $false a boolean value? Yes. Returns $true.\n5 -is [bool]                                              # Is the number 5 a boolean value? No. Returns $false.\n\/pre><\/pre>\n\n\n\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"powershell\" data-enlighter-theme=\"\" data-enlighter-highlight=\"\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\">###################################################\n# Regular Expressions\n###################################################\n\n'Trevor' -match '^T\\w*'                                   # Perform a regular expression match against a string value. # Returns $true and populates $matches variable\n$matches[0]                                               # Returns 'Trevor', based on the above match\n\n@('Trevor', 'Billy', 'Bobby') -match '^B'                 # Perform a regular expression match against an array of string values. Returns Billy, Bobby\n\n$regex = [regex]'(\\w{3,8})'\n$regex.Matches('Trevor Bobby Dillon Joe Jacob').Value     # Find multiple matches against a singleton string value.\n\/pre><\/pre>\n\n\n\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"powershell\" data-enlighter-theme=\"\" data-enlighter-highlight=\"\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\">###################################################\n# Flow Control\n###################################################\n\nif (1 -eq 1) { }                                          # Do something if 1 is equal to 1\n\ndo { 'hi' } while ($false)                                # Loop while a condition is true (always executes at least once)\n\nwhile ($false) { 'hi' }                                   # While loops are not guaranteed to run at least once\nwhile ($true) { }                                         # Do something indefinitely\nwhile ($true) { if (1 -eq 1) { break } }                  # Break out of an infinite while loop conditionally\n\nfor ($i = 0; $i -le 10; $i++) { Write-Host $i }           # Iterate using a for..loop\nforeach ($item in (Get-Process)) { }                      # Iterate over items in an array\n\nswitch ('test') { 'test' { 'matched'; break } }           # Use the switch statement to perform actions based on conditions. Returns string 'matched'\nswitch -regex (@('Trevor', 'Daniel', 'Bobby')) {          # Use the switch statement with regular expressions to match inputs\n  'o' { $PSItem; break }                                  # NOTE: $PSItem or $_ refers to the \"current\" item being matched in the array\n}\nswitch -regex (@('Trevor', 'Daniel', 'Bobby')) {          # Switch statement omitting the break statement. Inputs can be matched multiple times, in this scenario.\n  'e' { $PSItem }\n  'r' { $PSItem }\n}\n\/pre><\/pre>\n\n\n\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"powershell\" data-enlighter-theme=\"\" data-enlighter-highlight=\"\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\">###################################################\n# Variables\n###################################################\n\n\n$a = 0                                                    # Initialize a variable\n[int] $a = 'Trevor'                                       # Initialize a variable, with the specified type (throws an exception)\n[string] $a = 'Trevor'                                    # Initialize a variable, with the specified type (doesn't throw an exception)\n\nGet-Command -Name *varia*                                 # Get a list of commands related to variable management\n\nGet-Variable                                              # Get an array of objects, representing the variables in the current and parent scopes \nGet-Variable | ? { $PSItem.Options -contains 'constant' } # Get variables with the \"Constant\" option set\nGet-Variable | ? { $PSItem.Options -contains 'readonly' } # Get variables with the \"ReadOnly\" option set\n\nNew-Variable -Name FirstName -Value Trevor\nNew-Variable FirstName -Value Trevor -Option Constant     # Create a constant variable, that can only be removed by restarting PowerShell\nNew-Variable FirstName -Value Trevor -Option ReadOnly     # Create a variable that can only be removed by specifying the -Force parameter on Remove-Variable\n\nRemove-Variable -Name firstname                           # Remove a variable, with the specified name\nRemove-Variable -Name firstname -Force                    # Remove a variable, with the specified name, that has the \"ReadOnly\" option set\n\/pre><\/pre>\n\n\n\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"powershell\" data-enlighter-theme=\"\" data-enlighter-highlight=\"\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\">###################################################\n# Functions\n###################################################\n\nfunction add ($a, $b) { $a + $b }                         # A basic PowerShell function\n\nfunction Do-Something {                                   # A PowerShell Advanced Function, with all three blocks declared: BEGIN, PROCESS, END\n  [CmdletBinding]()]\n  param ()\n  begin { }\n  process { }\n  end { }\n}\n\/pre><\/pre>\n\n\n\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"powershell\" data-enlighter-theme=\"\" data-enlighter-highlight=\"\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\">###################################################\n# Working with Modules\n###################################################\n\nGet-Command -Name *module* -Module mic*core                 # Which commands can I use to work with modules?\n\nGet-Module -ListAvailable                                   # Show me all of the modules installed on my system (controlled by $env:PSModulePath)\nGet-Module                                                  # Show me all of the modules imported into the current session\n\n$PSModuleAutoLoadingPreference = 0                          # Disable auto-loading of installed PowerShell modules, when a command is invoked\n\nImport-Module -Name NameIT                                  # Explicitly import a module, from the specified filesystem path or name (must be present in $env:PSModulePath)\nRemove-Module -Name NameIT                                  # Remove a module from the scope of the current PowerShell session\n\nNew-ModuleManifest                                          # Helper function to create a new module manifest. You can create it by hand instead.\n\nNew-Module -Name trevor -ScriptBlock {                      # Create an in-memory PowerShell module (advanced users)\n  function Add($a,$b) { $a + $b } }\n\nNew-Module -Name trevor -ScriptBlock {                      # Create an in-memory PowerShell module, and make it visible to Get-Module (advanced users)\n  function Add($a,$b) { $a + $b } } | Import-Module\n\/pre><\/pre>\n\n\n\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"powershell\" data-enlighter-theme=\"\" data-enlighter-highlight=\"\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\">###################################################\n# Module Management\n###################################################\n\nGet-Command -Module PowerShellGet                           # Explore commands to manage PowerShell modules\n\nFind-Module -Tag cloud                                      # Find modules in the PowerShell Gallery with a \"cloud\" tag\nFind-Module -Name ps*                                       # Find modules in the PowerShell Gallery whose name starts with \"PS\"\n\nInstall-Module -Name NameIT -Scope CurrentUser -Force       # Install a module to your personal directory (non-admin)\nInstall-Module -Name NameIT -Force                          # Install a module to your personal directory (admin \/ root)\nInstall-Module -Name NameIT -RequiredVersion 1.9.0          # Install a specific version of a module\n\nUninstall-Module -Name NameIT                               # Uninstall module called \"NameIT\", only if it was installed via Install-Module\n\nRegister-PSRepository -Name &lt;repo> -SourceLocation &lt;uri>    # Configure a private PowerShell module registry\nUnregister-PSRepository -Name &lt;repo>                        # Deregister a PowerShell Repository\n\/pre><\/pre>\n\n\n\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"powershell\" data-enlighter-theme=\"\" data-enlighter-highlight=\"\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\">\n###################################################\n# Filesystem\n###################################################\n\nNew-Item -Path c:\\test -ItemType Directory                  # Create a directory\nmkdir c:\\test2                                              # Create a directory (short-hand)\n\nNew-Item -Path c:\\test\\myrecipes.txt                        # Create an empty file\nSet-Content -Path c:\\test.txt -Value ''                     # Create an empty file\n[System.IO.File]::WriteAllText('testing.txt', '')           # Create an empty file using .NET Base Class Library\n\nRemove-Item -Path testing.txt                               # Delete a file\n[System.IO.File]::Delete('testing.txt')                     # Delete a file using .NET Base Class Library\n\/pre><\/pre>\n\n\n\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"powershell\" data-enlighter-theme=\"\" data-enlighter-highlight=\"\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\">###################################################\n# Hashtables (Dictionary)\n###################################################\n\n$Person = @{\n  FirstName = 'Trevor'\n  LastName = 'Sullivan'\n  Likes = @(\n    'Bacon',\n    'Beer',\n    'Software'\n  )\n}                                                           # Create a PowerShell HashTable\n\n$Person.FirstName                                           # Retrieve an item from a HashTable\n$Person.Likes[-1]                                           # Returns the last item in the \"Likes\" array, in the $Person HashTable (software)\n$Person.Age = 50                                            # Add a new property to a HashTable\n\/pre><\/pre>\n\n\n\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"powershell\" data-enlighter-theme=\"\" data-enlighter-highlight=\"\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\">###################################################\n# Windows Management Instrumentation (WMI) (Windows only)\n###################################################\n\nGet-CimInstance -ClassName Win32_BIOS                       # Retrieve BIOS information\nGet-CimInstance -ClassName Win32_DiskDrive                  # Retrieve information about locally connected physical disk devices\nGet-CimInstance -ClassName Win32_PhysicalMemory             # Retrieve information about install physical memory (RAM)\nGet-CimInstance -ClassName Win32_NetworkAdapter             # Retrieve information about installed network adapters (physical + virtual)\nGet-CimInstance -ClassName Win32_VideoController            # Retrieve information about installed graphics \/ video card (GPU)\n\nGet-CimClass -Namespace root\\cimv2                          # Explore the various WMI classes available in the root\\cimv2 namespace\nGet-CimInstance -Namespace root -ClassName __NAMESPACE      # Explore the child WMI namespaces underneath the root\\cimv2 namespace\n\/pre><\/pre>\n\n\n\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"powershell\" data-enlighter-theme=\"\" data-enlighter-highlight=\"\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\">\n\n###################################################\n# Asynchronous Event Registration\n###################################################\n\n#### Register for filesystem events\n$Watcher = [System.IO.FileSystemWatcher]::new('c:\\tmp')\nRegister-ObjectEvent -InputObject $Watcher -EventName Created -Action {\n  Write-Host -Object 'New file created!!!'\n}                                                           \n\n#### Perform a task on a timer (ie. every 5000 milliseconds)\n$Timer = [System.Timers.Timer]::new(5000)\nRegister-ObjectEvent -InputObject $Timer -EventName Elapsed -Action {\n  Write-Host -ForegroundColor Blue -Object 'Timer elapsed! Doing some work.'\n}\n$Timer.Start()\n\/pre><\/pre>\n\n\n\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"powershell\" data-enlighter-theme=\"\" data-enlighter-highlight=\"\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\">###################################################\n# PowerShell Drives (PSDrives)\n###################################################\n\nGet-PSDrive                                                 # List all the PSDrives on the system\nNew-PSDrive -Name videos -PSProvider Filesystem -Root x:\\data\\content\\videos  # Create a new PSDrive that points to a filesystem location\nNew-PSDrive -Name h -PSProvider FileSystem -Root '\\\\storage\\h$\\data' -Persist # Create a persistent mount on a drive letter, visible in Windows Explorer\nSet-Location -Path videos:                                  # Switch into PSDrive context\nRemove-PSDrive -Name xyz                                    # Delete a PSDrive\n\/pre><\/pre>\n\n\n\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"powershell\" data-enlighter-theme=\"\" data-enlighter-highlight=\"\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\">###################################################\n# Data Management\n###################################################\n\nGet-Process | Group-Object -Property Name                   # Group objects by property name\nGet-Process | Sort-Object -Property Id                      # Sort objects by a given property name\nGet-Process | Where-Object -FilterScript { $PSItem.Name -match '^c' } # Filter objects based on a property matching a value\ngps | where Name -match '^c'                                # Abbreviated form of the previous statement\n\/pre><\/pre>\n\n\n\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"powershell\" data-enlighter-theme=\"\" data-enlighter-highlight=\"\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\">###################################################\n# PowerShell Classes\n###################################################\n\nclass Person {\n  [string] $FirstName                                       # Define a class property as a string\n  [string] $LastName = 'Sullivan'                           # Define a class property with a default value\n  [int] $Age                                                # Define a class property as an integer\n  \n  Person() {                                                # Add a default constructor (no input parameters) for a class\n  }\n  \n  Person([string] $FirstName) {                             # Define a class constructor with a single string parameter\n    $this.FirstName = $FirstName\n  }\n  \n  [string] FullName() {\n    return '{0} {1}' -f $this.FirstName, $this.LastName\n  }\n}\n$Person01 = [Person]::new()                                 # Instantiate a new Person object.\n$Person01.FirstName = 'Trevor'                              # Set the FirstName property on the Person object.\n$Person01.FullName()                                        # Call the FullName() method on the Person object. Returns 'Trevor Sullivan'\n\n\nclass Server {                                              # Define a \"Server\" class, to manage remote servers. Customize this based on your needs.\n  [string] $Name\n  [System.Net.IPAddress] $IPAddress                         # Define a class property as an IPaddress object\n  [string] $SSHKey = \"$HOME\/.ssh\/id_rsa\"                    # Set the path to the private key used to authenticate to the server\n  [string] $Username                                        # Set the username to login to the remote server with\n  \n  RunCommand([string] $Command) {                           # Define a method to call a command on the remote server, via SSH\n    ssh -i $this.SSHKey $this.Username@$this.Name $this.Command\n  }\n}\n\n$Server01 = [Server]::new()                                 # Instantiate the Server class as a new object\n$Server01.Name = 'webserver01.local'                        # Set the \"name\" of the remote server\n$Server01.Username = 'root'                                 # Set the username property of the \"Server\" object\n$Server01.RunCommand(\"hostname\")                            # Run a command on the remote server\n\/pre><\/pre>\n\n\n\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"powershell\" data-enlighter-theme=\"\" data-enlighter-highlight=\"\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\">###################################################\n# REST APIs\n###################################################\n\n$Params = @{\n  Uri = 'https:\/\/api.github.com\/events'\n  Method = 'Get'\n}\nInvoke-RestMethod @Params                                   # Call a REST API, using the HTTP GET method\n<\/pre>\n\n\n\n<h2 class=\"wp-block-heading\">Learning Powershell in 5 Minutes<\/h2>\n\n\n\n<h3 class=\"wp-block-heading\">Comments<\/h3>\n\n\n\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\" data-enlighter-theme=\"\" data-enlighter-highlight=\"\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\"># Single line comments start with a number symbol.\n\n&lt;#\n  Multi-line comments\n  like so\n#>\n\/pre><\/pre>\n\n\n\n<h3 class=\"wp-block-heading\">Primitive Datatypes and Operators<\/h3>\n\n\n\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\" data-enlighter-theme=\"\" data-enlighter-highlight=\"\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\">####################################################\n## 1. Primitive Datatypes and Operators\n####################################################\n\n# Numbers\n3 # => 3\n\n# Math\n1 + 1   # => 2\n8 - 1   # => 7\n10 * 2  # => 20\n35 \/ 5  # => 7.0\n\n# Powershell uses banker's rounding,\n# meaning [int]1.5 would round to 2 but so would [int]2.5\n# Division always returns a float. \n# You must cast result to [int] to round.\n[int]5 \/ [int]3       # => 1.66666666666667\n[int]-5 \/ [int]3      # => -1.66666666666667\n5.0 \/ 3.0   # => 1.66666666666667\n-5.0 \/ 3.0  # => -1.66666666666667\n[int]$result = 5 \/ 3 \n$result # => 2\n\n# Modulo operation\n7 \n\n# Exponentiation requires longform or the built-in [Math] class.\n[Math]::Pow(2,3)  # => 8\n\n# Enforce order of operations with parentheses.\n1 + 3 * 2  # => 7\n(1 + 3) * 2  # => 8\n\n# Boolean values are primitives (Note: the $)\n$True  # => True\n$False  # => False\n\n# negate with !\n!$True   # => False\n!$False  # => True\n\n# Boolean Operators\n# Note \"-and\" and \"-or\" usage\n$True -and $False  # => False\n$False -or $True   # => True\n\n# True and False are actually 1 and 0 but only support limited arithmetic.\n# However, casting the bool to int resolves this.\n$True + $True # => 2\n$True * 8    # => '[System.Boolean] * [System.Int32]' is undefined\n[int]$True * 8 # => 8\n$False - 5   # => -5\n\n# Comparison operators look at the numerical value of True and False.\n0 -eq $False  # => True\n1 -eq $True   # => True\n2 -eq $True   # => False\n-5 -ne $False # => True\n\n# Using boolean logical operators on ints casts to booleans for evaluation.\n# but their non-cast value is returned\n# Don't mix up with bool(ints) and bitwise -band\/-bor\n[bool](0)     # => False\n[bool](4)     # => True\n[bool](-6)    # => True\n0 -band 2     # => 0\n-5 -bor 0     # => -5\n\n# Equality is -eq (equals)\n1 -eq 1  # => True\n2 -eq 1  # => False\n\n# Inequality is -ne (notequals)\n1 -ne 1  # => False\n2 -ne 1  # => True\n\n# More comparisons\n1 -lt 10  # => True\n1 -gt 10  # => False\n2 -le 2  # => True\n2 -ge 2  # => True\n\n# Seeing whether a value is in a range\n1 -lt 2 -and 2 -lt 3  # => True\n2 -lt 3 -and 3 -lt 2  # => False\n\n# (-is vs. -eq) -is checks if two objects are the same type.\n# -eq checks if the objects have the same values.\n# Note: we called '[Math]' from .NET previously without the preceeding\n# namespaces. We can do the same with [Collections.ArrayList] if preferred.\n[System.Collections.ArrayList]$a = @()  # Point a at a new list\n$a = (1,2,3,4)\n$b = $a                                 # => Point b at what a is pointing to\n$b -is $a.GetType()                     # => True, a and b equal same type\n$b -eq $a                               # => True, a and b values are equal\n[System.Collections.Hashtable]$b = @{}  # => Point a at a new hash table\n$b = @{'one' = 1 \n       'two' = 2}\n$b -is $a.GetType()                     # => False, a and b types not equal\n\n# Strings are created with \" or ' but \" is required for string interpolation\n\"This is a string.\"\n'This is also a string.'\n\n# Strings can be added too! But try not to do this.\n\"Hello \" + \"world!\"  # => \"Hello world!\"\n\n# A string can be treated like a list of characters\n\"Hello world!\"[0]  # => 'H'\n\n# You can find the length of a string\n(\"This is a string\").Length  # => 16\n\n# You can also format using f-strings or formatted string literals.\n$name = \"Steve\"\n$age = 22\n\"He said his name is $name.\" \n# => \"He said his name is Steve\"\n\"{0} said he is {1} years old.\" -f $name, $age \n# => \"Steve said he is 22 years old\"\n\"$name's name is $($name.Length) characters long.\" \n# => \"Steve's name is 5 characters long.\"\n\n# Escape Characters in Powershell\n# Many languages use the '\\', but Windows uses this character for \n# file paths. Powershell thus uses '`' to escape characters\n# Take caution when working with files, as '`' is a\n# valid character in NTFS filenames.\n\"Showing`nEscape Chars\" # => new line between Showing and Escape\n\"Making`tTables`tWith`tTabs\" # => Format things with tabs\n\n# Negate pound sign to prevent comment\n# Note that the function of '#' is removed, but '#' is still present\n`#Get-Process # => Fail: not a recognized cmdlet\n\n# $null is not an object\n$null  # => None\n\n# $null, 0, and empty strings and arrays all evaluate to False.\n# All other values are True\nfunction Test-Value ($value) {\n  if ($value) {\n    Write-Output 'True'\n  }\n  else {\n    Write-Output 'False'\n  }\n}\n\nTest-Value ($null) # => False\nTest-Value (0)     # => False\nTest-Value (\"\")    # => False\nTest-Value []      # => True \n# *[] calls .NET class; creates '[]' string when passed to function\nTest-Value ({})    # => True\nTest-Value @()     # => False\n\n\/pre><\/pre>\n\n\n\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"powershell\" data-enlighter-theme=\"\" data-enlighter-highlight=\"\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\">####################################################\n## 2. Variables and Collections\n####################################################\n\n# Powershell uses the \"Write-Output\" function to print\nWrite-Output \"I'm Posh. Nice to meet you!\"  # => I'm Posh. Nice to meet you!\n\n# Simple way to get input data from console\n$userInput = Read-Host \"Enter some data: \" # Returns the data as a string\n\n# There are no declarations, only assignments.\n# Convention is to use camelCase or PascalCase, whatever your team uses.\n$someVariable = 5\n$someVariable  # => 5\n\n# Accessing a previously unassigned variable does not throw exception.\n# The value is $null by default\n\n# Ternary Operators exist in Powershell 7 and up\n0 ? 'yes' : 'no'  # => no\n\n\n# The default array object in Powershell is an fixed length array.\n$defaultArray = \"thing\",\"thing2\",\"thing3\"\n# you can add objects with '+=', but cannot remove objects.\n$defaultArray.Add(\"thing4\") # => Exception \"Collection was of a fixed size.\"\n# To have a more workable array, you'll want the .NET [ArrayList] class\n# It is also worth noting that ArrayLists are significantly faster\n\n# ArrayLists store sequences\n[System.Collections.ArrayList]$array = @()\n# You can start with a prefilled ArrayList\n[System.Collections.ArrayList]$otherArray = @(4, 5, 6)\n\n# Add to the end of a list with 'Add' (Note: produces output, append to $null)\n$array.Add(1) > $null    # $array is now [1]\n$array.Add(2) > $null    # $array is now [1, 2]\n$array.Add(4) > $null    # $array is now [1, 2, 4]\n$array.Add(3) > $null    # $array is now [1, 2, 4, 3]\n# Remove from end with index of count of objects-1; array index starts at 0\n$array.RemoveAt($array.Count-1) # => 3 and array is now [1, 2, 4]\n# Let's put it back\n$array.Add(3) > $null   # array is now [1, 2, 4, 3] again.\n\n# Access a list like you would any array\n$array[0]   # => 1\n# Look at the last element\n$array[-1]  # => 3\n\n# Looking out of bounds returns nothing\n$array[4]  # blank line returned\n\n# You can look at ranges with slice syntax.\n# The start index is included, the end index is not\n# (It's a closed\/open range for you mathy types.)\n$array[1..3]   # Return array from index 1 to 3 => [2, 4]\n$array[2..-1]    # Return array starting from index 2 => [4, 3]\n$array[0..3]    # Return array from beginning until index 3  => [1, 2, 4]\n$array[0..2]   # Return array selecting every second entry => [1, 4]\n$array.Reverse()  # mutates array to reverse order => [3, 4, 2, 1]\n# Use any combination of these to make advanced slices\n\n# Remove arbitrary elements from a array with \"del\"\n$array.Remove($array[2])  # $array is now [1, 2, 3]\n\n# Insert an element at a specific index\n$array.Insert(1, 2)  # $array is now [1, 2, 3] again\n\n# Get the index of the first item found matching the argument\n$array.IndexOf(2)  # => 1\n$array.IndexOf(6)  # Returns -1 as \"outside array\" \n\n# You can add arrays\n# Note: values for $array and for $otherArray are not modified.\n$array + $otherArray  # => [1, 2, 3, 4, 5, 6]\n\n# Concatenate arrays with \"AddRange()\"\n$array.AddRange($otherArray)  # Now $array is [1, 2, 3, 4, 5, 6]\n\n# Check for existence in a array with \"in\"\n1 -in $array  # => True\n\n# Examine length with \"Count\" (Note: \"Length\" on arrayList = each items length)\n$array.Count  # => 6\n\n\n# Tuples are like arrays but are immutable.\n# To use Tuples in powershell, you must use the .NET tuple class.\n$tuple = [System.Tuple]::Create(1, 2, 3)\n$tuple.Item(0)      # => 1\n$tuple.Item(0) = 3  # Raises a TypeError\n\n# You can do some of the array methods on tuples, but they are limited.\n$tuple.Length       # => 3\n$tuple + (4, 5, 6)  # => Exception\n$tuple[0..2]        # => $null\n2 -in $tuple        # => False\n\n\n# Hashtables store mappings from keys to values, similar to Dictionaries.\n$emptyHash = @{}\n# Here is a prefilled dictionary\n$filledHash = @{\"one\"= 1 \n                \"two\"= 2 \n                \"three\"= 3}\n\n# Look up values with []\n$filledHash[\"one\"]  # => 1\n\n# Get all keys as an iterable with \".Keys\".\n# items maintain the order at which they are inserted into the dictionary.\n$filledHash.Keys  # => [\"one\", \"two\", \"three\"]\n\n# Get all values as an iterable with \".Values\".\n$filledHash.Values  # => [1, 2, 3]\n\n# Check for existence of keys or values in a hash with \"-in\"\n\"one\" -in $filledHash.Keys  # => True\n1 -in $filledHash.Values    # => False\n\n# Looking up a non-existing key returns $null\n$filledHash[\"four\"]  # $null\n\n# Adding to a dictionary\n$filledHash.Add(\"five\",5)  # $filledHash[\"five\"] is set to 5\n$filledHash.Add(\"five\",6)  # exception \"Item with key \"five\" has already been added\"\n$filledHash[\"four\"] = 4 # $filledHash[\"four\"] is set to 4, running again does nothing\n\n# Remove keys from a dictionary with del\n$filledHash.Remove(\"one\") # Removes the key \"one\" from filled dict\n\n\/pre><\/pre>\n\n\n\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"powershell\" data-enlighter-theme=\"\" data-enlighter-highlight=\"\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\">####################################################\n## 3. Control Flow and Iterables\n####################################################\n\n# Let's just make a variable\n$someVar = 5\n\n# Here is an if statement.\n# This prints \"$someVar is smaller than 10\"\nif ($someVar -gt 10) {\n    Write-Output \"$someVar is bigger than 10.\"\n}\nelseif ($someVar -lt 10) {    # This elseif clause is optional.\n    Write-Output \"$someVar is smaller than 10.\"\n}\nelse {                        # This is optional too.\n    Write-Output \"$someVar is indeed 10.\"\n}\n\n\n&lt;#\nForeach loops iterate over arrays\nprints:\n    dog is a mammal\n    cat is a mammal\n    mouse is a mammal\n#>\nforeach ($animal in (\"dog\", \"cat\", \"mouse\")) {\n    # You can use -f to interpolate formatted strings\n    \"{0} is a mammal\" -f $animal\n}\n\n&lt;#\nFor loops iterate over arrays and you can specify indices\nprints:\n   0 a\n   1 b\n   2 c\n   3 d\n   4 e\n   5 f\n   6 g\n   7 h\n#>\n$letters = ('a','b','c','d','e','f','g','h')\nfor($i=0; $i -le $letters.Count-1; $i++){\n    Write-Host $i, $letters[$i]\n}\n\n&lt;#\nWhile loops go until a condition is no longer met.\nprints:\n    0\n    1\n    2\n    3\n#>\n$x = 0\nwhile ($x -lt 4) {\n    Write-Output $x\n    $x += 1  # Shorthand for x = x + 1\n}\n\n# Switch statements are more powerful compared to most languages\n$val = \"20\"\nswitch($val) {\n  { $_ -eq 42 }           { \"The answer equals 42\"; break }\n  '20'                    { \"Exactly 20\"; break }\n  { $_ -like 's*' }       { \"Case insensitive\"; break }\n  { $_ -clike 's*'}       { \"clike, ceq, cne for case sensitive\"; break }\n  { $_ -notmatch '^.*$'}  { \"Regex matching. cnotmatch, cnotlike, ...\"; break }\n  default                 { \"Others\" }\n}\n\n# Handle exceptions with a try\/catch block\ntry {\n    # Use \"throw\" to raise an error\n    throw \"This is an error\"\n}\ncatch {\n    Write-Output $Error.ExceptionMessage\n}\nfinally {\n    Write-Output \"We can clean up resources here\"\n}\n\n\n# Writing to a file\n$contents = @{\"aa\"= 12 \n             \"bb\"= 21}\n$contents | Export-CSV \"$env:HOMEDRIVE\\file.csv\" # writes to a file\n\n$contents = \"test string here\"\n$contents | Out-File \"$env:HOMEDRIVE\\file.txt\" # writes to another file\n\n# Read file contents and convert to json\nGet-Content \"$env:HOMEDRIVE\\file.csv\" | ConvertTo-Json\n\n\/pre><\/pre>\n\n\n\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"powershell\" data-enlighter-theme=\"\" data-enlighter-highlight=\"\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\">####################################################\n## 4. Functions\n####################################################\n\n# Use \"function\" to create new functions\n# Keep the Verb-Noun naming convention for functions\nfunction Add-Numbers {\n $args[0] + $args[1]\n}\n\nAdd-Numbers 1 2 # => 3\n\n# Calling functions with parameters\nfunction Add-ParamNumbers {\n param( [int]$firstNumber, [int]$secondNumber )\n $firstNumber + $secondNumber\n}\n\nAdd-ParamNumbers -FirstNumber 1 -SecondNumber 2 # => 3 \n\n# Functions with named parameters, parameter attributes, parsable documentation\n&lt;#\n.SYNOPSIS\nSetup a new website\n.DESCRIPTION\nCreates everything your new website needs for much win\n.PARAMETER siteName\nThe name for the new website\n.EXAMPLE\nNew-Website -Name FancySite -Po 5000\nNew-Website SiteWithDefaultPort\nNew-Website siteName 2000 # ERROR! Port argument could not be validated\n('name1','name2') | New-Website -Verbose\n#>\nfunction New-Website() {\n    [CmdletBinding()]\n    param (\n        [Parameter(ValueFromPipeline=$true, Mandatory=$true)]\n        [Alias('name')]\n        [string]$siteName,\n        [ValidateSet(3000,5000,8000)]\n        [int]$port = 3000\n    )\n    BEGIN { Write-Output 'Creating new website(s)' }\n    PROCESS { Write-Output \"name: $siteName, port: $port\" }\n    END { Write-Output 'Website(s) created' }\n}\n\/pre><\/pre>\n\n\n\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"powershell\" data-enlighter-theme=\"\" data-enlighter-highlight=\"\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\">\n####################################################\n## 5. Modules\n####################################################\n\n# You can import modules and install modules\n# The Install-Module is similar to pip or npm, pulls from Powershell Gallery\nInstall-Module dbaTools\nImport-Module dbaTools\n\n$query = \"SELECT * FROM dbo.sometable\"\n$queryParams = @{\n    SqlInstance = 'testInstance'\n    Database    = 'testDatabase'\n    Query       = $query\n}\nInvoke-DbaQuery @queryParams\n\n# You can get specific functions from a module\nImport-Module -Function Invoke-DbaQuery\n\n\n# Powershell modules are just ordinary Posh files. You\n# can write your own, and import them. The name of the\n# module is the same as the name of the file.\n\n# You can find out which functions and attributes\n# are defined in a module.\nGet-Command -module dbaTools\nGet-Help dbaTools -Full\n\n\/pre><\/pre>\n\n\n\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"powershell\" data-enlighter-theme=\"\" data-enlighter-highlight=\"\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\">####################################################\n## 6. Classes\n####################################################\n\n# We use the \"class\" statement to create a class\nclass Instrument {\n    [string]$Type\n    [string]$Family\n}\n\n$instrument = [Instrument]::new()\n$instrument.Type = \"String Instrument\"\n$instrument.Family = \"Plucked String\"\n\n$instrument\n\n&lt;# Output:\nType              Family        \n----              ------        \nString Instrument Plucked String\n#>\n\n\/pre><\/pre>\n\n\n\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"powershell\" data-enlighter-theme=\"\" data-enlighter-highlight=\"\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\">####################################################\n## 6.1 Inheritance\n####################################################\n\n# Inheritance allows new child classes to be defined that inherit \n# methods and variables from their parent class.\n\nclass Guitar : Instrument\n{\n    [string]$Brand\n    [string]$SubType\n    [string]$ModelType\n    [string]$ModelNumber\n}\n\n$myGuitar = [Guitar]::new()\n$myGuitar.Brand       = \"Taylor\"\n$myGuitar.SubType     = \"Acoustic\"\n$myGuitar.ModelType   = \"Presentation\"\n$myGuitar.ModelNumber = \"PS14ce Blackwood\"\n\n$myGuitar.GetType()\n\n&lt;#\nIsPublic IsSerial Name                                     BaseType                                               \n-------- -------- ----                                     --------                                               \nTrue     False    Guitar                                   Instrument  \n#>\n\n\/pre><\/pre>\n\n\n\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"powershell\" data-enlighter-theme=\"\" data-enlighter-highlight=\"\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\">####################################################\n## 7. Advanced\n####################################################\n\n# The powershell pipeline allows things like High-Order Functions.\n\n# Group-Object is a handy cmdlet that does incredible things.\n# It works much like a GROUP BY in SQL.\n\n&lt;#\n The following will get all the running processes,\n group them by Name,\n and tell us how many instances of each process we have running.\n Tip: Chrome and svcHost are usually big numbers in this regard.\n#>\nGet-Process | Foreach-Object ProcessName | Group-Object\n\n# Useful pipeline examples are iteration and filtering.\n1..10 | ForEach-Object { \"Loop number $PSITEM\" }\n1..10 | Where-Object { $PSITEM -gt 5 } | ConvertTo-Json\n\n# A notable pitfall of the pipeline is it's performance when\n# compared with other options.\n# Additionally, raw bytes are not passed through the pipeline,\n# so passing an image causes some issues.\n# See more on that in the link at the bottom.\n\n&lt;#\n Asynchronous functions exist in the form of jobs.\n Typically a procedural language,\n Powershell can operate non-blocking functions when invoked as Jobs.\n#>\n\n# This function is known to be non-optimized, and therefore slow.\n$installedApps = Get-CimInstance -ClassName Win32_Product\n\n# If we had a script, it would hang at this func for a period of time.\n$scriptBlock = {Get-CimInstance -ClassName Win32_Product}\nStart-Job -ScriptBlock $scriptBlock\n\n# This will start a background job that runs the command.\n# You can then obtain the status of jobs and their returned results.\n$allJobs = Get-Job\n$jobResponse = Get-Job | Receive-Job\n\n\n# Math is built in to powershell and has many functions.\n$r=2\n$pi=[math]::pi\n$r2=[math]::pow( $r, 2 )\n$area = $pi*$r2\n$area\n\n# To see all possibilities, check the members.\n[System.Math] | Get-Member -Static -MemberType All\n\n\n&lt;#\n This is a silly one:\n You may one day be asked to create a func that could take $start and $end\n and reverse anything in an array within the given range\n based on an arbitrary array without mutating the original array.\n Let's see one way to do that and introduce another data structure.\n#>\n\n$targetArray = 'a','b','c','d','e','f','g','h','i','j','k','l','m'\n\nfunction Format-Range ($start, $end, $array) {\n    [System.Collections.ArrayList]$firstSectionArray = @()\n    [System.Collections.ArrayList]$secondSectionArray = @()\n    [System.Collections.Stack]$stack = @()\n    for ($index = 0; $index -lt $array.Count; $index++) {\n        if ($index -lt $start) {\n            $firstSectionArray.Add($array[$index]) > $null\n        }\n        elseif ($index -ge $start -and $index -le $end) {\n            $stack.Push($array[$index])\n        }\n        else {\n            $secondSectionArray.Add($array[$index]) > $null\n        }\n    }\n    $finalArray = $firstSectionArray + $stack.ToArray() + $secondSectionArray\n    return $finalArray\n}\n\nFormat-Range 2 6 $targetArray \n# => 'a','b','g','f','e','d','c','h','i','j','k','l','m'\n\n# The previous method works, but uses extra memory by allocating new arrays.\n# It's also kind of lengthy.\n# Let's see how we can do this without allocating a new array.\n# This is slightly faster as well.\n\nfunction Format-Range ($start, $end) {\n  while ($start -lt $end)\n  {\n      $temp = $targetArray[$start]\n      $targetArray[$start] = $targetArray[$end]\n      $targetArray[$end] = $temp\n      $start++\n      $end--\n  }\n  return $targetArray\n}\n\nFormat-Range 2 6 # => 'a','b','g','f','e','d','c','h','i','j','k','l','m'\n\n# Find commands\nGet-Command about_* # alias: gcm\nGet-Command -Verb Add\nGet-Alias ps\nGet-Alias -Definition Get-Process\n\nGet-Help ps | less # alias: help\nps | Get-Member # alias: gm\n\nShow-Command Get-WinEvent # Display GUI to fill in the parameters\n\nUpdate-Help # Run as admin\n\nGet-ExecutionPolicy -List\nSet-ExecutionPolicy AllSigned\n# Execution policies include:\n# - Restricted: Scripts won't run.\n# - RemoteSigned: Downloaded scripts run only if signed by a trusted publisher. \n# - AllSigned: Scripts need to be signed by a trusted publisher.\n# - Unrestricted: Run all scripts.\nhelp about_Execution_Policies # for more info\n\n# Current PowerShell version:\n$PSVersionTable\n\n# Calling external commands, executables, \n# and functions with the call operator.\n# Exe paths with arguments passed or containing spaces can create issues.\nC:\\Program Files\\dotnet\\dotnet.exe\n# The term 'C:\\Program' is not recognized as a name of a cmdlet,\n# function, script file, or executable program.\n# Check the spelling of the name, or if a path was included, \n# verify that the path is correct and try again\n\n\"C:\\Program Files\\dotnet\\dotnet.exe\"\nC:\\Program Files\\dotnet\\dotnet.exe    # returns string rather than execute\n\n&amp;\"C:\\Program Files\\dotnet\\dotnet.exe --help\"   # fail\n&amp;\"C:\\Program Files\\dotnet\\dotnet.exe\" --help   # success\n# Alternatively, you can use dot-sourcing here\n.\"C:\\Program Files\\dotnet\\dotnet.exe\" --help   # success\n\n# the call operator (&amp;) is similar to Invoke-Expression, \n# but IEX runs in current scope.\n# One usage of '&amp;' would be to invoke a scriptblock inside of your script.\n# Notice the variables are scoped\n$i = 2\n$scriptBlock = { $i=5; Write-Output $i }\n&amp; $scriptBlock # => 5\n$i # => 2\n\ninvoke-expression ' $i=5; Write-Output $i ' # => 5\n$i # => 5\n\n# Alternatively, to preserve changes to public variables\n# you can use \"Dot-Sourcing\". This will run in the current scope.\n$x=1\n&amp;{$x=2};$x # => 1\n\n.{$x=2};$x # => 2\n\n\n# Remoting into computers is easy.\nEnter-PSSession -ComputerName RemoteComputer\n\n# Once remoted in, you can run commands as if you're local.\nRemoteComputer\\PS> Get-Process powershell\n\n&lt;#\nHandles  NPM(K)    PM(K)      WS(K)     CPU(s)     Id  SI ProcessName                                             \n-------  ------    -----      -----     ------     --  -- -----------                                             \n   1096      44   156324     179068      29.92  11772   1 powershell                                              \n    545      25    49512      49852             25348   0 powershell \n#>\nRemoteComputer\\PS> Exit-PSSession\n\n&lt;#\n Powershell is an incredible tool for Windows management and Automation.\n Let's take the following scenario:\n You have 10 servers.\n You need to check whether a service is running on all of them.\n You can RDP and log in, or PSSession to all of them, but why?\n Check out the following\n#>\n\n$serverList = @(\n    'server1',\n    'server2',\n    'server3',\n    'server4',\n    'server5',\n    'server6',\n    'server7',\n    'server8',\n    'server9',\n    'server10'\n)\n\n[scriptblock]$script = {\n    Get-Service -DisplayName 'Task Scheduler'\n}\n\nforeach ($server in $serverList) {\n    $cmdSplat = @{\n        ComputerName  = $server\n        JobName       = 'checkService'\n        ScriptBlock   = $script\n        AsJob         = $true\n        ErrorAction   = 'SilentlyContinue'\n    }\n    Invoke-Command @cmdSplat | Out-Null\n}\n\n&lt;#\n Here we've invoked jobs across many servers.\n We can now Receive-Job and see if they're all running.\n Now scale this up 100x as many servers :)\n#><\/pre>\n\n\n\n<h2 class=\"wp-block-heading\">Cheat Sheet 2<\/h2>\n\n\n\n<h3 class=\"wp-block-heading\" id=\"powershell-commands-cheat-sheet\"><strong>PowerShell Commands Cheat Sheet<\/strong><\/h3>\n\n\n\n<h4 class=\"wp-block-heading\" id=\"cmdlets\"><strong>cmdlets<\/strong><\/h4>\n\n\n\n<p class=\"wp-block-paragraph\">Cmdlets are PowerShell\u2019s internal commands. These cmdlets will return one or more objects to the pipeline where at the end of that pipeline, we mention some properties of the objects in the following table to see their values displayed on the screen.<\/p>\n\n\n\n<figure class=\"wp-block-table\"><table><tbody><tr><td><strong>Command<\/strong><\/td><td><strong>Description<\/strong><\/td><\/tr><tr><td><code>Get-Help<\/code><\/td><td>This command allows you to get support with PowerShell.<\/td><\/tr><tr><td><code>Get-PSdrive<\/code><\/td><td>This command offers you a list of available PSDrives, such as c, env, hklm, hkcu, alias, etc.<\/td><\/tr><tr><td><code>Get-ChildItem<\/code><\/td><td>In any registry, children are the subkeys of the current key. To get the required details, you can use the following command.<\/td><\/tr><tr><td><code>Get-ChildItem -recurse<\/code><\/td><td>Run this command to list all the children recursively of the current PSdrive, folder, or registry key.<\/td><\/tr><tr><td><code>Get-ChildItem -rec -force<\/code><\/td><td>Use this command To include the hidden folders (directories).<\/td><\/tr><tr><td><code>(Get-ChildItem).name or Get-ChildItem -name<\/code><\/td><td>Run any of these commands to get the list file and directory names in the current folder.<\/td><\/tr><tr><td><code>(Get-ChildItem).count<\/code><\/td><td>Use this command to get the number of entries in the collection of objects returned by the Get-Children.<\/td><\/tr><\/tbody><\/table><\/figure>\n\n\n\n<h4 class=\"wp-block-heading\" id=\"psdrives\"><strong>PSdrives<\/strong><\/h4>\n\n\n\n<p class=\"wp-block-paragraph\">PSdrives are the collection of entities grouped together so they can be accessed as a filesystem drive. The \u201cPSprovider\u201d does this grouping.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">By default, a PS session can access several PSdrives including c:, env:, alias:, and HKLM:, where c: refers to the usual Windows c-drive; env: is the space of Windows environmental variables; alias: is the collection of cmdlet aliases; and HKLM is a hive in the registry.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Any PS session will enter the user\u2019s home folder. If you want to switch from a PS session to another PSdrive and retrieve the information from that drive, consider the following commands:<\/p>\n\n\n\n<figure class=\"wp-block-table\"><table><tbody><tr><td><strong>Commands<\/strong><\/td><td><strong>Description<\/strong><\/td><\/tr><tr><td><code>Switching to env-<\/code><\/td><td>The prompt character will change to the \u201cENV:\\&gt;\u201d. Set-Location env by running the following command:&nbsp;<code>Set-Location env-<\/code><\/td><\/tr><tr><td><code>Env:\\&gt; Get-Childitem<\/code><\/td><td>This command will get you all the environment variables.<\/td><\/tr><tr><td><code>Env:\\&gt; Get-Childitem userprofile<\/code><\/td><td>Use this command to get the environment variables of \u201cuserprofile.\u201d<\/td><\/tr><tr><td><code>Env:\\&gt; Set-Location alias:<\/code><\/td><td>Run the following command to change the prompt character to \u201cAlias.\u201d<\/td><\/tr><tr><td><code>Alias:\\&gt; Get-Childitem<\/code><\/td><td>Run this command to get all the children of all aliases.<\/td><\/tr><tr><td><code>Alias:\\&gt; Set-Location C:\\<\/code><\/td><td>Use this command to get the \u201cC:\/&gt;\u201d prompt again, back to the default drive.<\/td><\/tr><tr><td><code>C:\\Users\\user_name&gt;$alias:ls<\/code><\/td><td>Run this command to find what alias \u201cls\u201d stands for.<\/td><\/tr><\/tbody><\/table><\/figure>\n\n\n\n<h4 class=\"wp-block-heading\" id=\"pipelines\"><strong>Pipelines<\/strong><\/h4>\n\n\n\n<p class=\"wp-block-paragraph\">Cmdlets uses the pipelines to pass the objects but not the character streams like Unix. The pipeline character is | (ASCII 124), followed by a command that handles the output passed through the pipeline. The pipeline consists of the following three stages.<\/p>\n\n\n\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\" data-enlighter-theme=\"\" data-enlighter-highlight=\"\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\">Get-ChildItem *.txt | Where-Object length -lt 1000 | Sort-Object length<\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">The following table highlights some of the basic pipeline commands:<\/p>\n\n\n\n<figure class=\"wp-block-table\"><table><tbody><tr><td><strong>Command<\/strong><\/td><td><strong>Description<\/strong><\/td><\/tr><tr><td><code>(Get-Item \/Users\/praashibansal\/Desktop).lastwritetime.year<\/code><\/td><td>Easily sets the value of the \u2018lastwritetime.year\u2019 property to the present date and time without affecting the file\u2019s content.<\/td><\/tr><tr><td><code>(Get-ChildItem data.txt.rtf -name).name # -&gt; null<\/code><\/td><td>Provides an empty result<\/td><\/tr><tr><td><code>\"data.txt.rtf\" | Rename-Item -NewName \"data_new.txt.rtf\"<\/code><\/td><td>Changes the old file names and file extensions to the new ones<\/td><\/tr><tr><td><code>Get-ChildItem data.txt | Rename-Item -new {$_.name}<\/code><\/td><td>A trivial renaming command that invokes an automatic variable<\/td><\/tr><tr><td><code>Get-ChildItem data.txt.rtf -name | Rename-Item -new {$_.name}<\/code><\/td><td>If the piped object $_ doesn&#8217;t have the member property (name), you will receive an error, as parameter $_.name is null<\/td><\/tr><tr><td><code>Get-ChildItem | Select-Object basename | Sort-Object *<\/code><\/td><td>Displays the list of the names of all the files that are present in the current folder sorted in alphabetical order.<\/td><\/tr><tr><td><code>Move-Item *.txt subdirectory<\/code><\/td><td>Moves all the files to the folder subdirectory<\/td><\/tr><tr><td><code>Get-ChildItem *.txt | Move-Item ..\\<\/code><\/td><td>Gives the error message that Move-Item lacks input<\/td><\/tr><\/tbody><\/table><\/figure>\n\n\n\n<h4 class=\"wp-block-heading\" id=\"alias\"><strong>Alias<\/strong><\/h4>\n\n\n\n<p class=\"wp-block-paragraph\">Cmdlets come with several aliases. The following table highlights a few of aliases, along with their descriptions:<\/p>\n\n\n\n<figure class=\"wp-block-table\"><table><tbody><tr><td><strong>Command<\/strong><\/td><td><strong>Description<\/strong><\/td><\/tr><tr><td><code>Add-Content<\/code><\/td><td>Appends value to a file<\/td><\/tr><tr><td><code>Get-Content<\/code><\/td><td>Finds file content in an array<\/td><\/tr><tr><td><code>Set-Location<\/code><\/td><td>Changes folder, key, or PS drive<\/td><\/tr><tr><td><code>Clear-Host<\/code><\/td><td>Clears console<\/td><\/tr><tr><td><code>Remove-Item<\/code><\/td><td>Delete files<\/td><\/tr><tr><td><code>Get-ChildItem -Path .\\<\/code><\/td><td>Lists Folder, Key, or PSDrive Children<\/td><\/tr><tr><td><code>Write-Output<\/code><\/td><td>Sends the array to the console, pipeline, or redirect it to the file<\/td><\/tr><tr><td><code>Foreach-Object<\/code><\/td><td>Traverses each object in a pipeline<\/td><\/tr><tr><td><code>Format-Table<\/code><\/td><td>Formats the table with selected properties for each object in each column<\/td><\/tr><tr><td><code>Format-List<\/code><\/td><td>Formats the process properties by name<\/td><\/tr><tr><td><code>Get-Alias<\/code><\/td><td>Provides Cmdlet Alias<\/td><\/tr><tr><td><code>Get-Command<\/code><\/td><td>Provides you with commands from the current session only<\/td><\/tr><tr><td><code>Get-Member<\/code><\/td><td>Retrieves all the object members<\/td><\/tr><tr><td><code>Get-ItemProperty .\\data.txt | Format-List<\/code><\/td><td>Provides the specified item\u2019s properties<\/td><\/tr><tr><td><code>Get-ItemPropertyValue -Path '.\\data.txt' -Name LastWriteTime<\/code><\/td><td>Gives the current value for a specified property while using the name parameter<\/td><\/tr><tr><td><code>Get-Variable m*<\/code><\/td><td>Finds session variable names and sessions<\/td><\/tr><tr><td><code>New-Item -Path .\\ -Name \"testfile1.txt\" -ItemType \"file\" -Value \"This is a text string.\"<\/code><\/td><td>Creates a new file, directory, symbolic link, registry key, or registry entry<\/td><\/tr><tr><td><code>Get-Process<\/code><\/td><td>Gives the entire list of all the running processes<\/td><\/tr><tr><td><code>Get-Location<\/code><\/td><td>Provides the current directory\u2019s or registry key\u2019s location<\/td><\/tr><tr><td><code>Rename-Item -Path \u201cold_name\u201d -NewName \u201cnew_name\u201d<\/code><\/td><td>Renames the old item name with the new name<\/td><\/tr><tr><td><code>Remove-Item .\\testfile1.txt<\/code><\/td><td>Removes the specified directory, files, or registry keys<\/td><\/tr><tr><td><code>Remove-Variable<\/code><\/td><td>Removes the specified variable<\/td><\/tr><tr><td><code>Start-Sleep<\/code><\/td><td>Suspends an activity for a specified period of time<\/td><\/tr><\/tbody><\/table><\/figure>\n\n\n\n<h3 class=\"wp-block-heading\" id=\"operators\"><strong>Operators<\/strong><\/h3>\n\n\n\n<ul class=\"wp-block-list\">\n<li><strong>Arithmetic Operators<\/strong><\/li>\n<\/ul>\n\n\n\n<figure class=\"wp-block-table\"><table><tbody><tr><td><strong>Operator<\/strong><\/td><td><strong>Description<\/strong><\/td><td><strong>Example<\/strong><\/td><\/tr><tr><td>+<\/td><td>Adds integers; concatenates<\/td><td>6 + 2<\/td><\/tr><tr><td>&nbsp;<\/td><td>strings, arrays, and hash tables.<\/td><td>&#8220;file&#8221; + &#8220;name&#8221;@(1, &#8220;one&#8221;) + @(2.0, &#8220;two&#8221;)@{&#8220;one&#8221; = 1} + @{&#8220;two&#8221; = 2}<\/td><\/tr><tr><td>+<\/td><td>Makes a number out of an object<\/td><td>123<\/td><\/tr><tr><td>&#8211;<\/td><td>Subtracts one value from another<\/td><td>6 &#8211; 2<\/td><\/tr><tr><td>&#8211;<\/td><td>Calculates the opposite number<\/td><td>&#8211; -6<\/td><\/tr><tr><td>&nbsp;<\/td><td>&nbsp;<\/td><td>(Get-Date).AddDays(-1)<\/td><\/tr><tr><td>*<\/td><td>Multiply numbers or copy strings and arrays for a specified number of times<\/td><td>6 * 2<\/td><\/tr><tr><td>&nbsp;<\/td><td>&nbsp;<\/td><td>@(&#8220;!&#8221;) * 4<\/td><\/tr><tr><td>&nbsp;<\/td><td>&nbsp;<\/td><td>&#8220;!&#8221; * 3<\/td><\/tr><tr><td>\/<\/td><td>Divides two values<\/td><td>6 \/ 2<\/td><\/tr><tr><td>\n\n\n\n<ul class=\"wp-block-list\">\n<li><strong>Operator Precedence<\/strong><\/li>\n<\/ul>\n\n\n\n<figure class=\"wp-block-table\"><table><tbody><tr><td><strong>Precedence<\/strong><\/td><td><strong>Operator<\/strong><\/td><td><strong>Description<\/strong><\/td><\/tr><tr><td>1<\/td><td>()<\/td><td>Parentheses<\/td><\/tr><tr><td>2<\/td><td>&#8211;<\/td><td>For a negative number or unary operator<\/td><\/tr><tr><td>3<\/td><td>*, \/, \n\n\n\n<ul class=\"wp-block-list\">\n<li><strong>Assignment Operators<\/strong><\/li>\n<\/ul>\n\n\n\n<figure class=\"wp-block-table\"><table><tbody><tr><td><strong>Operator<\/strong><\/td><td><strong>Description<\/strong><\/td><\/tr><tr><td>=<\/td><td>Sets a variable\u2019s value to the specified value<\/td><\/tr><tr><td>+=<\/td><td>Increases a variable\u2019s value by the specified value or appends the specified value to the existing value<\/td><\/tr><tr><td>-=<\/td><td>Decreases a variable\u2019s value by a specified value<\/td><\/tr><tr><td>*=<\/td><td>Multiplies a variable\u2019s value by a specified value, or appends the specified value to the existing value<\/td><\/tr><tr><td>\/=<\/td><td>Divides a variable\u2019s value by a specified value<\/td><\/tr><tr><td>\n\n\n\n<ul class=\"wp-block-list\">\n<li><strong>Comparison Operators<\/strong><\/li>\n<\/ul>\n\n\n\n<figure class=\"wp-block-table\"><table><tbody><tr><td><strong>Type<\/strong><\/td><td><strong>Operator<\/strong><\/td><td><strong>Comparison test<\/strong><\/td><\/tr><tr><td>Equality<\/td><td>-eq<\/td><td>equals<\/td><\/tr><tr><td>&nbsp;<\/td><td>-ne<\/td><td>not equals<\/td><\/tr><tr><td>&nbsp;<\/td><td>-gt<\/td><td>greater than<\/td><\/tr><tr><td>&nbsp;<\/td><td>-ge<\/td><td>greater than or equal<\/td><\/tr><tr><td>&nbsp;<\/td><td>-lt<\/td><td>less than<\/td><\/tr><tr><td>&nbsp;<\/td><td>-le<\/td><td>less than or equal<\/td><\/tr><tr><td>Matching<\/td><td>-like<\/td><td>string matches wildcard pattern<\/td><\/tr><tr><td>&nbsp;<\/td><td>-notlike<\/td><td>string doesn&#8217;t match wildcard pattern<\/td><\/tr><tr><td>&nbsp;<\/td><td>-match<\/td><td>string matches regex pattern<\/td><\/tr><tr><td>&nbsp;<\/td><td>-notmatch<\/td><td>string doesn&#8217;t match regex pattern<\/td><\/tr><tr><td>Replacement<\/td><td>-replace<\/td><td>replaces strings matching a regex pattern<\/td><\/tr><tr><td>Containment<\/td><td>-contains<\/td><td>collection contains a value<\/td><\/tr><tr><td>&nbsp;<\/td><td>-notcontains<\/td><td>collection doesn&#8217;t contain a value<\/td><\/tr><tr><td>&nbsp;<\/td><td>-in<\/td><td>value is in a collection<\/td><\/tr><tr><td>&nbsp;<\/td><td>-notin<\/td><td>value is not in a collection<\/td><\/tr><tr><td>Type<\/td><td>-is<\/td><td>both objects are the same type<\/td><\/tr><tr><td>&nbsp;<\/td><td>-isnot<\/td><td>objects are not the same type<\/td><\/tr><\/tbody><\/table><\/figure>\n\n\n\n<ul class=\"wp-block-list\">\n<li><strong>Logical Operators<\/strong><\/li>\n<\/ul>\n\n\n\n<figure class=\"wp-block-table\"><table><tbody><tr><td><strong>Operator<\/strong><\/td><td><strong>Description<\/strong><\/td><td><strong>Example<\/strong><\/td><\/tr><tr><td>-and<\/td><td>Logical AND. TRUE when both statements are true.<\/td><td>(1 -eq 1) -and (1 -eq 2)&nbsp;FALSE<\/td><\/tr><tr><td>-or<\/td><td>Logical OR. TRUE when either of the statements is TRUE.<\/td><td>(1 -eq 1) -or (1 -eq 2)TRUE<\/td><\/tr><tr><td>-xor<\/td><td>Logical EXCLUSIVE OR. TRUE when only one statement is TRUE.<\/td><td>(1 -eq 1) -xor (2 -eq 2)FALSE<\/td><\/tr><tr><td>-not<\/td><td>Logical not. Negates the statement that follows.<\/td><td>-not (1 -eq 1)FLASE<\/td><\/tr><tr><td>!<\/td><td>Same as -not<\/td><td>!(1 -eq 1)FALSE<\/td><\/tr><\/tbody><\/table><\/figure>\n\n\n\n<ul class=\"wp-block-list\">\n<li><strong>Redirection Operator<\/strong><\/li>\n<\/ul>\n\n\n\n<figure class=\"wp-block-table\"><table><tbody><tr><td><strong>Operator<\/strong><\/td><td><strong>Description<\/strong><\/td><td><strong>Syntax<\/strong><\/td><\/tr><tr><td>&gt;<\/td><td>Send specified stream to a file<\/td><td>n&gt;<\/td><\/tr><tr><td>&gt;&gt;<\/td><td>Append specified stream to a file<\/td><td>n&gt;&gt;<\/td><\/tr><tr><td>&gt;&amp;1<\/td><td>Redirects the specified stream to the Success stream<\/td><td>n&gt;&amp;1<\/td><\/tr><\/tbody><\/table><\/figure>\n\n\n\n<ul class=\"wp-block-list\">\n<li><strong>Type Operators<\/strong><\/li>\n<\/ul>\n\n\n\n<figure class=\"wp-block-table\"><table><tbody><tr><td><strong>Operator<\/strong><\/td><td><strong>Description<\/strong><\/td><td><strong>Example<\/strong><\/td><\/tr><tr><td>-isNot<\/td><td>Returns TRUE when the input not an instance of thespecified.NET&nbsp;type.<\/td><td>(get-date) -isNot [DateTime]FALSE<\/td><\/tr><tr><td>-as<\/td><td>Converts the input to the specified .NET type.<\/td><td>&#8220;5\/7\/07&#8221; -as [DateTime]Monday, May 7, 2007 00:00:00<\/td><\/tr><\/tbody><\/table><\/figure>\n\n\n\n<h4 class=\"wp-block-heading\" id=\"some-other-operators\"><strong>Some Other Operators<\/strong><\/h4>\n\n\n\n<figure class=\"wp-block-table\"><table><tbody><tr><td><strong>Operator<\/strong><\/td><td><strong>Description<\/strong><\/td><\/tr><tr><td>() Grouping Operator<\/td><td>Allows you to override operator precedence in expressions<\/td><\/tr><tr><td>&amp;() Subexpression Operator<\/td><td>Gives you the result of one or more statements<\/td><\/tr><tr><td>@( ) Array Subexpression Operator<\/td><td>Returns the results of one or more statements in the form of arrays.<\/td><\/tr><tr><td>&amp; Background Operator<\/td><td>The pipeline before &amp; is executed by this command in a Powershell job.<\/td><\/tr><tr><td>[] Cast Operator<\/td><td>Converts objects to the specific type.<\/td><\/tr><\/tbody><\/table><\/figure>\n\n\n\n<h3 class=\"wp-block-heading\" id=\"regular-expressions\"><strong>Regular Expressions<\/strong><\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">A regular expression is a pattern that is used to match text that includes literal characters, operators, and other constructs. PowerShell regular expressions are case-insensitive by default.<\/p>\n\n\n\n<figure class=\"wp-block-table\"><table><tbody><tr><td><strong>Method<\/strong><\/td><td><strong>Case Sensitivity<\/strong><\/td><\/tr><tr><td>Select-String<\/td><td>use -CaseSensitive switch<\/td><\/tr><tr><td>switch statement<\/td><td>use the -casesensitive option<\/td><\/tr><tr><td>operators<\/td><td>prefix with &#8216;c&#8217; (-cmatch, -csplit, or -creplace)<\/td><\/tr><\/tbody><\/table><\/figure>\n\n\n\n<ul class=\"wp-block-list\">\n<li><strong>Character Literals<\/strong><\/li>\n<\/ul>\n\n\n\n<p class=\"wp-block-paragraph\">A regular expression can be a literal character or a string.<\/p>\n\n\n\n<figure class=\"wp-block-image\"><img decoding=\"async\" src=\"https:\/\/cdn.hackr.io\/uploads\/posts\/attachments\/1656891296LDZXsJwaIC.webp\" alt=\"\"\/><\/figure>\n\n\n\n<ul class=\"wp-block-list\">\n<li><strong>Character Groups<\/strong><\/li>\n<\/ul>\n\n\n\n<p class=\"wp-block-paragraph\">These allow you to match any number of characters one time, while [^character group] only matches characters NOT in the group.<\/p>\n\n\n\n<figure class=\"wp-block-image\"><img decoding=\"async\" src=\"https:\/\/cdn.hackr.io\/uploads\/posts\/attachments\/1656891325bXXqOF4uJC.webp\" alt=\"\"\/><\/figure>\n\n\n\n<ul class=\"wp-block-list\">\n<li><strong>Character Range<\/strong><\/li>\n<\/ul>\n\n\n\n<p class=\"wp-block-paragraph\">A pattern can also be a range of characters. The characters can be alphabetic [A-Z], numeric [0-9], or even ASCII-based [ -~] (all printable characters).<\/p>\n\n\n\n<figure class=\"wp-block-image\"><img decoding=\"async\" src=\"https:\/\/cdn.hackr.io\/uploads\/posts\/attachments\/1656891366gtPq13tCV1.webp\" alt=\"\"\/><\/figure>\n\n\n\n<ul class=\"wp-block-list\">\n<li><strong>Numbers<\/strong><\/li>\n<\/ul>\n\n\n\n<p class=\"wp-block-paragraph\">The \\d character class will match any decimal digit. Conversely, \\D will match any non-decimal digit.<\/p>\n\n\n\n<figure class=\"wp-block-image\"><img decoding=\"async\" src=\"https:\/\/cdn.hackr.io\/uploads\/posts\/attachments\/1656891402LHBrWOjrWt.webp\" alt=\"\"\/><\/figure>\n\n\n\n<ul class=\"wp-block-list\">\n<li><strong>Word Character<\/strong><\/li>\n<\/ul>\n\n\n\n<p class=\"wp-block-paragraph\">The \\w character class will match any word character [a-zA-Z_0-9]. To match any non-word character, use \\W.<\/p>\n\n\n\n<figure class=\"wp-block-image\"><img decoding=\"async\" src=\"https:\/\/cdn.hackr.io\/uploads\/posts\/attachments\/1656891438bVPyRUjErt.webp\" alt=\"\"\/><\/figure>\n\n\n\n<ul class=\"wp-block-list\">\n<li><strong>Wildcard<\/strong><\/li>\n<\/ul>\n\n\n\n<p class=\"wp-block-paragraph\">The period (.) is a wildcard character in regular expressions. It will match any character except a newline (\\n).<\/p>\n\n\n\n<figure class=\"wp-block-image\"><img decoding=\"async\" src=\"https:\/\/cdn.hackr.io\/uploads\/posts\/attachments\/1656891538nkkovuWpZc.webp\" alt=\"\"\/><\/figure>\n\n\n\n<ul class=\"wp-block-list\">\n<li><strong>Whitespace<\/strong><\/li>\n<\/ul>\n\n\n\n<p class=\"wp-block-paragraph\">Whitespace is matched using the \\s character class. Any non-whitespace character is matched using \\S. Literal space characters &#8216; &#8216; can also be used.<\/p>\n\n\n\n<figure class=\"wp-block-image\"><img decoding=\"async\" src=\"https:\/\/cdn.hackr.io\/uploads\/posts\/attachments\/1656891557jXMhHwYE5c.webp\" alt=\"\"\/><\/figure>\n\n\n\n<ul class=\"wp-block-list\">\n<li><strong>Escaping Characters<\/strong><\/li>\n<\/ul>\n\n\n\n<p class=\"wp-block-paragraph\">The backslash (\\) is used to escape characters so the regular expression engine doesn\u2019t parse them.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">The following characters are reserved: []().\\^$|?*+{}.<\/p>\n\n\n\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\" data-enlighter-theme=\"\" data-enlighter-highlight=\"\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\">> '3.141' -match '3\\.\\d{2,]'\nTrue<\/pre>\n\n\n\n<ul class=\"wp-block-list\">\n<li><strong>Substitution in Regular Expression.<\/strong><\/li>\n<\/ul>\n\n\n\n<p class=\"wp-block-paragraph\">The regular expressions with the -replace operator allows you to dynamically replace text using captured text.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">&lt;input&gt; -replace &lt;original&gt;, &lt;substitute&gt;<\/p>\n\n\n\n<h3 class=\"wp-block-heading\"><strong><\/strong><\/h3>\n\n\n\n<h3 class=\"wp-block-heading\" id=\"flow-control\"><strong>Flow Control<\/strong><\/h3>\n\n\n\n<ul class=\"wp-block-list\">\n<li><strong>ForEach-Object<\/strong><\/li>\n<\/ul>\n\n\n\n<p class=\"wp-block-paragraph\">ForEach-Object is a cmdlet that allows you to iterate through items in a pipeline, such as with PowerShell one-liners. ForEach-Object will stream the objects through the pipeline.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Although the Module parameter of Get-Command accepts multiple values that are strings, it will only accept them via pipeline input using the property name, or parameter input.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">If you want to pipe two strings by value to Get-Command for use with the Module parameter, use the ForEach-Objectcmdlet:<\/p>\n\n\n\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\" data-enlighter-theme=\"\" data-enlighter-highlight=\"\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\">$ComputerName = 'DC01', 'WEB01'\n\nforeach ($Computer in $ComputerName) {\n    Get-ADComputer -Identity $Computer\n}<\/pre>\n\n\n\n<ul class=\"wp-block-list\">\n<li><strong>For<\/strong><\/li>\n<\/ul>\n\n\n\n<p class=\"wp-block-paragraph\">A \u201cfor\u201d loop iterates while a specified condition is true.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">For example:<\/p>\n\n\n\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\" data-enlighter-theme=\"\" data-enlighter-highlight=\"\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\">for ($i = 1; $i -lt 5; $i++) {\n\nWrite-Output \"Sleeping for $i seconds\"\n\nStart-Sleep -Seconds $i\n\n}<\/pre>\n\n\n\n<ul class=\"wp-block-list\">\n<li><strong>Do<\/strong><\/li>\n<\/ul>\n\n\n\n<p class=\"wp-block-paragraph\">There are two different \u201cdo\u201d loops in PowerShell. Do&nbsp;<em>Until&nbsp;<\/em>runs while the specified condition is false.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>Example 1:<\/strong><\/p>\n\n\n\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\" data-enlighter-theme=\"\" data-enlighter-highlight=\"\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\">$number = Get-Random -Minimum 1 -Maximum 10\n\ndo {\n    $guess = Read-Host -Prompt \"What's your guess?\"\n\n    if ($guess -lt $number) {\n        Write-Output 'Too low!'\n    } elseif ($guess -gt $number) {\n        Write-Output 'Too high!'\n    }\n}\n\nuntil ($guess -eq $number)<\/pre>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>Example 2:<\/strong><\/p>\n\n\n\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\" data-enlighter-theme=\"\" data-enlighter-highlight=\"\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\">$number = Get-Random -Minimum 1 -Maximum 10\n\ndo {\n    $guess = Read-Host -Prompt \"What's your guess?\"\n\n    if ($guess -lt $number) {\n        Write-Output 'Too low!'\n    } elseif ($guess -gt $number) {\n        Write-Output 'Too high!'\n    }\n}\n\nwhile ($guess -ne $number)<\/pre>\n\n\n\n<ul class=\"wp-block-list\">\n<li><strong>While<\/strong><\/li>\n<\/ul>\n\n\n\n<p class=\"wp-block-paragraph\">Similar to the Do While loop, a While loop runs as long as the specified condition is true. The difference however, is that a While loop evaluates the condition at the top of the loop before any code is run. So, it doesn&#8217;t run if the condition evaluates to false.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">For example:<\/p>\n\n\n\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\" data-enlighter-theme=\"\" data-enlighter-highlight=\"\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\">$date = Get-Date -Date 'November 22'\n\nwhile ($date.DayOfWeek -ne 'Thursday') {\n    $date = $date.AddDays(1)\n}\n\nWrite-Output $date<\/pre>\n\n\n\n<h3 class=\"wp-block-heading\" id=\"variables\"><strong>Variables<\/strong><\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">PowerShell allows you to store all types of values. For example, it can store command results and command expression elements like names, paths, and settings. Here are some of PowerShell\u2019s different variables.<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li><strong>User-created variables:<\/strong>&nbsp;These are created and maintained by the user. The variables you create at the PowerShell command line will only exist until the PowerShell window is open. When you close the PowerShell window, these variables are deleted. If you want to save a variable, you need to add it to your PowerShell profile. You can create variables and declare them with three different scopes: global, script, or local.<\/li>\n<\/ul>\n\n\n\n<ul class=\"wp-block-list\">\n<li><strong>Automatic variables:&nbsp;<\/strong>These variables store the state of PowerShell and are created by PowerShell. Only PowerShell can change their values as required to maintain accuracy. Users can\u2019t change these variables\u2019 value. For example, the $PSHOME variable will store the path to the PowerShell installation directory.<\/li>\n\n\n\n<li><strong>Preference variables:<\/strong>&nbsp;These variables store user preferences for PowerShell and are created by PowerShell. These variables are populated with default values and can be changed by the users. For example, the $MaximumHistoryCount variable specifies the maximum number of entries in the session history.<\/li>\n<\/ul>\n\n\n\n<p class=\"wp-block-paragraph\">To create a new variable, you need to use an assignment statement and assign a value to the variable. There is no need to declare the variable before using it. The default value of all variables is $null.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">For example:<\/p>\n\n\n\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\" data-enlighter-theme=\"\" data-enlighter-highlight=\"\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\">$MyVariable = 1, 2, 3\n\n$MyVariable<\/pre>\n\n\n\n<h3 class=\"wp-block-heading\" id=\"function\"><strong>Function<\/strong><\/h3>\n\n\n\n<ul class=\"wp-block-list\">\n<li><strong>Naming Your Function<\/strong><\/li>\n<\/ul>\n\n\n\n<p class=\"wp-block-paragraph\">Use a Pascal case name with an approved verb and a singular noun to name a function. You can get a list of approved verbs by running Get-Verb:<\/p>\n\n\n\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\" data-enlighter-theme=\"\" data-enlighter-highlight=\"\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\">Get-Verb | Sort-Object -Property Verb<\/pre>\n\n\n\n<ul class=\"wp-block-list\">\n<li><strong>Creating a Simple Function<\/strong><\/li>\n<\/ul>\n\n\n\n<p class=\"wp-block-paragraph\">Use a function keyword followed by the function name to create a simple function. Then, use an open and closing curly brace. The function will execute code contained within those curly braces.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">For example:<\/p>\n\n\n\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\" data-enlighter-theme=\"\" data-enlighter-highlight=\"\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\">function Get-Version {\n    $PSVersionTable.PSVersion\n}<\/pre>\n\n\n\n<h3 class=\"wp-block-heading\" id=\"working-with-modules\"><strong>Working with Modules<\/strong><\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">A module is a package containing PowerShell members, such as cmdlets, providers, functions, workflows, variables, and aliases. You can implement package members in a PowerShell script, a compiled DLL, or both. PowerShell automatically imports the modules the first time you run any command in an installed module. You can use the commands in a module without setting up or profile configuration.<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li><strong>How to Use a Module<\/strong><\/li>\n<\/ul>\n\n\n\n<p class=\"wp-block-paragraph\">To use any module, you need to first install them. Then, find the command that comes with the module and use them.<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li><strong>Installing a Module<\/strong><\/li>\n<\/ul>\n\n\n\n<p class=\"wp-block-paragraph\">If you get a module as a folder, install it before you use it on the PowerShell command line. Some modules are preinstalled. You can use the following command to create a Modules directory for the current user:<\/p>\n\n\n\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\" data-enlighter-theme=\"\" data-enlighter-highlight=\"\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\">New-Item -Type Directory -Path $HOME\\Documents\\PowerShell\\Modules<\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">Copy the entire module folder into the Modules directory. You can use any method to copy the folder, including Windows Explorer,&nbsp;Cmd.exe, and PowerShell.<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li><strong>Finding the Installed Modules<\/strong><\/li>\n<\/ul>\n\n\n\n<p class=\"wp-block-paragraph\">Run the following to find the modules installed in a default module location (not imported).<\/p>\n\n\n\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\" data-enlighter-theme=\"\" data-enlighter-highlight=\"\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\">Get-Module -ListAvailable<\/pre>\n\n\n\n<ul class=\"wp-block-list\">\n<li><strong>Finding Commands in a Module<\/strong><\/li>\n<\/ul>\n\n\n\n<p class=\"wp-block-paragraph\">Run the following command to find a module\u2019s commands:<\/p>\n\n\n\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\" data-enlighter-theme=\"\" data-enlighter-highlight=\"\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\">Get-Command -Module &lt;module-name>\n\nGet-Command -Module Microsoft.PowerShell.Archive<\/pre>\n\n\n\n<ul class=\"wp-block-list\">\n<li><strong>Importing a Module<\/strong><\/li>\n<\/ul>\n\n\n\n<p class=\"wp-block-paragraph\">Run the following command with the proper module name:<\/p>\n\n\n\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\" data-enlighter-theme=\"\" data-enlighter-highlight=\"\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\">Import-Module &lt;module-name><\/pre>\n\n\n\n<ul class=\"wp-block-list\">\n<li><strong>Removing a Module Name<\/strong><\/li>\n<\/ul>\n\n\n\n<p class=\"wp-block-paragraph\">You can run the following command with the proper module name:<\/p>\n\n\n\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\" data-enlighter-theme=\"\" data-enlighter-highlight=\"\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\">Remove-Module &lt;module-name><\/pre>\n\n\n\n<ul class=\"wp-block-list\">\n<li><strong>View Default Module Locations<\/strong><\/li>\n<\/ul>\n\n\n\n<p class=\"wp-block-paragraph\">Use the following command to view default module locations:<\/p>\n\n\n\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\" data-enlighter-theme=\"\" data-enlighter-highlight=\"\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\">$Env:PSModulePath<\/pre>\n\n\n\n<ul class=\"wp-block-list\">\n<li><strong>Add a Default Module Location<\/strong><\/li>\n<\/ul>\n\n\n\n<p class=\"wp-block-paragraph\">You can use the following command format:<\/p>\n\n\n\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\" data-enlighter-theme=\"\" data-enlighter-highlight=\"\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\">$Env:PSModulePath = $Env:PSModulePath + \";&lt;path>\"<\/pre>\n\n\n\n<ul class=\"wp-block-list\">\n<li><strong>Add a Default Module Location on Linux or MacOS<\/strong><\/li>\n<\/ul>\n\n\n\n<p class=\"wp-block-paragraph\">Use the following to execute the same command as above, only with Linux or macOS:<\/p>\n\n\n\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\" data-enlighter-theme=\"\" data-enlighter-highlight=\"\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\">$Env:PSModulePath += \":&lt;path>\"<\/pre>\n\n\n\n<h3 class=\"wp-block-heading\" id=\"hash-tables\"><strong>Hash Tables<\/strong><\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">A hash table is a complex data structure to store data in the form of key-value pairs. We also refer to a hash table as a dictionary or associative array. To understand a hash table, consider a series of IP addresses and the respective computer names. A hash stores this data in the form of key-value pairs, where IP addresses refer to keys and computer names to their corresponding values.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">The hash table syntax is as follows:<strong>@{ &lt;name&gt; = &lt;value&gt;; [&lt;name&gt; = &lt;value&gt; ] &#8230;}<\/strong><\/p>\n\n\n\n<p class=\"wp-block-paragraph\">An ordered dictionary\u2019s syntax is as follows:<strong>[ordered]@{ &lt;name&gt; = &lt;value&gt;; [&lt;name&gt; = &lt;value&gt; ] &#8230;}<\/strong><\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li><strong>Creating Hash Tables<\/strong><\/li>\n<\/ul>\n\n\n\n<p class=\"wp-block-paragraph\">If you want to create a hash table, follow these steps:<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li>Start the hash table with an at sign (@) and enclose it in curly braces ({}).<\/li>\n\n\n\n<li>A hash table should contain at least one key-value pair, and hence, enter the data after creating a hash table.<\/li>\n\n\n\n<li>Separate key from its value using an equal sign (=).<\/li>\n\n\n\n<li>Separate the key\/value pairs in a hash table with a semicolon (;).<\/li>\n\n\n\n<li>Enclose the space between the keys in quotation marks. Values must be valid PowerShell expressions. Also, enclose strings in quotation marks, even if there are no spaces between them.<\/li>\n\n\n\n<li>Save a hash table as a variable to manage it efficiently.<\/li>\n\n\n\n<li>When assigning an ordered hash table to a variable, place the [ordered] attribute before the @ symbol. If you place it before the variable name, the command fails.<\/li>\n<\/ul>\n\n\n\n<p class=\"wp-block-paragraph\">For example:<\/p>\n\n\n\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\" data-enlighter-theme=\"\" data-enlighter-highlight=\"\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\">$hash = @{}\n\n$hash = @{ Number = 1; Shape = \"Square\"; Color = \"Blue\"}\n\n[hashtable]$hash = [ordered]@{\n\nNumber = 1; Shape = \"Square\"; Color = \"Blue\"}\n\n$hash<\/pre>\n\n\n\n<figure class=\"wp-block-image\"><img decoding=\"async\" src=\"https:\/\/cdn.hackr.io\/uploads\/posts\/attachments\/1656892107w2IwkIoNzK.webp\" alt=\"\"\/><\/figure>\n\n\n\n<ul class=\"wp-block-list\">\n<li><strong>Adding and Removing Keys and Values<\/strong><\/li>\n<\/ul>\n\n\n\n<p class=\"wp-block-paragraph\">To add keys and values to a hash table, use the following command format:<\/p>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>$hash[&#8220;&lt;key&gt;&#8221;] = &#8220;&lt;value&gt;&#8221;<\/strong><\/p>\n\n\n\n<p class=\"wp-block-paragraph\">For example, you can add a &#8220;Time&#8221; key with a value of &#8220;Now&#8221; to the hash table with the following statement format:<\/p>\n\n\n\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\" data-enlighter-theme=\"\" data-enlighter-highlight=\"\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\">$hash[\"Time\"] = \"Now\"<\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">Or<\/p>\n\n\n\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\" data-enlighter-theme=\"\" data-enlighter-highlight=\"\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\">$hash.Add(\"Time\", \"Now\")<\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">Or, you can remove the key with this statement format:<\/p>\n\n\n\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\" data-enlighter-theme=\"\" data-enlighter-highlight=\"\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\">$hash.Remove(\"Time\")<\/pre>\n\n\n\n<h3 class=\"wp-block-heading\" id=\"asynchronous-event-handling\"><strong>Asynchronous Event Handling<\/strong><\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">These cmdlets allow you to register and unregister event subscriptions and list the existing subscriptions. You can also list pending events and handle or remove them as desired.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">PowerShell eventing cmdlets<\/p>\n\n\n\n<figure class=\"wp-block-table\"><table><tbody><tr><td><strong>Eventing Cmdlet name<\/strong><\/td><td><strong>Description<\/strong><\/td><\/tr><tr><td>Register-ObjectEvent<\/td><td>This cmdlet registers an event subscription for events generated by .NET objects<\/td><\/tr><tr><td>Register-WmiEvent<\/td><td>Registers an event subscription for events generated by WMI objects<\/td><\/tr><tr><td>Register-EngineEvent<\/td><td>Registers an event subscription for events generated by PowerShell itself<\/td><\/tr><tr><td>Get-EventSubscriber<\/td><td>Gets a list of the registered event subscriptions in the session<\/td><\/tr><tr><td>Unregister-Event<\/td><td>Removes one or more of the registered event subscriptions<\/td><\/tr><tr><td>Wait-Event<\/td><td>Waits for an event to occur. This cmdlet can wait for a specific event or any event. It also allows a timeout to be specified, limiting how long it will wait for the event. The default is to wait forever.<\/td><\/tr><tr><td>Get-Event<\/td><td>Gets pending unhandled events from the event queue<\/td><\/tr><tr><td>Remove-Event<\/td><td>Removes a pending event from the event queue<\/td><\/tr><tr><td>New-Event<\/td><td>This cmdlet is called in a script to allow the script to add its own events to the event queue<\/td><\/tr><\/tbody><\/table><\/figure>\n\n\n\n<p class=\"wp-block-paragraph\"><\/p>\n","protected":false},"excerpt":{"rendered":"<p>Cheat Sheet 1 Learning Powershell in 5 Minutes Comments Primitive Datatypes and Operators Cheat Sheet 2 PowerShell Commands Cheat Sheet cmdlets Cmdlets are PowerShell\u2019s internal commands. These cmdlets will return one or more objects to the pipeline where at the end of that pipeline, we mention some properties of the objects in the following table to see their values displayed on the screen. Command Description Get-Help This command allows you to get support with PowerShell. Get-PSdrive This command offers you a list of available PSDrives, such as c, env, hklm, hkcu, alias, etc. Get-ChildItem In any registry, children are the subkeys [&hellip;]<\/p>\n","protected":false},"author":1,"featured_media":7170,"comment_status":"open","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"_crdt_document":"","_jetpack_memberships_contains_paid_content":false,"footnotes":""},"categories":[102],"tags":[],"class_list":["post-9626","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-power-shell"],"jetpack_featured_media_url":"","jetpack_sharing_enabled":true,"_links":{"self":[{"href":"https:\/\/via-internet.de\/blog\/wp-json\/wp\/v2\/posts\/9626","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/via-internet.de\/blog\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/via-internet.de\/blog\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/via-internet.de\/blog\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/via-internet.de\/blog\/wp-json\/wp\/v2\/comments?post=9626"}],"version-history":[{"count":6,"href":"https:\/\/via-internet.de\/blog\/wp-json\/wp\/v2\/posts\/9626\/revisions"}],"predecessor-version":[{"id":9639,"href":"https:\/\/via-internet.de\/blog\/wp-json\/wp\/v2\/posts\/9626\/revisions\/9639"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/via-internet.de\/blog\/wp-json\/"}],"wp:attachment":[{"href":"https:\/\/via-internet.de\/blog\/wp-json\/wp\/v2\/media?parent=9626"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/via-internet.de\/blog\/wp-json\/wp\/v2\/categories?post=9626"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/via-internet.de\/blog\/wp-json\/wp\/v2\/tags?post=9626"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}