Learning PowerShell

General / Intro

  • Powershell commands are case-insensitive
  • Use tab-completion
  • Launch the Integrated Script Environment by typing ISE in the powershell. From within ISE, explore:
    • Command Add-on (Menu Item: View | Show Command Add-on)
    • Remote Powershell (Menu Item: File | New Remote Powershell Tab)

Know the powershell version

$PSVersionTable

Output:

Name                           Value
---- -----
PSVersion 5.1.22000.2538
PSEdition Desktop
PSCompatibleVersions {1.0, 2.0, 3.0, 4.0...}
BuildVersion 10.0.22000.2538
CLRVersion 4.0.30319.42000
WSManStackVersion 3.0
PSRemotingProtocolVersion 2.3
SerializationVersion 1.1.0.1

Help

Get help on help

Get-Help

Get help on any commandlet (e.g. on commandlet Get-Command)

Get-help Get-Command
Get-Help Get-Command -examples
Get-Help Get-Command -detailed
Get-Help Get-Command -full
Get-Help Get-Command -online

List available commandlets, functions, aliases etc.

Get-Command

Output (snipped):

CommandType     Name                                               Version    Source
----------- ---- ------- ------
Alias Add-AppPackage 2.0.1.0 Appx
Alias Add-AppPackageVolume 2.0.1.0 Appx
Alias Add-AppProvisionedPackage 3.0 Dism
Alias Add-ProvisionedAppPackage 3.0 Dism
Alias Add-ProvisionedAppSharedPackageContainer 3.0 Dism
Alias Add-ProvisionedAppxPackage 3.0 Dism
Alias Add-ProvisioningPackage 3.0 Provisioning
Alias Add-TrustedProvisioningCertificate 3.0 Provisioning
Alias Apply-WindowsUnattend 3.0 Dism
Alias Disable-PhysicalDiskIndication 2.0.0.0 Storage
Alias Disable-PhysicalDiskIndication 1.0.0.0 VMDirectStorage
.
.
.

List only particular command types (e.g. commandlets / functions / aliases)

 Get-Command -CommandType Cmdlet
 Get-Command -CommandType Function
 Get-Command -CommandType Alias

List all the columns offered by a particular command output

Get-Member command lists all the columns (object and object members) offered by a particular command output.

Usage: Pipe the output of a command through ‘get-member’

The following example shows all columns offered by Get-Command

 Get-Command | Get-Member

Output (snipped):

   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;}
.
.
.

Create and explore a simple function

function greeting {
>>  write-output "Greetings, cheerful greetings"
>> }

# Call the new function
greeting

Output:

Greetings, cheerful greetings

Spot the new function using Get-Command

Get-Command greeting

Output:

CommandType     Name                                               Version    Source
----------- ---- ------- ------
Function greeting

Get help on the new function using Get-Help

Get-Help greeting

Output:

NAME
greeting

SYNTAX
greeting

ALIASES
None

REMARKS
None

Risk mitigation parameters

Risk mitigation parameter -WhatIf

 Get-Service | Stop-Service -WhatIf

Output (snipped):

What if: Performing the operation "Stop-Service" on target "Agent Activation Runtime_365e0dba (AarSvc_365e0dba)".
What if: Performing the operation "Stop-Service" on target "Adobe Acrobat Update Service (AdobeARMservice)".
What if: Performing the operation "Stop-Service" on target "AllJoyn Router Service (AJRouter)".
What if: Performing the operation "Stop-Service" on target "Application Layer Gateway Service (ALG)".
What if: Performing the operation "Stop-Service" on target "Application Identity (AppIDSvc)".
What if: Performing the operation "Stop-Service" on target "Application Information (Appinfo)".
.
.
.

Risk mitigation parameter -Confirm

 Get-Service | Stop-Service -Confirm 

Output (snipped):

Confirm
Are you sure you want to perform this action?
Performing the operation "Stop-Service" on target "Agent Activation Runtime_365e0dba (AarSvc_365e0dba)".
[Y] Yes [A] Yes to All [N] No [L] No to All [S] Suspend [?] Help (default is "Y"): n

