Working with Windows PowerShell

Working with Windows PowerShell

In this section we will cover the basics of using Windows PowerShell. First, we will look into the Get-Help cmdlet (pronounced “command-let”), which displays information about cmdlets and conceptual topics in Windows PowerShell. Then, we will discuss a few of the basic cmdlets, how to use cmdlet parameters, and how to format the output of the cmdlets to get the data required to create a useful output. Finally, we will cover how to use aliases in Windows PowerShell, how to run traditional Windows applications in Windows PowerShell, and how to manage errors.

Getting Help

To get the help about any cmdlet, PowerShell provides Get-Help cmdlet. The Get-Help cmdlet is a useful tool for learning about Windows PowerShell. By reading the descriptions of the cmdlets, learning about the concepts, and exploring the language topics, you can learn how to use Windows PowerShell.

If you are new to PowerShell, the first topic of interest might be the Get-Help cmdlet itself. To display information about the Help system in Windows PowerShell, run the following command:

PS C:\Users\Surender\Documents> Get-Help

TOPIC
    Windows PowerShell Help System

SHORT DESCRIPTION
    Displays help about Windows PowerShell cmdlets and concepts.

LONG DESCRIPTION
    Windows PowerShell Help describes Windows PowerShell cmdlets,
    functions, scripts, and modules, and explains concepts, including
    the elements of the Windows PowerShell language.

    Windows PowerShell does not include help files, but you can read the help topics online, or use the Update-Help cmdlet to download help files to your computer and then use the Get-Help cmdlet to display the help topics at the command line.

    You can also use the Update-Help cmdlet to download updated help files as they are released so that your local help content is never obsolete.

    Without help files, Get-Help displays auto-generated help for cmdlets, functions, and scripts.


  ONLINE HELP
    You can find help for Windows PowerShell online in the TechNet Library beginning at http://go.microsoft.com/fwlink/?LinkID=108518.

    To open online help for any cmdlet or function, type:

        Get-Help <cmdlet-name> -Online

  UPDATE-HELP
    To download and install help files on your computer:

       1. Start Windows PowerShell with the "Run as administrator" option.
       2. Type:

          Update-Help

    After the help files are installed, you can use the Get-Help cmdlet to display the help topics. You can also use the Update-Help cmdlet to download updated help files so that your local help files are always up-to-date.

    For more information about the Update-Help cmdlet, type:

       Get-Help Update-Help -Online

    or go to: http://go.microsoft.com/fwlink/?LinkID=210614


  GET-HELP
    The Get-Help cmdlet displays help at the command line from content in help files on your computer. Without help files, Get-Help displays basic help about cmdlets and functions. You can also use Get-Help to display online help for cmdlets and functions.

    To get help for a cmdlet, type:

        Get-Help <cmdlet-name>

    To get online help, type:

        Get-Help <cmdlet-name> -Online

    The titles of conceptual topics begin with "About_".
    To get help for a concept or language element, type:

        Get-Help About_<topic-name>

    To search for a word or phrase in all help files, type:

        Get-Help <search-term>

    For more information about the Get-Help cmdlet, type:

        Get-Help Get-Help -Online

    or go to: http://go.microsoft.com/fwlink/?LinkID=113316


  EXAMPLES:
      Save-Help              : Download help files from the Internet and saves them on a file share.
      Update-Help            : Downloads and installs help files from the Internet or a file share.
      Get-Help Get-Process   : Displays help about the Get-Process cmdlet.
      Get-Help Get-Process -Online
                             : Opens online help for the Get-Process cmdlet.
      Help Get-Process       : Displays help about Get-Process one page at a time.
      Get-Process -?         : Displays help about the Get-Process cmdlet.
      Get-Help About_Modules : Displays help about Windows PowerShell modules.
      Get-Help remoting      : Searches the help topics for the word "remoting."

  SEE ALSO:
      about_Updatable_Help
      Get-Help
      Save-Help
      Update-Help

I would recommend using Update-Help command if your system is connected to Internet. The Update-Help command will update the help files for various PowerShell cmdlets.

To display the simplest view of Help for a cmdlet, type “Get-Help” followed by the cmdlet name. For example, to get Help for the Get-Command cmdlet, type:

PS C:\Users\Surender\Documents> Get-Help Get-Command

NAME
    Get-Command

