Show pageOld revisionsBacklinksBack to top This page is read only. You can view the source, but not change it. Ask your administrator if you think this is wrong. ====== Powershell (quick-n-dirty) ====== * [[powershell:qnd:Documentation]] * [[powershell:qnd:strings]] * [[powershell:qnd:OS/Environment]] * [[powershell:qnd:File Operations]] * [[powershell:qnd:Output]] * [[powershell:qnd:Network]] * [[powershell:qnd:Scripts and Modules]] ====== 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 ====== * [[https://stackoverflow.com/questions/71174012/how-do-you-edit-the-command-line-in-an-external-editor|Editing commands in external editor of choice]] Example of setting VS Code as the editor used for command line editing <code powershell> '@code --new-window --wait %*' > "$HOME\codewait.cmd" $env:VISUAL = "$HOME/codewait" # Custom key binding Set-PSReadLineKeyHandler -Chord Alt+e -Function ViEditVisually </code> ====== Data Types ====== * Use ''$var.GetType()'' to get data type of variable * [[https://docs.microsoft.com/en-us/powershell/scripting/learn/deep-dives/everything-about-hashtable|hashtables]] ==== scalar ==== <code powershell> $foo = "alpha" </code> ==== array ==== <code powershell> $foo = @() $foo = "alpha", "beta" </code> <code powershell> $foo = @( "alpha" "beta" "gamma" ) </code> ==== hash table ==== <code powershell> $hash = @{} $hash = @{ Number = 1; Shape = "Square"; Color = "Blue"} </code> ===== Variables ===== * 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 ====== ==== For Loop ==== <code powershell> $fruit = @('apple','pear','banana','lemon','lime','mango') For ($i = 0; $i -le $fruit.length; $i++) { Write-Host $fruit[$i]; } </code> ==== Foreach Loop ==== <code powershell> foreach ($file in Get-ChildItem) { # do something with $file } </code> Loop over elements of array and reference the element by the automatic variable for the current element. <code powershell> $array | foreach { $_ } </code> * [[https://adamtheautomator.com/powershell-foreach/]] ==== Hash Table ==== * To loop over the items in a hash table one option is to call ''GetEnumerator()'' on the hash table. <code powershell> $t1 = @{firstname = "Michael"; lastname = "Muse"} foreach ($i in $t1.GetEnumerator()) { $i.value } </code> === Alternatively use the keys === <code powershell> $t1 = @{firstname = "Michael"; lastname = "Muse"} foreach ($i in $t1.keys) { $t1[$i] } </code> ====== Select-String ====== Example of selecting a matching line and 7 lines of context before and after the match. <code powershell> netsh http show urlacl | sls -context 7,7 wsman </code> ====== 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 <code powershell> ls | select -first 1 </code> == Example: Select all disabled user accounts == The ''Where-Object'' or ''where'' cmdlet allows a collection of objects to be filtered by some specified criteria. <code powershell> Get-ADUser -Credential $Credentials -Server pdc -Filter * -SearchBase "dc=contoso,dc=com" | Where-Object {$_.Enabled -eq $false} </code> Select properties from an object using ''Select-Object'' cmdlet. Selecting NIC name and IP address. <code powershell> Get-NetIPAddress | Select-Object InterfaceAlias, IPAddress </code> ===== Expand Property ===== ====== Get Objects - Where-Object ====== <code powershell> Get-ChildItem -Exclude @("web*", "sql*") </code> <code powershell> ls -Exclude web*,sql* </code> Example using ''-notmatch'' operator and regex to match files that don't begin with ''test''. <code powershell> ls | Where-Object {$_.name -notmatch "^test*"} </code> Example of filtering for files that contain spaces. <code powershell> ls | Where-Object {$_.name -match ".*[ ]+.*"} </code> ====== Selecting Properties ====== List the properties/methods of the returned objects. Example: <code powershell> Get-Command | Get-Members </code> Example: <code powershell> $(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;} </code> ==== Return just property values (no header) ==== <code powershell> (Get-NetIPAddresses).IPAddress </code> <code powershell> Get-NetIPAddresses | foreach {$_.IPAddress} </code> ==== Return properties with a header ==== <code powershell> Get-NetIPAddresses | Select-Object InterfaceAlias, IPAddress </code> ====== Modules ====== ====== Miscellanea ====== ==== Write current date-time to a file ==== <code> get-date | out-file -FilePath c:\test.txt </code> ==== Detect if software is installed ==== <code> $null -eq (wmic product get name | select-string "sentinelone") </code> <code> 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 } </code> ==== Redirect command history to Notepad ==== <code powershell> notepad (Get-PSReadLineOption | select -ExpandProperty HistorySavePath) </code> ====== Powershell Meta ====== * Use ''Get-Help'' to show command documentation ==== Find Commands ==== Find commands when you know part of the name. <code powershell> Get-Command | Where-Object {$_.Name -like "*csv*"} </code> <code powershell> Get-Command *csv* </code> <code powershell> Get-Command | Select-String *csv* </code> List commands in module <code powershell> Get-Command -Module <module-name> </code> Examples of getting path to executables <code powershell> Get-Command notepad CommandType Name Version Source ----------- ---- ------- ------ Application notepad.exe 10.0.19... C:\Windows\system32\notepad.exe </code> <code powershell> where.exe notepad </code> ==== Lookup Alias ==== <code powershell> Get-Alias | Where-=Object {$_.Name -like "*where*"} </code> ==== List Installed Modules ==== <code> Get-Module -ListAvailable </code> ==== Get Module Version ==== === Example === <code> Get-Module -Name Microsoft.Online.SharePoint.PowerShell -ListAvailable | Select Name,Version </code> ==== Get Module Cmdlets ==== === Example === <code> Get-command -Module Microsoft.Online.SharePoint.PowerShell </code> powershell/qnd/powershell.txt Last modified: 2024/10/24 14:24by mgupton