Confirm
Are you sure you want to perform this action?
Performing the operation "Stop-Service" on target "Adobe Acrobat Update Service (AdobeARMservice)".
[Y] Yes [A] Yes to All [N] No [L] No to All [S] Suspend [?] Help (default is "Y"): N

Confirm
Are you sure you want to perform this action?
Performing the operation "Stop-Service" on target "AllJoyn Router Service (AJRouter)".
[Y] Yes [A] Yes to All [N] No [L] No to All [S] Suspend [?] Help (default is "Y"):
.
.
.

Output can be tailored by using following commands:

  • format-*
  • out-*
  • export-*

Format-* commands

Get-Command Format-*

Output:

CommandType     Name                                               Version    Source
----------- ---- ------- ------
Function Format-Hex 3.1.0.0 Microsoft.PowerShell.Utility
Function Format-Volume 2.0.0.0 Storage
Cmdlet Format-Custom 3.1.0.0 Microsoft.PowerShell.Utility
Cmdlet Format-List 3.1.0.0 Microsoft.PowerShell.Utility
Cmdlet Format-SecureBootUEFI 2.0.0.0 SecureBoot
Cmdlet Format-Table 3.1.0.0 Microsoft.PowerShell.Utility
Cmdlet Format-Wide 3.1.0.0 Microsoft.PowerShell.Utility

Example of Format-List
Get-Service | Format-List ServiceName, DisplayName, StartType, Status

Output:

ServiceName : AarSvc_365e0dba
DisplayName : Agent Activation Runtime_365e0dba
StartType : Manual
Status : Stopped

ServiceName : AdobeARMservice
DisplayName : Adobe Acrobat Update Service
StartType : Automatic
Status : Running

ServiceName : AJRouter
DisplayName : AllJoyn Router Service
StartType : Manual
Status : Stopped

ServiceName : ALG
DisplayName : Application Layer Gateway Service
StartType : Manual
Status : Stopped
.
.
.

Another example of Format-List (show all the values)

An asterisk shows all the values associated with the objects

Get-Service | Format-List *

Output (snipped):


Name : AarSvc_365e0dba
RequiredServices : {}
CanPauseAndContinue : False
CanShutdown : False
CanStop : False
DisplayName : Agent Activation Runtime_365e0dba
DependentServices : {}
MachineName : .
ServiceName : AarSvc_365e0dba
ServicesDependedOn : {}
ServiceHandle :
Status : Stopped
ServiceType : 224
StartType : Manual
Site :
Container :

Name : AdobeARMservice
RequiredServices : {}
CanPauseAndContinue : False
CanShutdown : False
CanStop : True
DisplayName : Adobe Acrobat Update Service
DependentServices : {}
MachineName : .
ServiceName : AdobeARMservice
ServicesDependedOn : {}
ServiceHandle :
Status : Running
ServiceType : Win32OwnProcess
StartType : Automatic
Site :
Container :

Name : AJRouter
RequiredServices : {}
CanPauseAndContinue : False
CanShutdown : False
.
.
.

Example of Format-Table
Get-Service | Format-Table ServiceName, DisplayName, StartType, Status

Output (snipped):

ServiceName                                 StartType  Status
----------- --------- ------
AarSvc_365e0dba Manual Stopped
AdobeARMservice Automatic Running
AJRouter Manual Stopped
ALG Manual Stopped
AppIDSvc Manual Stopped
Appinfo Manual Running
AppMgmt Manual Stopped
AppReadiness Manual Stopped
AppVClient Disabled Stopped
AppXSvc Manual Stopped
.
.
.

Out-* commands

Get-Command Out-*

Output:

CommandType     Name                                               Version    Source
----------- ---- ------- ------
Cmdlet Out-Default 3.0.0.0 Microsoft.PowerShell.Core
Cmdlet Out-File 3.1.0.0 Microsoft.PowerShell.Utility
Cmdlet Out-GridView 3.1.0.0 Microsoft.PowerShell.Utility
Cmdlet Out-Host 3.0.0.0 Microsoft.PowerShell.Core
Cmdlet Out-Null 3.0.0.0 Microsoft.PowerShell.Core
Cmdlet Out-Printer 3.1.0.0 Microsoft.PowerShell.Utility
Cmdlet Out-String 3.1.0.0 Microsoft.PowerShell.Utility