SYNTAX
    Get-Command [[-ArgumentList] <Object[]>] [-Verb <string[]>] [-Noun <string[]>] [-Module <string[]>] [-TotalC
    <int>] [-Syntax] [-All] [-ListImported] [-ParameterName <string[]>] [-ParameterType <PSTypeName[]>]
    [<CommonParameters>]

    Get-Command [[-Name] <string[]>] [[-ArgumentList] <Object[]>] [-Module <string[]>] [-CommandType <CommandTyp
    {Alias | Function | Filter | Cmdlet | ExternalScript | Application | Script | Workflow | Configuration | All
    [-TotalCount <int>] [-Syntax] [-All] [-ListImported] [-ParameterName <string[]>] [-ParameterType <PSTypeName
    [<CommonParameters>]


ALIASES
    gcm


REMARKS
    Get-Help cannot find the Help files for this cmdlet on this computer. It is displaying only partial help.
        -- To download and install Help files for the module that includes this cmdlet, use Update-Help.
        -- To view the Help topic for this cmdlet online, type: "Get-Help Get-Command -Online" or
           go to http://go.microsoft.com/fwlink/?LinkID=113309.

If the cmdlet Help is not formatted correctly, that is, if it begins with XMLNS tags, the Windows PowerShell execution policy on your system might have prevented the system from loading the configuration file that formats cmdlet Help. You may need to change the system ExecutionPolicy as shown here.

To display detailed Help for any cmdlet, including parameter descriptions and examples, use the Detailed parameter of Get-Help. For example, to get detailed Help for the Get-Command cmdlet, type:

PS C:\Users\Surender\Documents> Get-Help Get-Command -Detailed

NAME
    Get-Command

SYNTAX
    Get-Command [[-ArgumentList] <Object[]>] [-Verb <string[]>] [-Noun <string[]>] [-Module <string[]>] [-TotalCount
    <int>] [-Syntax] [-All] [-ListImported] [-ParameterName <string[]>] [-ParameterType <PSTypeName[]>]
    [<CommonParameters>]

    Get-Command [[-Name] <string[]>] [[-ArgumentList] <Object[]>] [-Module <string[]>] [-CommandType <CommandTypes>
    {Alias | Function | Filter | Cmdlet | ExternalScript | Application | Script | Workflow | Configuration | All}]
    [-TotalCount <int>] [-Syntax] [-All] [-ListImported] [-ParameterName <string[]>] [-ParameterType <PSTypeName[]>]
    [<CommonParameters>]


PARAMETERS
    -All

    -ArgumentList <Object[]>

    -CommandType <CommandTypes>

    -ListImported

    -Module <string[]>

    -Name <string[]>

    -Noun <string[]>

    -ParameterName <string[]>

    -ParameterType <PSTypeName[]>

    -Syntax

    -TotalCount <int>

    -Verb <string[]>

    <CommonParameters>
        This cmdlet supports the common parameters: Verbose, Debug,
        ErrorAction, ErrorVariable, WarningAction, WarningVariable,
        OutBuffer, PipelineVariable, and OutVariable. For more information, see about_CommonParameters (http://go.microsoft.com/fwlink/?LinkID=113216).


ALIASES
    gcm


REMARKS
    Get-Help cannot find the Help files for this cmdlet on this computer. It is displaying only partial help.
        -- To download and install Help files for the module that includes this cmdlet, use Update-Help.
        -- To view the Help topic for this cmdlet online, type: "Get-Help Get-Command -Online" or
           go to http://go.microsoft.com/fwlink/?LinkID=113309.

To display all of the available Help for a cmdlet, including technical information about the cmdlet and its parameters, use the Full parameter. For example, to get complete Help for the Get-Command cmdlet, type:

Get-Help Get-Command -Full

You can also display selected parts of the Help file. To see only the examples, use the Examples parameter. For example, to display the examples for the Get-Command cmdlet, type:

Get-Help Get-Command -Examples

To see only detailed parameter descriptions, use the Parameter parameter of Get-Help. You can specify the name of a parameter or use the wildcard character (*) to specify all parameters. For example, to see a description of the TotalCount parameter of Get-Command, type:

Get-Help Get-Command -Parameter TotalCount

To see all parameters of the Get-Command cmdlet, type:

Get-Help Get-Command -Parameter *

Using Cmdlets (Command-lets)

A cmdlet is a simple, single-function command-line tool. You use cmdlets just as you would use traditional command-line commands and utilities. Begin by typing the name of the cmdlet at the Windows PowerShell command prompt. Windows PowerShell commands are not case-sensitive, so you can type in any case.

For example, try the Get-Date cmdlet:

PS C:\Users\Surender\Documents> Get-Date

14-09-2015 11:20:19 AM

To find the cmdlets (and other types of commands) that are available to you, use the Get-Command cmdlet.

PS C:\Users\Surender\Documents> Get-Command

CommandType     Name                                               ModuleName
-----------     ----                                               ----------
Alias           Add-ProvisionedAppxPackage                         Dism
Alias           Add-VMToCluster                                    FailoverClusters
Alias           Add-WindowsFeature                                 ServerManager
Alias           Apply-WindowsUnattend                              Dism
Alias           Expand-IscsiVirtualDisk                            IscsiTarget
Alias           Export-DnsServerTrustAnchor                        DnsServer
Alias           Flush-Volume                                       Storage
Alias           Get-GPPermissions                                  GroupPolicy

[output cut]

By default PowerShell will list all the available commands weather these are Alias, Functions or cmdlets. If you only want to list the cmdlets, use Get-Command with -CommandType parameter as shown below:

PS C:\Users\Surender\Documents> Get-Command -CommandType cmdlet

CommandType     Name                                               ModuleName
-----------     ----                                               ----------
Cmdlet          Add-ADCentralAccessPolicyMember                    ActiveDirectory
Cmdlet          Add-ADComputerServiceAccount                       ActiveDirectory
Cmdlet          Add-ADDomainControllerPasswordReplicationPolicy    ActiveDirectory
Cmdlet          Add-ADFineGrainedPasswordPolicySubject             ActiveDirectory
Cmdlet          Add-ADGroupMember                                  ActiveDirectory
Cmdlet          Add-ADPrincipalGroupMembership                     ActiveDirectory
Cmdlet          Add-ADResourcePropertyListMember                   ActiveDirectory
Cmdlet          Add-AppxPackage                                    Appx
Cmdlet          Add-AppxProvisionedPackage                         Dism
Cmdlet          Add-BitsFile                                       BitsTransfer
Cmdlet          Add-CauClusterRole                                 ClusterAwareUpdating
Cmdlet          Add-CertificateEnrollmentPolicyServer              PKI

[output cut]

Windows PowerShell cmdlets use a very simple naming convention such as verb and noun separated by a dash (-). When you know and understand the various verbs, using the Get-Command cmdlet becomes much more valuable. For example, when you are looking for information about various items, you know you will more than likely use the Get verb. Therefore, use the Get-Command cmdlet to retrieve only cmdlets that use the get verb. This is done using following command:

PS C:\Users\Surender\Documents> Get-Command –verb get

CommandType     Name                                               ModuleName
-----------     ----                                               ----------
Alias           Get-GPPermissions                                  GroupPolicy
Alias           Get-PhysicalDiskSNV                                Storage
Alias           Get-ProvisionedAppxPackage                         Dism
Alias           Get-VpnServerIPsecConfiguration                    RemoteAccess
Function        Get-AppBackgroundTask                              AppBackgroundTask
Function        Get-AppxLastError                                  Appx
Function        Get-AppxLog                                        Appx
Function        Get-AssignedAccess                                 AssignedAccess
Function        Get-BCClientConfiguration                          BranchCache
Function        Get-BCContentServerConfiguration                   BranchCache
Function        Get-BCDataCache                                    BranchCache

[output cut]

If you want to look at the cmdlets that will assign a new value to something, you more than likely are looking for a cmdlet that uses the Set verb. The following command retrieves these types of cmdlets.

PS C:\Users\Surender\Documents> Get-Command –verb set

CommandType     Name                                               ModuleName
-----------     ----                                               ----------
Alias           Set-GPPermissions                                  GroupPolicy
Alias           Set-VpnServerIPsecConfiguration                    RemoteAccess
Function        Set-AssignedAccess                                 AssignedAccess
Function        Set-BCAuthentication                               BranchCache
Function        Set-BCCache                                        BranchCache
Function        Set-BCDataCacheEntryMaxAge                         BranchCache
Function        Set-BCMinSMBLatency                                BranchCache
Function        Set-BCSecretKey                                    BranchCache
Function        Set-BgpPeer                                        RemoteAccess
Function        Set-BgpRouter                                      RemoteAccess
Function        Set-BgpRoutingPolicy                               RemoteAccess
Function        Set-BgpRoutingPolicyForPeer                        RemoteAccess

[output cut]

You can also use the Get-Command cmdlet to search for the cmdlets with specific noun. For example, to find cmdlets that manage Network adapter, use a command as shown below. Because cmdlet names are usually singular, not plural, the command searches for cmdlets with names that include “NetAdapter”.

PS C:\Users\Surender\Documents> Get-Command -Name *NetAdapter*

CommandType     Name                                               ModuleName
-----------     ----                                               ----------
Function        Disable-NetAdapter                                 NetAdapter
Function        Disable-NetAdapterBinding                          NetAdapter
Function        Disable-NetAdapterChecksumOffload                  NetAdapter
Function        Disable-NetAdapterEncapsulatedPacketTaskOffload    NetAdapter
Function        Disable-NetAdapterIPsecOffload                     NetAdapter
Function        Disable-NetAdapterLso                              NetAdapter
Function        Disable-NetAdapterPowerManagement                  NetAdapter
Function        Disable-NetAdapterQos                              NetAdapter
Function        Disable-NetAdapterRdma                             NetAdapter
Function        Disable-NetAdapterRsc                              NetAdapter
Function        Disable-NetAdapterRss                              NetAdapter
Function        Disable-NetAdapterSriov                            NetAdapter
Function        Disable-NetAdapterVmq                              NetAdapter
Function        Enable-NetAdapter                                  NetAdapter

[output cut]

Using Cmdlet Parameters

The parameters of a cmdlet let you customize the behavior of the cmdlet. Windows PowerShell cmdlets can have none, one, or many parameters. Most cmdlets have several parameters, and it’s important to become familiar with them, because they can make the cmdlet do just what you need it to do.

The cmdlet parameters are identified by a hyphen (-) followed by the parameter name. Remember that slashes (/ and \) are not used with parameters in Windows PowerShell.

When you type a parameter name, you can type the whole name or only the enough characters to distinguish the parameter name from the names of other parameters for that cmdlet.

For example, the Get-Command cmdlet has a parameter named “detailed”. You can type “-det”, which is just enough to distinguish it from the other parameter name.

Some parameter names are optional. You can use the parameter by typing a parameter value without typing the parameter name. However, if you omit the parameter name, the parameter value must appear in the in the same position in the command that it appears in the syntax diagram.

For example, the Get-Help (or in fact most of) cmdlet(s) has a Name parameter that specifies the name of a cmdlet or concept. You can type the name of the Name parameter or leave it out. To get Help for the Get-Alias cmdlet, you can either use “Get-Help -Name Get-Alias” command or simply use “Get-Help Get-Alias” command. Both will work fine.

PS C:\Users\Surender\Documents> Get-Help -Name Get-Alias

NAME
    Get-Alias

SYNTAX
    Get-Alias [[-Name] <string[]>] [-Exclude <string[]>] [-Scope <string>]  [<CommonParameters>]

    Get-Alias [-Exclude <string[]>] [-Scope <string>] [-Definition <string[]>]  [<CommonParameters>]


ALIASES
    gal

[output cut]

Notice the syntax of command. The parameter names which are optional appear in square brackets, such as Get-Alias [-Name] [-Exclude] [-Scope]. In this context, every parameter is optional because you can run Get-Alias cmdlet without any parameter. Some PowerShell cmdlets (e.g. Enter-PSSession) have mandatory parameters which are required to be entered. If you omit a mandatory parameter, the PowerShell will prompt you to enter the parameter value during runtime. To view which parameters are Mandatory and which are optional, you can use Get-Help command with -Full parameter as shown below:

PS C:\Users\Surender\Documents> Get-Help Enter-PSSession -Full

NAME
    Enter-PSSession

SYNTAX
    Enter-PSSession [-ComputerName] <string> [-EnableNetworkAccess] [-Credential <pscredential>] [-Port <int>]
    [-UseSSL] [-ConfigurationName <string>] [-ApplicationName <string>] [-SessionOption <PSSessionOption>]
    [-Authentication <AuthenticationMechanism> {Default | Basic | Negotiate | NegotiateWithImplicitCredential |
    Credssp | Digest | Kerberos}] [-CertificateThumbprint <string>]  [<CommonParameters>]

    Enter-PSSession [[-Session] <PSSession>]  [<CommonParameters>]

    Enter-PSSession [[-ConnectionUri] <uri>] [-EnableNetworkAccess] [-Credential <pscredential>] [-ConfigurationName
    <string>] [-AllowRedirection] [-SessionOption <PSSessionOption>] [-Authentication <AuthenticationMechanism>
    {Default | Basic | Negotiate | NegotiateWithImplicitCredential | Credssp | Digest | Kerberos}]
    [-CertificateThumbprint <string>]  [<CommonParameters>]

    Enter-PSSession [-InstanceId <guid>]  [<CommonParameters>]

    Enter-PSSession [[-Id] <int>]  [<CommonParameters>]

    Enter-PSSession [-Name <string>]  [<CommonParameters>]


PARAMETERS
    -AllowRedirection

        Required?                    false
        Position?                    Named
        Accept pipeline input?       false
        Parameter set name           Uri
        Aliases                      None
        Dynamic?                     false

    -ApplicationName <string>

        Required?                    false
        Position?                    Named
        Accept pipeline input?       true (ByPropertyName)
        Parameter set name           ComputerName
        Aliases                      None
        Dynamic?                     false

  [output cut]

    -ComputerName <string>

        Required?                    true
        Position?                    0
        Accept pipeline input?       true (ByValue, ByPropertyName)
        Parameter set name           ComputerName
        Aliases                      Cn
        Dynamic?                     false

Notice that the Enter-PSSession cmdlet uses -ComputerName as mandatory parameter. This cmdlet helps you to initiate a PowerShell session on remote computer. If you omit the –ComputerName parameter, you will be prompted to enter it.

PS C:\Users\Surender\Documents> Enter-PSSession

cmdlet Enter-PSSession at command pipeline position 1
Supply values for the following parameters:
ComputerName: DC1
[DC1]: PS C:\Users\surender\Documents>

I just wanted to point out how fair is Windows PowerShell with user. I mean if you forget to enter a mandatory parameter, it does not horrify you will pretty long ERROR message, it will fairly ask you to provide the value for required parameter.

Finding Cmdlet Parameters

Each cmdlet Help topic lists and describes the parameters of a cmdlet. To display the parameter section of a Help topic, use the –Detailed or –Parameter parameters of the Get-Help cmdlet. The –Parameters parameter of the Get-Help cmdlet is particularly useful because it displays only the parameters and includes detailed information about the parameters.

For example, to display detailed information about all the parameters of the Get-Command cmdlet, type the following command:

PS C:\Users\Surender\Documents> Get-Help Get-Command -Parameter *

-All

    Required?                    false
    Position?                    Named
    Accept pipeline input?       true (ByPropertyName)
    Parameter set name           (All)
    Aliases                      None
    Dynamic?                     false


-ArgumentList <Object[]>

    Required?                    false
    Position?                    1
    Accept pipeline input?       true (FromRemainingArguments)
    Parameter set name           (All)
    Aliases                      Args
    Dynamic?                     false


-CommandType <CommandTypes>

    Required?                    false
    Position?                    Named
    Accept pipeline input?       true (ByPropertyName)
    Parameter set name           AllCommandSet
    Aliases                      Type
    Dynamic?                     false

[output cut]

To display detailed information about a particular parameter, type the parameter name in the value of the Parameter parameter of Get-Help. For example, to display a detailed explanation of the CommandType parameter of the Get-Command cmdlet, type:

PS C:\Users\Surender\Documents> Get-Help Get-Command -Parameter CommandType

-CommandType <CommandTypes>

    Required?                    false
    Position?                    Named
    Accept pipeline input?       true (ByPropertyName)
    Parameter set name           AllCommandSet
    Aliases                      Type
    Dynamic?                     false

The Get-Command cmdlet displays cmdlet parameters in its syntax diagram and in the Parameters property of the CmdletInfo object that Get-Command returns. For example, to list the parameters of the Get-Service cmdlet, type:

PS C:\Users\Surender\Documents> (Get-Command Get-Service).parameters

Key                                                         Value
---                                                         -----
Name                                                        System.Management.Automation.ParameterMetadata
ComputerName                                                System.Management.Automation.ParameterMetadata
DependentServices                                           System.Management.Automation.ParameterMetadata
RequiredServices                                            System.Management.Automation.ParameterMetadata
DisplayName                                                 System.Management.Automation.ParameterMetadata
Include                                                     System.Management.Automation.ParameterMetadata
Exclude                                                     System.Management.Automation.ParameterMetadata
InputObject                                                 System.Management.Automation.ParameterMetadata
Verbose                                                     System.Management.Automation.ParameterMetadata

[output cut]

To display the syntax diagram for the Get-Service cmdlet, type:

PS C:\Users\Surender\Documents> (Get-Command Get-Service).definition

Get-Service [[-Name] <string[]>] [-ComputerName <string[]>] [-DependentServices] [-RequiredServices] [-Include <string[
]>] [-Exclude <string[]>] [<CommonParameters>]

Get-Service -DisplayName <string[]> [-ComputerName <string[]>] [-DependentServices] [-RequiredServices] [-Include <stri
ng[]>] [-Exclude <string[]>] [<CommonParameters>]

Get-Service [-ComputerName <string[]>] [-DependentServices] [-RequiredServices] [-Include <string[]>] [-Exclude <string
[]>] [-InputObject <ServiceController[]>] [<CommonParameters>]

Common Parameters

All cmdlets have a set of parameters that are called Common Parameters. This feature provides a consistent interface to Windows PowerShell.

Some of the cmdlets use the common parameters, but others do not. The effect of each common parameter varies from cmdlet to cmdlet, and some common parameters have no effect in some cmdlets.

Running Commands

Windows PowerShell provides a complete interactive environment. When you type a command at the Windows PowerShell command console, the command is processed immediately and the output is returned to the console.

This is true for all command types, including cmdlets, aliases, functions, CIM commands, workflows, and executable files.

You can also send the output of a command to a file or printer, or you can use the pipeline operator (|) to send the output to another command.

Windows PowerShell also gives you the ability to arithmetic expressions which uses PowerShell built-in converters. Again, the experience is interactive. The expression is processed immediately and the results are returned at the command console as shown below:

PS C:\Users\Surender\Documents> (100*20)/5
400

Using Aliases

The cmdlet names can be cumbersome to type. To minimize typing, and to make it easier for users accustomed to other shells to use Windows PowerShell, Windows PowerShell supports the concept of an alias, that is, an alternate name for a command. You can create an alias for a cmdlet name, function name, or the name of an executable file, and then type the alias instead of the name in any command.

Windows PowerShell includes many built-in aliases and you can create your own. The aliases that you create are valid only within the current session. To create a persistent alias, add the alias to your Windows PowerShell profile.

To find all of the aliases in your session, use Get-Alias cmdlet:

PS C:\Users\Surender\Documents> Get-Alias

CommandType     Name                                               ModuleName
-----------     ----                                               ----------
Alias           % -> ForEach-Object
Alias           ? -> Where-Object
Alias           ac -> Add-Content
Alias           asnp -> Add-PSSnapin
Alias           cat -> Get-Content
Alias           cd -> Set-Location
Alias           chdir -> Set-Location
Alias           clc -> Clear-Content
Alias           clear -> Clear-Host
Alias           clhy -> Clear-History
Alias           cli -> Clear-Item
Alias           clp -> Clear-ItemProperty
Alias           cls -> Clear-Host
Alias           clv -> Clear-Variable
Alias           cnsn -> Connect-PSSession
Alias           compare -> Compare-Object
Alias           copy -> Copy-Item
Alias           cp -> Copy-Item

If you are already familiar to Linux command line and Windows cmd.exe, you will find most of the commands used in Linux and Windows cmd.exe are used as Alias for Windows PowerShell cmdlets. For example, cp command is used in Linux to copy a file, in PowerShell it can also be used to perform the same function since alias is by default created for Copy-Item cmdlet. Similarly, copy command used in cmd.exe can also be used in PowerShell since copy alias is by default created for Copy-Item cmdlet.

The aliases in Windows PowerShell are supported by the Windows PowerShell Alias provider, a .NET Framework assembly that lets you view the aliases in a drive that looks much like the file system drives in Windows. The drive for aliases is Alias:.

To change to the Alias drive, type set-location Alias: command.

PS C:\Users\Surender\Documents> Set-Location Alias:
PS Alias:\> Get-ChildItem

CommandType     Name                                               ModuleName
-----------     ----                                               ----------
Alias           % -> ForEach-Object
Alias           ? -> Where-Object
Alias           ac -> Add-Content
Alias           asnp -> Add-PSSnapin
Alias           cat -> Get-Content
Alias           cd -> Set-Location
Alias           chdir -> Set-Location
Alias           clc -> Clear-Content
Alias           clear -> Clear-Host

[output cut]

To find the aliases for a specific cmdlet, use the following command:

PS C:\Users\Surender\Documents> Get-Alias -Definition Set-Location

CommandType     Name                                               ModuleName
-----------     ----                                               ----------
Alias           cd -> Set-Location
Alias           chdir -> Set-Location
Alias           sl -> Set-Location

Notice that Set-Location cmdlet has three default alias named cd, chdir and sl.

The above command can also be written in following way:

PS C:\Users\Surender\Documents> Get-Alias | Where-Object {$_.definition -eq "Set-Location"}

CommandType     Name                                               ModuleName
-----------     ----                                               ----------
Alias           cd -> Set-Location
Alias           chdir -> Set-Location
Alias           sl -> Set-Location

The above syntax seems to be very complicated if you are beginner to PowerShell but I covered this because you will more likely to see this syntax if you download any PowerShell script from technet or Microsoft Script Center. Let me explain what happened in above command. At first place the Get-Alias cmdlet is run and the output of Get-Alias is sent as input (piped) to another PowerShell cmdlet Where-Object. The Where-Object cmdlet is used to filter objects based on any criteria you like. When you pipe to Where-Object, you need to specify an expression that tells PowerShell which objects you want. For example, in above command we wanted to filter the output piped from Get-Alias command. So, in this case {$_.} is used to indicate the current pipeline object. Basically, $_. is the variable for the current value in the pipe line. Windows PowerShell variables are declared with dollar ($) character.  You may need to look at some more examples to understand the concept of $_. representation. For example, to list all the Windows Service which are currently running, you can use the following command:

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

Status   Name               DisplayName
------   ----               -----------
Running  AdobeARMservice    Adobe Acrobat Update Service
Running  Appinfo            Application Information
Running  AudioEndpointBu... Windows Audio Endpoint Builder
Running  Audiosrv           Windows Audio
Running  AVP15.0.2          Kaspersky Small Office Security Ser...
Running  BFE                Base Filtering Engine

[output cut]

Coming back on Get-Alias command; if you already know the alias (for example you are familiar to cmd.exe) and want to list the PowerShell cmdlet for any alias, you can use the Get-Alias cmdlet with –Name parameter as shown below:

PS C:\Users\Surender\Documents> Get-Alias -name cd

CommandType     Name                                               ModuleName
-----------     ----                                               ----------
Alias           cd -> Set-Location

PS C:\Users\Surender\Documents> Get-Alias -Name ren

CommandType     Name                                               ModuleName
-----------     ----                                               ----------
Alias           ren -> Rename-Item

PS C:\Users\Surender\Documents> Get-Alias -Name del

CommandType     Name                                               ModuleName
-----------     ----                                               ----------
Alias           del -> Remove-Item
Creating an Alias

To create aliases for cmdlets and commands in Windows PowerShell, use the Set-Alias cmdlet. For example, to create the “gh” alias for the Get-Help cmdlet, use the Set-Alias gh get-Help command as shown below:

PS C:\Users\Surender\Documents> Set-Alias -Name gh -Value Get-help
PS C:\Users\Surender\Documents> gh get-service

NAME
    Get-Service

SYNTAX
    Get-Service [[-Name] <string[]>] [-ComputerName <string[]>] [-DependentServices] [-RequiredServices] [-Include
    <string[]>] [-Exclude <string[]>]  [<CommonParameters>]

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

    Get-Service [-ComputerName <string[]>] [-DependentServices] [-RequiredServices] [-Include <string[]>] [-Exclude
    <string[]>] [-InputObject <ServiceController[]>]  [<CommonParameters>]

[output cut]
Deleting an Alias

To delete an alias, use the Remove-Item cmdlet to delete the alias from the Alias: drive. For example, to remove the “gh” alias, use Remove-Item Alias:gh command:

PS C:\Users\Surender\Documents> Remove-Item alias:gh
PS C:\Users\Surender\Documents> gh get-service
gh : The term 'gh' is not recognized as the name of a cmdlet, function, script file, or operable program. Check the
spelling of the name, or if a path was included, verify that the path is correct and try again.
At line:1 char:1
+ gh get-service 
+ ~~
    + CategoryInfo          : ObjectNotFound: (gh:String) [], CommandNotFoundException
    + FullyQualifiedErrorId : CommandNotFoundException

Formatting Command Output

In traditional command-line shells, each tool or command determines the format of its output. Some tools let you customize the output, and they include special parameters to control the output format.

In Windows PowerShell, the only cmdlets that format output are the format cmdlets shown below:

  • Format-Table
  • Format-List
  • Format-Custom
  • Format-Wide

There is no other cmdlet which formats the output. As a result, you do not need to learn the formatting routines and parameters of multiple tools. Just learn about the Format cmdlets and their parameters.

To find out the Format cmdlets available for your PowerShell session, use Get-Command cmdlet to display all cmdlets with “format” verb as shown below:

PS D:\MyScripts> Get-Command -Verb Format

CommandType     Name                                               ModuleName
-----------     ----                                               ----------
Function        Format-Volume                                      Storage
Cmdlet          Format-Custom                                      Microsoft.PowerShell.Utility
Cmdlet          Format-List                                        Microsoft.PowerShell.Utility
Cmdlet          Format-SecureBootUEFI                              SecureBoot
Cmdlet          Format-Table                                       Microsoft.PowerShell.Utility
Cmdlet          Format-Wide                                        Microsoft.PowerShell.Utility

When you run a cmdlet, the Windows PowerShell calls the default formatter, which is determined by the type of data being displayed. The formatter determines which properties of the output are displayed and whether they are displayed in a list or table format.

For example, when you use the Get-Service cmdlet, the default display is a three-column table, such as shown below:

PS D:\MyScripts> Get-Service

Status   Name               DisplayName
------   ----               -----------
Running  AdobeARMservice    Adobe Acrobat Update Service
Stopped  AeLookupSvc        Application Experience
Stopped  ALG                Application Layer Gateway Service

[output cut]

To change the format of the output from any cmdlet, use the pipeline operator (|) to send the output of the cmdlet to one of the Format cmdlets.

For example, the following command sends the output of a Get-Service command to the Format-List cmdlet. As a result, the service data is formatted as a list for each service.

PS D:\MyScripts> Get-Service | Format-List

Name                : AdobeARMservice
DisplayName         : Adobe Acrobat Update Service
Status              : Running
DependentServices   : {}
ServicesDependedOn  : {}
CanPauseAndContinue : False
CanShutdown         : False
CanStop             : True
ServiceType         : Win32OwnProcess

Name                : AeLookupSvc
DisplayName         : Application Experience
Status              : Stopped
DependentServices   : {}
ServicesDependedOn  : {}
CanPauseAndContinue : False
CanShutdown         : False
CanStop             : False
ServiceType         : Win32ShareProcess

Name                : ALG
DisplayName         : Application Layer Gateway Service
Status              : Stopped
DependentServices   : {}
ServicesDependedOn  : {}
CanPauseAndContinue : False
CanShutdown         : False
CanStop             : False
ServiceType         : Win32OwnProcess

[output cut]

In this format there is more information about each service and the data is displayed in the form of list. Instead of three columns of data for each service, there are nine rows of data now. The Format-List cmdlet did not retrieve the extra service information. The Format-Table, the default formatter, omitted it, because it could not display more than three columns across on the screen.

In addition to determining whether the data appears in a list or table, you can also determine which properties of the object are displayed. For example, the default display of Get-Service display only the Status, Name, and DisplayName properties of the service object. To see all of the properties of an object, use a pipeline operator (|) to send the output of a command to the Get-Member cmdlet.  For example, to see all of the properties of a service object, use the following command:

PS D:\MyScripts> Get-Service | Get-Member -MemberType Properties

   TypeName: System.ServiceProcess.ServiceController

Name                MemberType    Definition
----                ----------    ----------
Name                AliasProperty Name = ServiceName
RequiredServices    AliasProperty RequiredServices = ServicesDependedOn
CanPauseAndContinue Property      bool CanPauseAndContinue {get;}
CanShutdown         Property      bool CanShutdown {get;}
CanStop             Property      bool CanStop {get;}
Container           Property      System.ComponentModel.IContainer Container {get;}
DependentServices   Property      System.ServiceProcess.ServiceController[] DependentServices {get;}
DisplayName         Property      string DisplayName {get;set;}
MachineName         Property      string MachineName {get;set;}
ServiceHandle       Property      System.Runtime.InteropServices.SafeHandle ServiceHandle {get;}
ServiceName         Property      string ServiceName {get;set;}
ServicesDependedOn  Property      System.ServiceProcess.ServiceController[] ServicesDependedOn {get;}
ServiceType         Property      System.ServiceProcess.ServiceType ServiceType {get;}
Site                Property      System.ComponentModel.ISite Site {get;set;}
Status              Property      System.ServiceProcess.ServiceControllerStatus Status {get;}

Since all of these properties are in the object that Get-Service retrieves for each service, you can display any or all of them. Use the Property parameter of the Format cmdlet to select the properties to be displayed and the order in which they are displayed. For example, the following command uses the Format-Table cmdlet to display only the Name, ServiceType, and Status properties of the service.

PS D:\MyScripts> Get-Service | Format-Table Name, Servicetype, Status -AutoSize -Wrap

Name                                                                             ServiceType  Status
----                                                                             -----------  ------
AdobeARMservice                                                              Win32OwnProcess Running
AeLookupSvc                                                                Win32ShareProcess Stopped
ALG                                                                          Win32OwnProcess Stopped
AmmyyAdmin_690                                                               Win32OwnProcess Stopped
AppIDSvc                                                                   Win32ShareProcess Stopped
Appinfo                                                                    Win32ShareProcess Running

[output cut]

When you use theAutoSize parameter of Format-Table cmdlet, Windows PowerShell will calculate column widths based on the actual data you are going to display. This makes the columns more readable. You can force lengthy Format-Table data to wrap within its display column by using the Wrap parameter

If you want to manually sort and filter the output of command, you can pipe the output of cmdlet to Out-GridView cmdlet. The Out-GridView cmdlet sends the output to an interactive table in a separate window as shown below.

Out-GridView cmdlet

Out-GridView cmdlet

This is just the beginning of what you can do with Windows PowerShell output. For more details, you can read the help for all the Format cmdlets.

Running Scripts

What is a script?

A script is text file that contains one or more Windows PowerShell commands or expressions. When you run the script, the commands and expressions in the script file run, just as if you typed them at the command line.

Typically, you write a script to save command sequence that you use frequently or to share a command sequence with others.

Scripts can be as simple as a one-line command or as complex as an application program. Windows PowerShell includes a very rich and powerful scripting language that is designed especially for people who are not programmers. It supports language constructs for looping, conditions, flow-control, variable assignment, and much more.

How to Write Scripts?

To write a script, start a text editor, such as Notepad, or a script editor, such as Windows PowerShell Integrated Scripting Environment (ISE). Type commands or expressions, just as you would type them at the command line. Then save them to a file with .ps1 extension.

For example, the following command finds scripts in your user profile directory ($home) and its subdirectories. The $Home automatic variable is equivalent to the %UserProfile% environment variable, which is written as $env:UserProfile in Windows PowerShell.

PS C:\Users\Surender\Documents> Get-ChildItem -Path $home\* -Include *.ps1 -Recurse

    Directory: C:\Users\Surender\Desktop


Mode                LastWriteTime     Length Name
----                -------------     ------ ----
-a---        01-11-2013  10:45 AM        440 Connection.ps1
-a---        01-11-2013  01:53 PM        327 Get-DisabledADUsers.ps1
-a---        06-11-2013  05:09 PM        299 Get-DriveInfo.ps1
-a---        02-11-2013  12:40 PM        424 Get-UserInfo.ps1
-a---        20-09-2013  03:31 PM        470 IP.ps1
-a---        01-11-2013  04:34 PM        181 Stop-Process.ps1
-a---        20-09-2013  02:05 PM        391 Test.ps1
-a---        09-11-2013  11:29 AM        108 Testing.ps1
-a---        20-09-2013  03:26 PM        472 UserDomainInfo.ps1


    Directory: C:\Users\Surender\Documents\PowerShell


Mode                LastWriteTime     Length Name
----                -------------     ------ ----
-a---        17-10-2014  12:51 PM          0 Microsoft.PowerShellISE_profile.ps1
-a---        17-10-2014  12:51 PM          0 Microsoft.PowerShell_profile.ps1

To create the Get-Scripts.ps1 script, use the following procedure:

  1. Start Notepad.
  2. Paste the Get-ChildItem command (above) in the Notepad window.
  3. Save the file as Get-Scripts.ps1 in D:\MyScripts directory.

That’s all. As you become more familiar with Windows PowerShell, you’ll create more scripts and get scripts from colleagues and from safe websites.

How to Allow Scripts to Run?

Although scripts are extremely useful, even essential, they can be used to spread malicious code to potentially compromise you computer. To keep your computer secure, the default Windows PowerShell execution policy is Restricted which does not permit you to run scripts. And, to eliminate an obvious risk, none of the execution policies in Windows PowerShell allow you to run a script by double-clicking the script file.

To get the current execution policy, use the Get-ExecutionPolicy cmdlet.

To change the execution policy for the computer, for particular users, or for particular sessions, use the Set-ExecutionPolicy cmdlet, as follows.

  1. Start Windows PowerShell with the “Run as Administrator” option.
  2. Run the Set-ExecutionPolicy RemoteSigned command.

For more information, see PowerShell ExecutionPolicy).

How to Run Scripts?

To run a script, type the path and name of the script file. The path is required, even when the script is located in the current directory, to make it more difficult for malicious code to run scripts. The file name extension is optional.

For example, to run the Get-Scripts.ps1 script, type:

PS C:\Users\Surender\Documents> D:\MyScripts\Get-Scripts.ps1

    Directory: C:\Users\Surender\Desktop

Mode                LastWriteTime     Length Name
----                -------------     ------ ----
-a---        01-11-2013  10:45 AM        440 Connection.ps1
-a---        01-11-2013  01:53 PM        327 Get-DisabledADUsers.ps1
-a---        06-11-2013  05:09 PM        299 Get-DriveInfo.ps1
-a---        02-11-2013  12:40 PM        424 Get-UserInfo.ps1
-a---        20-09-2013  03:31 PM        470 IP.ps1
-a---        01-11-2013  04:34 PM        181 Stop-Process.ps1
-a---        20-09-2013  02:05 PM        391 Test.ps1
-a---        09-11-2013  11:29 AM        108 Testing.ps1
-a---        20-09-2013  03:26 PM        472 UserDomainInfo.ps1


    Directory: C:\Users\Surender\Documents\PowerShell


Mode                LastWriteTime     Length Name
----                -------------     ------ ----
-a---        17-10-2014  12:51 PM          0 Microsoft.PowerShellISE_profile.ps1
-a---        17-10-2014  12:51 PM          0 Microsoft.PowerShell_profile.ps1

If the script you want to run is in the current directory, type the directory name or use a dot (.) to represent the current directory. For example, use the Set-Location command to go to theD:\MyScripts directory, as follows:

PS C:\Users\Surender\Documents> Set-Location D:\MyScripts
PS D:\MyScripts>

Then, use a dot to indicate the current directory in the path to the Get-Scripts.ps1 script.

PS D:\MyScripts> .\Get-Scripts.ps1


    Directory: C:\Users\Surender\Desktop


Mode                LastWriteTime     Length Name
----                -------------     ------ ----
-a---        01-11-2013  10:45 AM        440 Connection.ps1
-a---        01-11-2013  01:53 PM        327 Get-DisabledADUsers.ps1
-a---        06-11-2013  05:09 PM        299 Get-DriveInfo.ps1
-a---        02-11-2013  12:40 PM        424 Get-UserInfo.ps1
-a---        20-09-2013  03:31 PM        470 IP.ps1
-a---        01-11-2013  04:34 PM        181 Stop-Process.ps1
-a---        20-09-2013  02:05 PM        391 Test.ps1
-a---        09-11-2013  11:29 AM        108 Testing.ps1
-a---        20-09-2013  03:26 PM        472 UserDomainInfo.ps1

[output cut]
Run with PowerShell

There is one more way to run scripts. It is designed for particular types of scripts, so you’re likely to use it only occasionally, but it’s very handy when you need it.

Beginning in Windows PowerShell 3.0, you can run scripts from File Explorer in Windows 8 and Windows Server 2012 and from Windows Explorer in earlier versions of Windows. The “Run with PowerShell” feature is designed to run scripts that do not have required parameters and do not return output to the command prompt.

To use the “Run with PowerShell” feature:

  • In Windows Explorer, right-click the script file name and then select “Run with PowerShell.”

The “Run with PowerShell” feature starts a Windows PowerShell session that has an execution policy of Bypass, runs the script, and closes the session.

Run the Script with Run Dialog Box

You can also execute a script right from Run dialog box (Windows+R), however the syntax is somewhat complex, but it might come handy if you want to schedule a PowerShell script in Windows Schedule Tasks. Before actually scheduling the script; you can test if the script could run successfully.  For example, follow the steps to run Get-Scripts.ps1 :

  1. Open the Run dialog (Press Windows+R).
  2. Type powershell.exe -noexit -file “D:\MyScripts\Get-scripts.ps1  and press Enter.

The script will be run in PowerShell window and the window will auto close once the script execution completes. The -noexit parameter keeps the PowerShell window open even after the script execution is completed. You can also use -WindowStyle parameter with the Minimized or Maximized value to change the behavior of the PowerShell window. The -WindowStyle Minimized parameter will run the PowerShell window minimized to task bar.

List the Properties and Methods of Objects

When you start working with any Windows PowerShell cmdlet, you might be wondering that which properties and methods are available to be used with a particular cmdlet.

The Windows PowerShell provides Get-Member cmdlet to do this for you. Once you connect to an object, you can pipe that object to Get-Member; in turn, Get-Member will enumerate the properties and methods of that object. For example, suppose want to know which properties and methods are available for the Get-Scripts.ps1 file we have just created. To know this you can use the following command:

PS D:\MyScripts> .\Get-Scripts.ps1 | Get-Member


   TypeName: System.IO.FileInfo

Name                      MemberType     Definition
----                      ----------     ----------
Mode                      CodeProperty   System.String Mode{get=Mode;}
AppendText                Method         System.IO.StreamWriter AppendText()
CopyTo                    Method         System.IO.FileInfo CopyTo(string destFileName), System.IO.FileInfo CopyTo(string destFi...
Create                    Method         System.IO.FileStream Create()
CreateObjRef              Method         System.Runtime.Remoting.ObjRef CreateObjRef(type requestedType)
CreateText                Method         System.IO.StreamWriter CreateText()
Decrypt                   Method         void Decrypt()
Delete                    Method         void Delete()
Encrypt                   Method         void Encrypt()
Equals                    Method         bool Equals(System.Object obj)
GetAccessControl          Method         System.Security.AccessControl.FileSecurity GetAccessControl(), System.Security.AccessCo...
GetHashCode               Method         int GetHashCode()
GetLifetimeService        Method         System.Object GetLifetimeService()
GetObjectData             Method         void GetObjectData(System.Runtime.Serialization.SerializationInfo info, System.Runtime....
GetType                   Method         type GetType()
InitializeLifetimeService Method         System.Object InitializeLifetimeService()
MoveTo                    Method         void MoveTo(string destFileName)
Open                      Method         System.IO.FileStream Open(System.IO.FileMode mode), System.IO.FileStream Open(System.IO...
OpenRead                  Method         System.IO.FileStream OpenRead()
OpenText                  Method         System.IO.StreamReader OpenText()
OpenWrite                 Method         System.IO.FileStream OpenWrite()
Refresh                   Method         void Refresh()
Replace                   Method         System.IO.FileInfo Replace(string destinationFileName, string destinationBackupFileName...
SetAccessControl          Method         void SetAccessControl(System.Security.AccessControl.FileSecurity fileSecurity)
ToString                  Method         string ToString()
PSChildName               NoteProperty   System.String PSChildName=Connection.ps1
PSDrive                   NoteProperty   System.Management.Automation.PSDriveInfo PSDrive=C
PSIsContainer             NoteProperty   System.Boolean PSIsContainer=False
PSParentPath              NoteProperty   System.String PSParentPath=Microsoft.PowerShell.Core\FileSystem::C:\Users\Surender...
PSPath                    NoteProperty   System.String PSPath=Microsoft.PowerShell.Core\FileSystem::C:\Users\Surender\Desk...
PSProvider                NoteProperty   System.Management.Automation.ProviderInfo PSProvider=Microsoft.PowerShell.Core\FileSystem
Attributes                Property       System.IO.FileAttributes Attributes {get;set;}
CreationTime              Property       datetime CreationTime {get;set;}
CreationTimeUtc           Property       datetime CreationTimeUtc {get;set;}
Directory                 Property       System.IO.DirectoryInfo Directory {get;}
DirectoryName             Property       string DirectoryName {get;}
Exists                    Property       bool Exists {get;}
Extension                 Property       string Extension {get;}
FullName                  Property       string FullName {get;}
IsReadOnly                Property       bool IsReadOnly {get;set;}
LastAccessTime            Property       datetime LastAccessTime {get;set;}
LastAccessTimeUtc         Property       datetime LastAccessTimeUtc {get;set;}
LastWriteTime             Property       datetime LastWriteTime {get;set;}
LastWriteTimeUtc          Property       datetime LastWriteTimeUtc {get;set;}
Length                    Property       long Length {get;}
Name                      Property       string Name {get;}
BaseName                  ScriptProperty System.Object BaseName {get=if ($this.Extension.Length -gt 0){$this.Name.Remove($this.N...
VersionInfo               ScriptProperty System.Object VersionInfo {get=[System.Diagnostics.FileVersionInfo]::GetVersionInfo($th...

Notice that there are lot of methods and properties you can use while working with the Get-Scripts.ps1 file. The PowerShell will display the different Methods and Properties for different types of files. Similarly you can also use Get-Member cmdlet to determine the Methods and Properties available for any PowerShell cmdlet. Let’s take a look at the members of Get-Service cmdlet.

PS D:\MyScripts> Get-Service | Get-Member

   TypeName: System.ServiceProcess.ServiceController

Name                      MemberType    Definition
----                      ----------    ----------
Name                      AliasProperty Name = ServiceName
RequiredServices          AliasProperty RequiredServices = ServicesDependedOn
Disposed                  Event         System.EventHandler Disposed(System.Object, System.EventArgs)
Close                     Method        void Close()
Continue                  Method        void Continue()
CreateObjRef              Method        System.Runtime.Remoting.ObjRef CreateObjRef(type requestedType)
Dispose                   Method        void Dispose(), void IDisposable.Dispose()
Equals                    Method        bool Equals(System.Object obj)
ExecuteCommand            Method        void ExecuteCommand(int command)
GetHashCode               Method        int GetHashCode()
GetLifetimeService        Method        System.Object GetLifetimeService()
GetType                   Method        type GetType()
InitializeLifetimeService Method        System.Object InitializeLifetimeService()
Pause                     Method        void Pause()
Refresh                   Method        void Refresh()
Start                     Method        void Start(), void Start(string[] args)
Stop                      Method        void Stop()
WaitForStatus             Method        void WaitForStatus(System.ServiceProcess.ServiceControllerStatus desiredStatus), void Wa...
CanPauseAndContinue       Property      bool CanPauseAndContinue {get;}
CanShutdown               Property      bool CanShutdown {get;}
CanStop                   Property      bool CanStop {get;}
Container                 Property      System.ComponentModel.IContainer Container {get;}
DependentServices         Property      System.ServiceProcess.ServiceController[] DependentServices {get;}
DisplayName               Property      string DisplayName {get;set;}
MachineName               Property      string MachineName {get;set;}
ServiceHandle             Property      System.Runtime.InteropServices.SafeHandle ServiceHandle {get;}
ServiceName               Property      string ServiceName {get;set;}
ServicesDependedOn        Property      System.ServiceProcess.ServiceController[] ServicesDependedOn {get;}
ServiceType               Property      System.ServiceProcess.ServiceType ServiceType {get;}
Site                      Property      System.ComponentModel.ISite Site {get;set;}
Status                    Property      System.ServiceProcess.ServiceControllerStatus Status {get;}
ToString                  ScriptMethod  System.Object ToString();

While working with any Windows Service, you will be most likely want to Start or Stop the service or change its StartupMode. Windows PowerShell offers large number of Methods and Properties (including Stop and Start) for Service objects.

Running Windows Programs

You can run Windows command-line programs and start Windows graphic programs by using Windows PowerShell. If the program generates text output, you can capture the text and use it in Windows PowerShell.

You can run many programs just by typing the program name. For example, you can start the Notepad program by using the following command.

PS D:\MyScripts> notepad

This command works because the executable file for the Notepad program is in a location that is listed in the Path environment variable. To start the program in other locations, type the full path to the program. If the path includes spaces, enclose the path in quotation marks and parentheses and use the call operator (&) to run the quoted string. For example, the following command starts Microsoft Excel, use the following command:

PS D:\MyScripts> &("C:\Program Files (x86)\Microsoft Office\Office15\excel.exe")

To make this command easier to run, create a function and save it in your Windows PowerShell profile. For example, the following command creates the Excel function.

PS D:\MyScripts> function Excel
>> {
>> &("C:\Program Files (x86)\Microsoft Office\Office15\excel.exe")
>> }
>>
PS D:\MyScripts>

Now, everytime you want to start Microsoft Excel from PowerShell console, just type excel in console and press Enter.

Managing Errors

Errors will occur occasionally when you use the Windows PowerShell, such as when you are trying to set your location to a nonexistent directory or trying to remove a file without the required privileges.

There are two types of errors in Windows PowerShell:

  • Terminating Errors: Errors that halt the execution of the command.
  • Non-terminating Errors: Errors that do not halt the execution of the command.

For example, if you are removing *.tmp files from a directory, you might not want the operation to stop if one of the files cannot be removed. Typically, you want to remove all of the files that you can remove, and then go back for the files that you could not remove.

The error that occurs when you cannot remove a file is called a Non-terminating error. When a non-terminating error occurs, Windows PowerShell continues despite the error and then displays the error along with the output.

More serious errors will stop command processing. These are called Terminating errors. Terminating errors stop the processing of the command. For example, if you submit data that is not valid or if you do not have the permissions required to perform the command, Windows PowerShell generates a terminating error.

Once you start writing scripts, you should become familiar with the –ErrorAction parameter. It is one of the standard parameters, and is therefore available on all cmdlets. It allows you to specify a custom error action for each cmdlet or each line of code in your script.

Get-Content .\Close-Outlook.ps1 -ErrorAction Continue
Get-Content Test.ps1 -ErrorAction Stop

In the code shown above, the first line of code has ErrorAction Continue parameter which means it informs you of an error if it occurs while retrieving the content of the Close-Outlook.ps1 file located in current directory. If an error occurs, after informing you of the problem, the script continues to the next line. TheErrorAction for the second line of code is Stop. The script will halt if the Get-Content cmdlet is unable to find the file Test.ps1.

You can either use enumeration or use a numeric value with ErrorAction parameter Table 1 shows the enumeration and values which can be used with ErrorAction parameter:

Table 1

EnumerationValueDescription
SilentlyContinue 0The Windows PowerShell runtime will continue processing without notifying the user that an action has occurred.
Stop 1The Windows PowerShell runtime will stop processing when an action occurs.
Continue 2The Windows PowerShell runtime will continue processing and notify the user that an action has occurred.
Inquire 3The Windows PowerShell runtime will stop processing and ask the user how it should proceed.

This means, the above code lines can also be written as follows:

Get-Content .\Close-Outlook.ps1 -ea 2
Get-Content Test.ps1 -ea 1

When writing a script, I do not recommend using aliases and enumeration values directly because it makes the script very difficult to read, which in turn makes the script harder to troubleshoot. However, when working interactively from the Windows PowerShell prompt, it is perfectly acceptable to use the enumeration values and alias.

Back

Leave a Comment

1 Comment

Comments are closed.