powershell:qnd:powershell

Powershell (quick-n-dirty)

Core

  • The back tick/grave accent (`) is the line continuation character
  • On Powershell CLI press Shift + Enter to go into multi-line editing mode
  • To string together multiple commands in one line use the ; separator
  • The pound (#) is the single line comment character
  • <# and #> are the markers for a block/multi-line comment
  • Use Ctrl+r and Ctrl+s to search backward and forward through history for the typed text
  • Use F8 and Shift+F8 to search backward and forward through history for the text already on the command line
  • Get last command error by referencing $? variable
  • $(<command>) is the syntax to do command substitution
  • Wrap identifier names in {} when they contain special characters like spaces and dashes

Command Line

Example of setting VS Code as the editor used for command line editing

'@code --new-window --wait %*' > "$HOME\codewait.cmd"
 
$env:VISUAL = "$HOME/codewait"
 
# Custom key binding
Set-PSReadLineKeyHandler -Chord Alt+e -Function ViEditVisually

Data Types

  • Use $var.GetType() to get data type of variable
$foo = "alpha"
$foo = @()
$foo = "alpha", "beta"
$foo = @(
       "alpha"
       "beta"
       "gamma"
       )
$hash = @{}
$hash = @{ Number = 1; Shape = "Square"; Color = "Blue"}
  • Use ${<var>} to reference variables that have names that include special characters (e.g. spaces) or are being used to build a string. For building a string this syntax disambiguates the variable name from the rest of the characters in a string.
  • $(<var>) is also needed in certain scenarios, more to come on this
  • If a variable name contains spaces it needs to be wrapped in quotes (e.g. $obj.“First Name” or {}. This might happen with imported CSV data, for example.

Control Structures

Loops/Iteration

$fruit = @('apple','pear','banana','lemon','lime','mango')
 
For ($i = 0; $i -le $fruit.length; $i++) {
    Write-Host $fruit[$i];    
}
foreach ($file in Get-ChildItem) {
  # do something with $file
}

Loop over elements of array and reference the element by the automatic variable for the current element.

$array | foreach { $_ }
  • To loop over the items in a hash table one option is to call GetEnumerator() on the hash table.
$t1 = @{firstname = "Michael"; lastname = "Muse"}
 
foreach ($i in $t1.GetEnumerator()) {
    $i.value
}

Alternatively use the keys

$t1 = @{firstname = "Michael"; lastname = "Muse"}
 
foreach ($i in $t1.keys) {
    $t1[$i]
}

Select-String

Example of selecting a matching line and 7 lines of context before and after the match.

netsh http show urlacl | sls -context 7,7 wsman

Working With Objects

  • Get-Member to list all object members (properties and methods)

Select Objects

  • Select-Object, alias select

Example of getting just the first item of the listed output

ls | select first 1
Example: Select all disabled user accounts

The Where-Object or where cmdlet allows a collection of objects to be filtered by some specified criteria.

Get-ADUser -Credential $Credentials -Server pdc -Filter * -SearchBase "dc=contoso,dc=com" | Where-Object {$_.Enabled -eq $false}

Select properties from an object using Select-Object cmdlet. Selecting NIC name and IP address.

Get-NetIPAddress | Select-Object InterfaceAlias, IPAddress

Get Objects - Where-Object

Get-ChildItem -Exclude @("web*", "sql*")
ls -Exclude web*,sql*

Example using -notmatch operator and regex to match files that don't begin with test.

ls | Where-Object {$_.name -notmatch "^test*"}

Example of filtering for files that contain spaces.

ls | Where-Object {$_.name -match ".*[ ]+.*"}

Selecting Properties

List the properties/methods of the returned objects.

Example:

Get-Command | Get-Members

Example:

$(get-command)[0] | Get-Member
 
 
   TypeName: System.Management.Automation.AliasInfo
 
Name                MemberType     Definition
----                ----------     ----------
Equals              Method         bool Equals(System.Object obj)
GetHashCode         Method         int GetHashCode()
GetType             Method         type GetType()
ResolveParameter    Method         System.Management.Automation.ParameterMetadata ResolveParameter(string name)
ToString            Method         string ToString()
CommandType         Property       System.Management.Automation.CommandTypes CommandType {get;}
Definition          Property       string Definition {get;}
Description         Property       string Description {get;set;}
Module              Property       psmoduleinfo Module {get;}
ModuleName          Property       string ModuleName {get;}
Name                Property       string Name {get;}
Options             Property       System.Management.Automation.ScopedItemOptions Options {get;set;}
OutputType          Property       System.Collections.ObjectModel.ReadOnlyCollection[System.Management.Automation.PS...
Parameters          Property       System.Collections.Generic.Dictionary[string,System.Management.Automation.Paramet...
ParameterSets       Property       System.Collections.ObjectModel.ReadOnlyCollection[System.Management.Automation.Co...
ReferencedCommand   Property       System.Management.Automation.CommandInfo ReferencedCommand {get;}
RemotingCapability  Property       System.Management.Automation.RemotingCapability RemotingCapability {get;}
ResolvedCommand     Property       System.Management.Automation.CommandInfo ResolvedCommand {get;}
Source              Property       string Source {get;}
Version             Property       version Version {get;}
Visibility          Property       System.Management.Automation.SessionStateEntryVisibility Visibility {get;set;}
DisplayName         ScriptProperty System.Object DisplayName {get=if ($this.Name.IndexOf('-') -lt 0)...
HelpUri             ScriptProperty System.Object HelpUri {get=$oldProgressPreference = $ProgressPreference...
ResolvedCommandName ScriptProperty System.Object ResolvedCommandName {get=$this.ResolvedCommand.Name;}
(Get-NetIPAddresses).IPAddress
Get-NetIPAddresses | foreach {$_.IPAddress}
Get-NetIPAddresses | Select-Object InterfaceAlias, IPAddress

Modules

Miscellanea

get-date | out-file -FilePath c:\test.txt
$null -eq (wmic product get name | select-string "sentinelone")
if ($null -eq (wmic product get name | select-string "sentinelone")) {
    msiexec.exe /i \\server_name\share_name\sentinel_installer.msi SITE_TOKEN=$site_token /qn /norestart
}
notepad (Get-PSReadLineOption | select -ExpandProperty HistorySavePath)

Powershell Meta

  • Use Get-Help to show command documentation

Find commands when you know part of the name.

Get-Command | Where-Object {$_.Name -like "*csv*"}
Get-Command *csv*
Get-Command | Select-String *csv*

List commands in module

Get-Command -Module <module-name>

Examples of getting path to executables

Get-Command notepad
 
CommandType     Name                                               Version    Source
-----------     ----                                               -------    ------
Application     notepad.exe                                        10.0.19... C:\Windows\system32\notepad.exe
where.exe notepad
Get-Alias | Where-=Object {$_.Name -like "*where*"}
Get-Module -ListAvailable

Example

Get-Module -Name Microsoft.Online.SharePoint.PowerShell -ListAvailable | Select Name,Version

Example

Get-command -Module Microsoft.Online.SharePoint.PowerShell
  • powershell/qnd/powershell.txt
  • Last modified: 2023/02/02 18:14
  • by mgupton