PowerShell
  • PowerShell
  • General Information
  • Basics
    • Structure and Naming
    • Find commands, help and history
    • Pipeline, Get-Member and Formatting
  • Troubleshooting
    • WMI & CIM
    • Gather OS and HW Information
    • Gather Networking Information
Powered by GitBook
On this page
  • Get-Command
  • Syntax
  • Get-Help
  • Updating help pages
  • Get-History
  • Transcript
  1. Basics

Find commands, help and history

PreviousStructure and NamingNextPipeline, Get-Member and Formatting

Last updated 7 years ago

Get-Command

The Get-Command cmdlet gets all commands that are installed on the computer, including cmdlets, aliases, functions, workflows, filters, scripts, and applications. Get-Command gets the commands from Windows PowerShell modules and s nap-ins and commands that were imported from other sessions. To get only commands that have been imported into the current session, use the ListImported parameter.

Syntax

Image result for powershell command syntax

Get-Help

PowerShell have one of the best help systems I've seen for console apps. I think it is even better than the man-pages in the UNIX world. I like the examples section which usually is completely enough to learn about cmdlet without reading whole help page.

Example:

help Get-Service
  • Shows the help page for get-service cmdlet

NAME
    Get-Service

SYNOPSIS
    Gets the services on a local or remote computer.


SYNTAX
    Get-Service [-ComputerName <String[]>] [-DependentServices] -DisplayName <String[]> [-Exclude <String[]>] [-Include
     <String[]>] [-RequiredServices] [<CommonParameters>]

    Get-Service [-ComputerName <String[]>] [-DependentServices] [-Exclude <String[]>] [-Include <String[]>] [-InputObje
    ct <ServiceController[]>] [-RequiredServices] [<CommonParameters>]

    Get-Service [[-Name] <String[]>] [-ComputerName <String[]>] [-DependentServices] [-Exclude <String[]>] [-Include <S
    tring[]>] [-RequiredServices] [<CommonParameters>]


DESCRIPTION
    The Get-Service cmdlet gets objects that represent the services on a local computer or on a remote computer, includ
    ing running and stopped services.

    You can direct this cmdlet to get only particular services by specifying the service name or display name of the se
    rvices, or you can pipe service objects to this cmdlet.


RELATED LINKS
    Online Version: http://go.microsoft.com/fwlink/?LinkId=821593
    New-Service
    Restart-Service
    Resume-Service
    Set-Service
    Start-Service
    Stop-Service
    Suspend-Service

REMARKS
    To see the examples, type: "get-help Get-Service -examples".
    For more information, type: "get-help Get-Service -detailed".
    For technical information, type: "get-help Get-Service -full".
    For online help, type: "get-help Get-Service -online"