Out-GridView explained

Out-GridView pops a user-friendly interface which facilitates filtering / sorting through UI

Get-Service | Out-GridView

Export-* commands

Get-Command Export-*

Output:

CommandType     Name                                               Version    Source
----------- ---- ------- ------
Function Export-BCCachePackage 1.0.0.0 BranchCache
Function Export-BCSecretKey 1.0.0.0 BranchCache
Function Export-ODataEndpointProxy 1.0 Microsoft.PowerShell.ODataUtils
Function Export-ScheduledTask 1.0.0.0 ScheduledTasks
Function Export-WinhttpProxy 1.0.0.0 WinHttpProxy
Cmdlet Export-Alias 3.1.0.0 Microsoft.PowerShell.Utility
Cmdlet Export-BcdStore 1.0.0 Microsoft.Windows.Bcd.Cmdlets
Cmdlet Export-BinaryMiLog 1.0.0.0 CimCmdlets
Cmdlet Export-Certificate 1.0.0.0 PKI
Cmdlet Export-Clixml 3.1.0.0 Microsoft.PowerShell.Utility
Cmdlet Export-Console 3.0.0.0 Microsoft.PowerShell.Core
Cmdlet Export-Counter 3.0.0.0 Microsoft.PowerShell.Diagnostics
Cmdlet Export-Csv 3.1.0.0 Microsoft.PowerShell.Utility
Cmdlet Export-FormatData 3.1.0.0 Microsoft.PowerShell.Utility
Cmdlet Export-ModuleMember 3.0.0.0 Microsoft.PowerShell.Core
Cmdlet Export-PfxCertificate 1.0.0.0 PKI
Cmdlet Export-ProvisioningPackage 3.0 Provisioning
Cmdlet Export-PSSession 3.1.0.0 Microsoft.PowerShell.Utility
Cmdlet Export-StartLayout 1.0.0.1 StartLayout
Cmdlet Export-StartLayoutEdgeAssets 1.0.0.1 StartLayout
Cmdlet Export-TlsSessionTicketKey 2.0.0.0 TLS
Cmdlet Export-Trace 3.0 Provisioning
Cmdlet Export-UevConfiguration 2.1.639.0 UEV
Cmdlet Export-UevPackage 2.1.639.0 UEV
Cmdlet Export-WindowsCapabilitySource 3.0 Dism
Cmdlet Export-WindowsDriver 3.0 Dism
Cmdlet Export-WindowsImage 3.0 Dism

Sorting the output

Get-Service | Sort-Object -Property ServicesDependedOn -Descending | Format-Table Name, ServicesDependedOn

Output (snipped):

Name                                        ServicesDependedOn
---- ------------------
XblGameSave {XblAuthManager, UserManager}
WMPNetworkSvc {WSearch, http}
iphlpsvc {WinHttpAutoProxySvc, nsi, RpcSS, tcpip}
WdNisSvc {WdNisDrv}
WlanSvc {wcmsvc, RpcSs, nativewifip, Ndisuio}
vmictimesync {VmGid}
CDPSvc {Tcpip, ncbservice, RpcSS}
PolicyAgent {Tcpip, bfe}
PCManager Service Store {staterepository}
WslInstaller {staterepository}
RasMan {SstpSvc, DnsCache}
LanmanServer {SamSS, Srv2}
wlpasvc {RpcSs, WwanSvc}
.
.
.

Note that the order of pipe is important. For example, in the series of command below the objects are lost by the time Sort-Object is invoked and hence the error:

Get-Service | Format-Table Name, ServicesDependedOn | Sort-Object -Property ServicesDependedOn

Output:

<todo> Select-Object, Get-module, Get-Module -ListAvailable, Install-module, Get-command -module xyz, Get-ExecutionPolicy, Set-ExecutionPolicy

<todo> winget search Microsoft.PowerShell
winget install –id Microsoft.PowerShell –source winget