help Get-Service -Examples
Gets the services on a local or remote computer.

    Example 1: Get all services on the computer

    PS C:\>Get-Service

    This command gets all of the services on the computer. It behaves as though you typed `Get-Service *`. The default
    display shows the status, service name, and display name of each service.
    Example 2: Get services that begin with a search string

    PS C:\>Get-Service "wmi*"

    This command retrieves services with service names that begin with WMI (the acronym for Windows Management Instrume
    ntation).
    Example 3: Display services that include a search string

    PS C:\>Get-Service -Displayname "*network*"

    This command displays services with a display name that includes the word network. Searching the display name finds
     network-related services even when the service name does not include "Net", such as xmlprov, the Network Provision
    ing Service.
    Example 4: Get services that begin with a search string and an exclusion

    PS C:\>Get-Service -Name "win*" -Exclude "WinRM"

    These commands get only the services with service names that begin with win, except for the WinRM service.
    Example 5: Display services that are currently active

    PS C:\>Get-Service | Where-Object {$_.Status -eq "Running"}

    This command displays only the services that are currently active. It uses the Get-Service cmdlet to get all of the
     services on the computer. The pipeline operator (|) passes the results to the Where-Object cmdlet, which selects o
    nly the services with a Status property that equals Running.

    Status is only one property of service objects. To see all of the properties, type `Get-Service | Get-Member`.
    Example 6: Get the services on a remote computer

    PS C:\>Get-Service -ComputerName "Server02"

    This command gets the services on the Server02 remote computer.

    Because the ComputerName parameter of Get-Service does not use Windows PowerShell remoting, you can use this parame
    ter even if the computer is not configured for remoting in Windows PowerShell.
    Example 7: List the services on the local computer that have dependent services

    PS C:\>Get-Service | Where-Object {$_.DependentServices} | Format-List -Property Name, DependentServices, @{Label="
    NoOfDependentServices"; Expression={$_.dependentservices.count}}



    Name                  : AudioEndpointBuilder
    DependentServices     : {AudioSrv}
    NoOfDependentServices : 1
    Name                  : Dhcp
    DependentServices     : {WinHttpAutoProxySvc}
    NoOfDependentServices : 1
    ...

    This example lists the services on the computer that have dependent services.

    The first command uses the Get-Service cmdlet to get the services on the computer. A pipeline operator (|) sends th
    e services to the Where-Object cmdlet, which selects the services whose DependentServices property is not null.

    Another pipeline operator sends the results to the Format-List cmdlet. The command uses its Property parameter to d
    isplay the name of the service, the name of the dependent services, and a calculated property that displays the num
    ber of dependent services that each service has.
    Example 8: Sort services by property value

    PS C:\>Get-Service "s*" | Sort-Object status

    Status   Name               DisplayName
    ------   ----               -----------
    Stopped  stisvc             Windows Image Acquisition (WIA)
    Stopped  SwPrv              MS Software Shadow Copy Provider
    Stopped  SysmonLog          Performance Logs and Alerts
    Running  Spooler            Print Spooler
    Running  srservice          System Restore Service
    Running  SSDPSRV            SSDP Discovery Service
    Running  ShellHWDetection   Shell Hardware Detection
    Running  Schedule           Task Scheduler
    Running  SCardSvr           Smart Card
    Running  SamSs              Security Accounts Manager
    Running  SharedAccess       Windows Firewall/Internet Connectio...
    Running  SENS               System Event Notification
    Running  seclogon           Secondary Logon

    PS C:\>Get-Service "s*" | Sort-Object status -Descending

    Status   Name               DisplayName
    ------   ----               -----------
    Running  ShellHWDetection   Shell Hardware Detection
    Running  SharedAccess       Windows Firewall/Internet Connectio...
    Running  Spooler            Print Spooler
    Running  SSDPSRV            SSDP Discovery Service
    Running  srservice          System Restore Service
    Running  SCardSvr           Smart Card
    Running  SamSs              Security Accounts Manager
    Running  Schedule           Task Scheduler
    Running  SENS               System Event Notification
    Running  seclogon           Secondary Logon
    Stopped  SysmonLog          Performance Logs and Alerts
    Stopped  SwPrv              MS Software Shadow Copy Provider
    Stopped  stisvc             Windows Image Acquisition (WIA)

    This command shows that when you sort services in ascending order by the value of their Status property, stopped se
    rvices appear before running services. This happens because the value of Status is an enumeration, in which Stopped
     has a value of 1, and Running has a value of 4.

    To list running services first, use the Descending parameter of the Sort-Object cmdlet.
    Example 9: Get services on multiple computers

    PS C:\>Get-Service -Name "WinRM" -ComputerName "localhost", "Server01", "Server02" | Format-Table -Property Machine
    Name, Status, Name, DisplayName -auto


    MachineName    Status  Name  DisplayName
    ------------   ------  ----  -----------
    localhost      Running WinRM Windows Remote Management (WS-Management)
    Server01       Running WinRM Windows Remote Management (WS-Management)
    Server02       Running WinRM Windows Remote Management (WS-Management)

    This command uses the Get-Service cmdlet to run a Get-Service Winrm command on two remote computers and the local c
    omputer ("localhost").

    The command runs on the remote computers, and the results are returned to the local computer. A pipeline operator (
    |) sends the results to the Format-Table cmdlet, which formats the services as a table. The Format-Table command us
    es the Property parameter to specify the properties displayed in the table, including the MachineName property.
    Example 10: Get the dependent services of a service

    PS C:\>Get-Service "WinRM" -RequiredServices

    This command gets the services that the WinRM service requires.

    The command returns the value of the ServicesDependedOn property of the service.
    Example 11: Get a service through the pipeline operator

    PS C:\>"WinRM" | Get-Service

    This command gets the WinRM service on the local computer. This example shows that you can pipe a service name stri
    ng (enclosed in quotation marks) to Get-Service .

Very important are the about help pages that shows how to use usually built-in features such as aliases, classes, functions, loops, comparison operators, etc.

help *about*
  • List all available about help pages

about_Arrays                      HelpFile                            Describes arrays, which are data structures de...
about_Assignment_Operators        HelpFile                            Describes how to use operators to assign value...
about_Automatic_Variables         HelpFile                            Describes variables that store state informati...
about_Break                       HelpFile                            Describes a statement you can use to immediate...
about_Checkpoint-Workflow         HelpFile                            Describes the Checkpoint-Workflow activity, which
about_CimSession                  HelpFile                            Describes a CimSession object and the differen...
about_Classes                     HelpFile                            Describes how you can use classes to develop i...
about_Command_Precedence          HelpFile                            Describes how Windows PowerShell determines wh...
about_Command_Syntax              HelpFile                            Describes the syntax diagrams that are used in...
about_Comment_Based_Help          HelpFile                            Describes how to write comment-based help topi...
about_CommonParameters            HelpFile                            Describes the parameters that can be used with...
about_Comparison_Operators        HelpFile                            Describes the operators that compare values in...
about_Continue                    HelpFile                            Describes how the Continue statement immediate...
about_Core_Commands               HelpFile                            Lists the cmdlets that are designed for use wi...
about_Data_Sections               HelpFile                            Explains Data sections, which isolate text str...
about_Debuggers                   HelpFile                            Describes the Windows PowerShell debugger.
about_DesiredStateConfiguration   HelpFile                            Provides a brief introduction to the Windows
about_Do                          HelpFile                            Runs a statement list one or more times, subje...
about_Environment_Variables       HelpFile                            Describes how to access Windows environment va...
about_Escape_Characters           HelpFile                            Introduces the escape character in Windows Pow...
about_Eventlogs                   HelpFile                            Windows PowerShell creates a Windows event log...
about_Execution_Policies          HelpFile                            Describes the Windows PowerShell execution pol...
about_For                         HelpFile                            Describes a language command you can use to ru...
about_ForEach-Parallel            HelpFile                            Describes the ForEach -Parallel language const...
about_Foreach                     HelpFile                            Describes a language command you can use to tr...
about_Format.ps1xml               HelpFile                            The Format.ps1xml files in Windows PowerShell ...
about_Functions                   HelpFile                            Describes how to create and use functions in W...
about_Functions_Advanced          HelpFile                            Introduces advanced functions that act similar...
about_Functions_Advanced_Methods  HelpFile                            Describes how functions that specify the Cmdle...
about_Functions_Advanced_Param... HelpFile                            Explains how to add parameters to advanced fun...
about_Functions_CmdletBindingA... HelpFile                            Describes the attribute that makes a function ...
about_Functions_OutputTypeAttr... HelpFile                            Describes an attribute that reports the type o...
about_Group_Policy_Settings       HelpFile                            Describes the Group Policy settings for Window...
about_Hash_Tables                 HelpFile                            Describes how to create, use, and sort hash ta...
about_Hidden                      HelpFile                            Describes the Hidden keyword, which hides clas...
about_History                     HelpFile                            Describes how to get and run commands in the c...
about_If                          HelpFile                            Describes a language command you can use to ru...
about_InlineScript                HelpFile                            Describes the InlineScript activity, which run...
about_Jobs                        HelpFile                            Provides information about how Windows PowerSh...
about_Job_Details                 HelpFile                            Provides details about background jobs on loca...
about_Join                        HelpFile                            Describes how the join operator (-join) combin...
about_Language_Keywords           HelpFile                            Describes the keywords in the Windows PowerShe...
about_Language_Modes              HelpFile                            Explains language modes and their effect on Wi...
about_Line_Editing                HelpFile                            Describes how to edit commands at the Windows ...
about_Locations                   HelpFile                            Describes how to access items from the working...
about_Logical_Operators           HelpFile                            Describes the operators that connect statement...
about_Methods                     HelpFile                            Describes how to use methods to perform action...
about_Modules                     HelpFile                            Explains how to install, import, and use Windo...
about_Objects                     HelpFile                            Provides essential information about objects i...
about_Object_Creation             HelpFile                            Explains how to create objects in Windows Powe...
about_Operators                   HelpFile                            Describes the operators that are supported by ...
about_Operator_Precedence         HelpFile                            Lists the Windows PowerShell operators in prec...
about_PackageManagement           HelpFile                            PackageManagement is an aggregator for softwar...
about_Parallel                    HelpFile                            Describes the Parallel keyword, which runs the
about_Parameters                  HelpFile                            Describes how to work with command parameters ...
about_Parameters_Default_Values   HelpFile                            Describes how to set custom default values for...
about_Parsing                     HelpFile                            Describes how Windows PowerShell parses commands.
about_Parsing_LocTest             HelpFile                            Describes how Windows PowerShell parses commands.
about_Path_Syntax                 HelpFile                            Describes the full and relative path name form...
about_Pipelines                   HelpFile                            Combining commands into pipelines in the Windo...
about_PowerShell.exe              HelpFile                            Explains how to use the PowerShell.exe command...
about_PowerShell_Ise.exe          HelpFile                            Explains how to use the PowerShell_Ise.exe com...
about_Preference_Variables        HelpFile                            Variables that customize the behavior of Windo...
about_Profiles                    HelpFile                            Describes how to create and use a Windows Powe...
about_Prompts                     HelpFile                            Describes the Prompt function and demonstrates...
about_Properties                  HelpFile                            Describes how to use object properties in Wind...
about_Providers                   HelpFile                            Describes how Windows PowerShell providers pro...
about_PSConsoleHostReadLine       HelpFile                            Explains how to create a customize how Windows...
about_PSReadline                  HelpFile
about_PSSessions                  HelpFile                            Describes Windows PowerShell sessions (PSSessi...
about_PSSession_Details           HelpFile                            Provides detailed information about Windows Po...
about_PSSnapins                   HelpFile                            Describes Windows PowerShell snap-ins and show...
about_Quoting_Rules               HelpFile                            Describes rules for using single and double qu...
about_Redirection                 HelpFile                            Explains how to redirect output from Windows P...
about_Ref                         HelpFile                            Describes how to create and use a reference va...
about_Regular_Expressions         HelpFile                            Describes regular expressions in Windows Power...
about_Remote                      HelpFile                            Describes how to run remote commands in Window...
about_Remote_Disconnected_Sess... HelpFile                            Explains how to disconnect from and reconnect ...
about_Remote_FAQ                  HelpFile                            Contains questions and answers about running r...
about_Remote_Jobs                 HelpFile                            Describes how to run background jobs on remote...
about_Remote_Output               HelpFile                            Describes how to interpret and format the outp...
about_Remote_Requirements         HelpFile                            Describes the system requirements and configur...
about_Remote_Troubleshooting      HelpFile                            Describes how to troubleshoot remote operation...
about_Remote_Variables            HelpFile                            Explains how to use local and remote variables...
about_Requires                    HelpFile                            Prevents a script from running without the req...
about_Reserved_Words              HelpFile                            Lists the reserved words that cannot be used a...
about_Return                      HelpFile                            Exits the current scope, which can be a functi...
about_Run_With_PowerShell         HelpFile                            Explains how to use the "Run with PowerShell" ...
about_Scheduled_Jobs              HelpFile                            Describes scheduled jobs and explains how to u...
about_Scheduled_Jobs_Advanced     HelpFile                            Explains advanced scheduled job topics, includ...
about_Scheduled_Jobs_Basics       HelpFile                            Explains how to create and manage scheduled jobs.
about_Scheduled_Jobs_Troublesh... HelpFile                            Explains how to resolve problems with schedule...
about_Scopes                      HelpFile                            Explains the concept of scope in Windows Power...
about_Scripts                     HelpFile                            Describes how to run and write scripts in Wind...
about_Script_Blocks               HelpFile                            Defines what a script block is and explains ho...
about_Script_Internationalization HelpFile                            Describes the script internationalization feat...
about_Sequence                    HelpFile                            Describes the Sequence keyword, which runs sel...
about_Session_Configurations      HelpFile                            Describes session configurations, which determ...
about_Session_Configuration_Files HelpFile                            Describes session configuration files, which c...
about_Signing                     HelpFile                            Explains how to sign scripts so that they comp...
about_Special_Characters          HelpFile                            Describes the special characters that you can ...
about_Splatting                   HelpFile                            Describes how to use splatting to pass paramet...
about_Split                       HelpFile                            Explains how to use the Split operator to spli...
about_Suspend-Workflow            HelpFile                            Describes the Suspend-Workflow activity, which...
about_Switch                      HelpFile                            Explains how to use a switch to handle multipl...
about_Throw                       HelpFile                            Describes the Throw keyword, which generates a...
about_Transactions                HelpFile                            Describes how to manage transacted operations ...
about_Trap                        HelpFile                            Describes a keyword that handles a terminating...
about_Try_Catch_Finally           HelpFile                            Describes how to use the Try, Catch, and Final...
about_Types.ps1xml                HelpFile                            Explains how to use Types.ps1xml files to exte...
about_Type_Operators              HelpFile                            Describes the operators that work with Microso...
about_Updatable_Help              HelpFile                            Describes the updatable help system in Windows...
about_Variables                   HelpFile                            Describes how variables store values that can ...
about_While                       HelpFile                            Describes a language statement that you can us...
about_Wildcards                   HelpFile                            Describes how to use wildcard characters in Wi...
about_Windows_PowerShell_5.0      HelpFile                            Describes new features that are included in
about_Windows_PowerShell_ISE      HelpFile                            Describes the features and system requirements...
about_Windows_RT                  HelpFile                            Explains limitations of Windows PowerShell 4.0...
about_WMI                         HelpFile                            Windows Management Instrumentation (WMI) uses the
about_WMI_Cmdlets                 HelpFile                            Provides background information about Windows ...
about_WorkflowCommonParameters    HelpFile                            This topic describes the parameters that are v...
about_Workflows                   HelpFile                            Provides a brief introduction to the Windows
about_WQL                         HelpFile                            Describes WMI Query Language (WQL), which can be
about_WS-Management_Cmdlets       HelpFile                            Provides an overview of Web Services for Manag...
WSManAbout                        HelpFile
about_posh-git                    HelpFile                            posh-git integrates Git and PowerShell providi...
about_BeforeEach_AfterEach        HelpFile                            performed at the beginning and end of every It...
about_Mocking                     HelpFile                            Pester provides a set of Mocking functions mak...
about_Pester                      HelpFile                            Pester is a BDD based test runner for PowerShell.
about_should                      HelpFile                            Provides assertion convenience methods for com...
about_TestDrive                   HelpFile                            A PSDrive for file activity limited to the sco...
about_Scheduled_Jobs              HelpFile                            Describes scheduled jobs and explains how to u...
about_Scheduled_Jobs_Advanced     HelpFile                            Explains advanced scheduled job topics, includ...
about_Scheduled_Jobs_Basics       HelpFile                            Explains how to create and manage scheduled jobs.
about_Scheduled_Jobs_Troublesh... HelpFile                            Explains how to resolve problems with schedule...
about_ActivityCommonParameters    HelpFile                            Describes the parameters that Windows PowerShell
about_Checkpoint-Workflow         HelpFile                            Describes the Checkpoint-Workflow activity, which
about_ForEach-Parallel            HelpFile                            Describes the ForEach -Parallel language const...
about_InlineScript                HelpFile                            Describes the InlineScript activity, which run...
about_Parallel                    HelpFile                            Describes the Parallel keyword, which runs the
about_Sequence                    HelpFile                            Describes the Sequence keyword, which runs sel...
about_Suspend-Workflow            HelpFile                            Describes the Suspend-Workflow activity, which...
about_WorkflowCommonParameters    HelpFile                            This topic describes the parameters that are v...
about_Workflows
help about_foreach
TOPIC
    about_Foreach

SHORT DESCRIPTION
    Describes a language command you can use to traverse all the items in a
    collection of items.


LONG DESCRIPTION
    The Foreach statement (also known as a Foreach loop) is a language
    construct for stepping through (iterating) a series of values in a
    collection of items.


    The simplest and most typical type of collection to traverse is an array.
    Within a Foreach loop, it is common to run one or more commands against
    each item in an array.


  Syntax
      The following shows the ForEach syntax:


          foreach ($<item> in $<collection>){<statement list>}

  Simplified syntax
      Starting in Windows PowerShell 3.0, syntax with language keywords such
      as Where and ForEach was simplified. Comparison operators that work on
      the members of a collection are treated as parameters. You can use a method
      on the members of a collection without containing it in a script block
      or adding the automatic variable "$_.". Consider the following two examples:

          dir cert:\ -Recurse | foreach GetKeyAlgorithm
          dir cert:\ -Recurse | foreach {$_.GetKeyAlgorithm()}

      Although both commands work, the first returns results without using
      a script block or the $_. automatic variable. The method GetKeyAlgorithm
      is treated as a parameter of ForEach. The first command returns the same results,
      but without errors, because the simplified syntax does not attempt to return
      results for items for which the specified argument did not apply.

      In this example, the Get-Process property Description is passed as a parameter
      argument of the ForEach statement. The results are the descriptions of active
      processes.

          Get-Process | ForEach Description

  The Foreach statement outside a command pipeline
      The part of the Foreach statement enclosed in parenthesis represents a
      variable and a collection to iterate. Windows PowerShell creates the
      variable ($<item>) automatically when the Foreach loop runs. Prior to
      each iteration through the loop, the variable is set to a value in the
      collection. The block following a Foreach statement {<statement list>}
      contains a set of commands to execute against each item in a collection.


  Examples
      For example, the Foreach loop in the following example displays the
      values in the $letterArray array.


          $letterArray = "a","b","c","d"
          foreach ($letter in $letterArray)
          {
              Write-Host $letter
          }

Updating help pages

Open PowerShell as an Administrator and run

Update-Help
Updating Help for module ActiveDirectory
    Installing Help content...
    [oooooooo                                                  ]

  • Always run Update-Help after installing new Roles and Features!

Get-History

PowerShell by default doesn't preserve history between different PowerShell Sessions. This means that once you close your console, you'll loose it all :-(

get-history # or just 'history'
  • Show history of commands for this session

get-history | out-file c:\scripts\history\history01.txt
  • Output history of commands into a file

  Id CommandLine
  -- -----------
   1 cd E:
   2 get-verb
   3 get-alias
   4 get-command *-service
   5 get-verb -verb s*
   6 help get-command
   7 cls
   8 get-service
   9 show-command get-service
  10 help get-service
  11 help get-service -online
  12 help get-service -examples
  13 help *about*
  14 help about_foreach

Transcript

Creates a record of all or part of a Windows PowerShell session to a text file. (We can compare it to Excel Record Macro functionality probably)

start-transcript -path c:\scripts\transcript01.txt  # starts recording
stop-transcript                                     # stops recording