Category Archives: HelpFile

about_preference_variables

TOPIC
    Preference Variables

SHORT DESCRIPTION
    Variables that customize the behavior of Windows PowerShell

LONG DESCRIPTION
    Windows PowerShell includes a set of Variables that enable you to
    customize its behavior. These “preference Variables” work like the
    options in GUI-based systems.

    The preference Variables affect the Windows PowerShell operating
    Environment and all commands run in the Environment. In many cases,
    the cmdlets have parameters that you can use to override the preference
    behavior for a specific command.

    The following table lists the preference Variables and their default
    values.

    Variable                             Default Value
    ——–                             ————-
    $ConfirmPreference                 High
    $DebugPreference                     SilentlyContinue
    $ErrorActionPreference             Continue
    $ErrorView                         NormalView
    $FormatEnumerationLimit             4
    $LogCommandHealthEvent             False (not logged)
    $LogCommandLifecycleEvent            False (not logged)
    $LogEngineHealthEvent                True (logged)
    $LogEngineLifecycleEvent             True (logged)
    $LogProviderLifecycleEvent         True (logged)
    $LogProviderHealthEvent             True (logged)
    $MaximumAliasCount                 4096
    $MaximumDriveCount                 4096
    $MaximumErrorCount                 256
    $MaximumFunctionCount                4096
    $MaximumHistoryCount                 64
    $MaximumVariableCount                4096
    $OFS                                 (Space character (” “))
    $OutputEncoding                 ASCIIEncoding object
    $ProgressPreference                 Continue
    $PSEmailServer                     (None)
    $PSSessionApplicationName            WSMan
    $PSSessionConfigurationName         http://schemas.microsoft.com/powershell/microsoft.powershell
    $PSSessionOption                     (See below)
    $VerbosePreference                 SilentlyContinue
    $WarningPreference                 Continue
    $WhatIfPreference                    0

    Windows Powershell also includes the following Environment Variables that
    store user preferences. For more information about the Environment Variables,
    see about_environment_variables.

    Variable
    ——–
    PSModulePath

WORKING WITH PREFERENCE VariableS
    This document describes each of the preference Variables.

    To display the current value of a specific preference Variable, type
    the name of the Variable. In response, Windows PowerShell provides the
    value. For example, the following command displays the value of the
    $ConfirmPreference Variable.

        PS> $ConfirmPreference
        High

    To change the value of a Variable, use an assignment statement. For
    example, the following statement assigns the value “Medium” to the
    $ConfirmPreference Variable.

        PS> $ConfirmPreference = “Medium”

    Like all Variables, the values that you set are specific to the current
    Windows PowerShell window. To make them effective in all Windows
    PowerShell windows, add them to your Windows PowerShell profile. For
    more information, see about_profiles.

WORKING REMOTELY
When you run commands on a remote computer, the remote commands are subject
only to the preferences set in the Windows PowerShell client on the remote
computer. For example, when you run a remote command, the value of the
$DebugPreference Variable on remote computer determines how Windows
PowerShell responds to debugging messages.

For more information about remote commands, see about_remote.

$ConfirmPreference
——————
    Determines which cmdlet actions automatically request confirmation
    from the user before they are performed.

    When the $ConfirmPreference value (High, Medium, Low, None) is
    greater than or equal to the risk of the cmdlet action (High, Medium,
    Low, None), Windows PowerShell automatically requests confirmation
    from the user before performing the action.

    You can use the Confirm parameter of a cmdlet to override the preference
    for a specific command.

        Valid values:
        None:    No cmdlet actions are automatically confirmed.
                         Users must use the Confirm parameter to request
                         confirmation of specific commands.

        Low:     Cmdlet actions with a low, medium, or high risk are
                         automatically confirmed. To suppress confirmation
                         of a specific command, use -Confirm:$false.

        Medium: Cmdlet actions with a medium or high risk are
                         automatically confirmed. To enable confirmation of
                         a specific command, use -confirm. To suppress
                         confirmation of a specific command, use
                         -confirm:$false.

        High:    Cmdlet actions with a high risk are automatically
             (default) confirmed. To enable confirmation of a specific
                         command, use -confirm. To suppress confirmation for a
                         specific command, use -confirm:$false.

    DETAILED EXPLANATION
        When a cmdlet action significantly affects the system, such as by
        deleting data or by using a significant amount of system resources,
        Windows PowerShell can automatically prompt you for confirmation
        before performing the action.

        For example,

        PS> Remove-Item pref2.txt

            Confirm
            Are you sure you want to perform this action?
            Performing operation “Remove File” on Target “C:\pref2.txt”.
            [Y] Yes [A] Yes to All [N] No [L] No to All [S] Suspend [?] Help (default is “Y”):

        The estimate of the risk is part of the cmdlet known as its
        “ConfirmImpact”. You cannot change it.

        Cmdlet that might pose a risk to the system have a Confirm parameter
        that you can use to request or suppress confirmation for a
        specific command.

    Because most cmdlets use the default risk value of Medium, and the
        default value of $ConfirmPreference is High, automatic confirmation
        rarely occurs. However, you can activate automatic confirmation by
        changing the value of $ConfirmPreference to Medium or Low.

    EXAMPLES
     This example shows the effect of the default value of
     $ConfirmPreference. The High value only confirms high-risk cmdlet
     actions. Since most actions are of medium risk, they are not
     automatically confirmed, although you can use the Confirm
     parameter of the cmdlet to request confirmation of a specific
     command.

         PS> $confirmpreference             #Get the current value of the
         High                                 Variable

         PS> Remove-Item temp1.txt         #Delete a file
         PS>                                 #Deleted without confirmation
         PS> Remove-Item temp2.txt -confirm #Use the Confirm parameter

         Confirm
         Are you sure you want to perform this action?
         Performing operation “Remove File” on Target “C:\temp2.txt”.
         [Y] Yes [A] Yes to All [N] No [L] No to All [S] Suspend [?] Help (default is “Y”):

     This example shows the effect of changing the value of
     $ConfirmPrefernce to Medium. Because most cmdlet actions are
     medium-risk, they are automatically confirmed, and you have to use
     the Confirm parameter with a value of $false to suppress the
     confirmation prompt for a specific command.

         PS> $confirmpreference = “Medium”
                                     #Change the value of $ConfirmPreference
         PS> Remove-Item temp2.txt
                                     #Deleting a file triggers confirmation
         Confirm
         Are you sure you want to perform this action?
         Performing operation “Remove File” on Target “C:\temp2.txt”.
         [Y] Yes [A] Yes to All [N] No [L] No to All [S] Suspend [?] Help (default is “Y”):

         PS> Remove-Item temp3.txt -confirm:$false #Use Confirm parameter
                                                     to suppress confirmation
         PS>

$DebugPreference
——————
    Determines how Windows PowerShell responds to debugging messages
        generated by a script, cmdlet or provider, or by a Write-Debug
        command at the command line.

        Some cmdlets display debugging messages, which are typically very
        technical messages designed for programmers and technical support
        professionals. By default, debugging messages are not displayed,
        but you can display debugging messages by changing the value of
        $DebugPreference.

        You can also use the Debug common parameter of a cmdlet to display
        or hide the debugging messages for a specific command. For more
        information, type: “Get-Help about_CommonParameters“.

        Valid values:
        Stop:             Displays the debug message and stops
                                executing. Writes an error to the console.

             Inquire:            Displays the debug message and asks you
                                whether you want to continue.

            Continue:         Displays the debug message and continues
                                with execution.

            SilentlyContinue: No effect. The debug message is not
            (Default)         displayed and execution continues without
                                 interruption.

    EXAMPLES

    The following examples show the effect of changing the values of
    $DebugPreference when a Write-Debug command is entered at the command
    line. The change affects all debugging messages, including those
    generated by cmdlets and scripts. The examples also show the use of the
    Debug common parameter, which displays or hides the debugging messages
    related to a single command.

    This example shows the effect of the default value, “SilentlyContinue.”
    The debug message is not displayed and processing continues. The final
    command uses the Debug parameter to override the preference for a single
    command.

        PS> $debugpreference                    # Get the current value of
        SilentlyContinue                         $DebugPreference

        PS> Write-Debug “Hello, World”
        PS>                                     # The debug message is not
                                                 displayed.

        PS> Write-Debug “Hello, World” -Debug # Use the Debug parameter
        DEBUG: Hello, World                     # The debug message is
                                                 is requested.                                                                                                    displayed and confirmation
        Confirm
        Continue with this operation?
        [Y] Yes [A] Yes to All [H] Halt Command [S] Suspend [?] Help (default is “Y”):

    This example shows the effect of the “Continue” value. The final command
    uses the Debug parameter with a value of $false to suppress the message
    for a single command.

        PS> $debugpreference = “Continue” # Change the value to “Continue”

        PS> Write-Debug “Hello, World”
        DEBUG: Hello, World                 # The debug message is displayed
        PS>                                 and processing continues.

        PS> Write-Debug “Hello, World” -Debug:$false
                                            # Use the Debug parameter with
                                             false.
        PS>                                 # The debug message is not
                                             displayed.

    This example shows the effect of the “Stop” value. The final command
    uses the Debug parameter with a value of $false to suppress the message
    for a single command.

        PS> $debugpreference = “Stop”     #Change the value to “Stop”
        PS> Write-Debug “Hello, World”
        DEBUG: Hello, World
        Write-Debug : Command execution stopped because the shell Variable “DebugPreference” is
        set to Stop.
        At line:1 char:12
        + Write-Debug <<<< “Hello, World”

        PS> Write-Debug “Hello, World” -Debug:$false
                                            # Use the Debug parameter with
                                             $false
        PS>                                 # The debug message is not
                                             displayed and processing is
                                             not stopped.

    This example shows the effect of the “Inquire” value. The final command
    uses the Debug parameter with a value of $false to suppress the message
    for a single command.

        PS> $debugpreference = “Inquire”
        PS> Write-Debug “Hello, World”
        DEBUG: Hello, World

        Confirm
        Continue with this operation?
        [Y] Yes [A] Yes to All [H] Halt Command [S] Suspend [?] Help (default is “Y”):

        PS> Write-Debug “Hello, World” -Debug:$false
                                            # Use the Debug parameter with
                                             $false
        PS>                                 # The debug message is not
                                             displayed and processing
                                             continues without interruption.

$ErrorActionPreference
———————-
    Determines how Windows PowerShell responds to a non-terminating
        error (an error that does not stop the cmdlet processing) at the
        command line or in a script, cmdlet, or provider, such as the
        errors generated by the Write-Error cmdlet.

        You can also use the ErrorAction common parameter of a cmdlet to
        override the preference for a specific command. For more
        information, type: “Get-Help about_CommonParameters“.

        Valid values:
        Stop:             Displays the error message and stops
                                executing.

             Inquire:            Displays the error message and asks you
                                whether you want to continue.

            Continue:         Displays the error message and continues
                                executing.

            SilentlyContinue: No effect. The error message is not
            (Default)         displayed and execution continues without
                                interruption.

     Neither $ErrorActionPreference nor the ErrorAction common parameter
     affect how Windows PowerShell responds to terminating errors (those
     that stop cmdlet processing).

     For more information about the ErrorAction common parameter, type
     “Get-Help about_CommonParameters“.

    EXAMPLES

    These examples show the effect of the different values of
    $ErrorActionPreference and the use of the ErrorAction common parameter
    to override the preference for a single command. The ErrorAction
    parameter has the same valid values as the $ErrorActionPreference
    Variable.

    This example shows the effect of the Continue value, which is the
    default.

        PS> $erroractionpreference
        Continue        # Display the value of the preference.

        PS> Write-Error “Hello, World”
                                # Generate a non-terminating error.

        Write-Error “Hello, World” : Hello, World
                                # The error message is displayed and
                                 execution continues.

        PS> Write-Error “Hello, World” -ErrorAction:SilentlyContinue
                                # Use the ErrorAction parameter with a
                                 value of “SilentlyContinue”.
        PS>
                                # The error message is not displayed and
                                 execution continues.

    This example shows the effect of the SilentlyContinue value.

        PS> $ErrorActionPreference = “SilentlyContinue”
                                # Change the value of the preference.
        PS> Write-Error “Hello, World”
                                # Generate an error message.
        PS>
                                # Error message is suppressed.
        PS> Write-Error “Hello, World” -ErrorAction:continue
                                # Use the ErrorAction parameter with a
                                 value of “Continue”.
        Write-Error “Hello, World” -ErrorAction:continue : Hello, World
                                # The error message is displayed and
                                 execution continues.

    This example shows the effect of a real error. In this case, the command
    gets a non-existent file, nofile.txt. The example also uses the
    ErrorAction common parameter to override the preference.

        PS> $erroractionpreference
        SilentlyContinue        # Display the value of the preference.

        PS> Get-ChildItem -path nofile.txt
        PS>                     # Error message is suppressed.

        PS> $ErrorActionPreference = “Continue”
                                # Change the value to Continue.

        PS> Get-ChildItem -path nofile.txt
        Get-ChildItem : Cannot find path ‘C:\nofile.txt’ because it does not exist.
        At line:1 char:4
        + Get-ChildItem <<<< nofile.txt

        PS> Get-ChildItem -path nofile.txt -ErrorAction SilentlyContinue
                                # Use the ErrorAction parameter
        PS>
                                # Error message is suppressed.

        PS> $ErrorActionPreference = “Inquire”
                                # Change the value to Inquire.
        PS> Get-ChildItem -path nofile.txt

        Confirm
        Cannot find path ‘C:\nofile.txt’ because it does not exist.
        [Y] Yes [A] Yes to All [H] Halt Command [S] Suspend [?] Help (default is “Y”): y

        Get-ChildItem : Cannot find path ‘C:\nofile.txt’ because it does not exist.
        At line:1 char:4
        + Get-ChildItem <<<< nofile.txt

        PS> $ErrorActionPreference = “Continue”
                                # Change the value to Continue.
        PS> Get-ChildItem nofile.txt -ErrorAction “Inquire”
                                # Use the ErrorAction parameter to override
                                 the preference value.

        Confirm
        Cannot find path ‘C:\nofile.txt’ because it does not exist.
        [Y] Yes [A] Yes to All [H] Halt Command [S] Suspend [?] Help (default is “Y”):

$ErrorView
———-
        Determines the display format of error messages in Windows
        PowerShell.

        Valid values:
        NormalView:         A detailed view designed for most users.
            (default)         Consists of a description of the error, the
                                name of the object involved in the error,
                                and arrows (<<<<) that point to the words
                                in the command that caused the error.

             CategoryView:     A succinct, structured view designed for
                                production Environments. The format is:
                                {Category}: ({TargetName}:{TargetType}):[{Activity}], {Reason}

        For more information about the fields in CategoryView, see
        “ErrorCategoryInfo class” in the Windows PowerShell SDK.

    EXAMPLES

    These example show the effect of the ErrorView values.

    This example shows how an error appears when the value of $ErrorView is
    NormalView. In this case, the Get-ChildItem command is used to find a
    non-existent file.

        PS> $ErrorView                         # Verify the value.
        NormalView

        PS> Get-ChildItem nofile.txt         # Find a non-existent file.
        Get-ChildItem : Cannot find path ‘C:\nofile.txt’ because it does not exist.
        At line:1 char:14
        + Get-ChildItem <<<< nofile.txt

    This example shows how the same error appears when the value of
    $ErrorView is CategoryView.

        PS> $ErrorView = “CategoryView”        # Change the value to
                                                 CategoryView

        PS> Get-ChildItem nofile.txt
        ObjectNotFound: (C:\nofile.txt:String) [Get-ChildItem], ItemNotFoundException

This example demonstrates that the value of ErrorView only affects the
error display; it does not change the structure of the error object that
is stored in the $error automatic Variable. For information about the $error
automatic Variable, see about_Automatic_Variables.

This command takes the ErrorRecord object associated with the most recent
error in the error array (element 0) and formats all of the properties
of the error object in a list.

        PS> $error[0] | Format-List -property * -force

        Exception    : System.Management.Automation.ItemNotFoundException: Cannot find path
                     ‘C:\nofile.txt’ because it does not exist.
                     at System.Management.Automation.SessionStateInternal.GetChildItems(String path,
                     Boolean recurse, CmdletProviderContext context)
                     at System.Management.Automation.ChildItemCmdletProviderIntrinsics.Get(String path,
                     Boolean recurse, CmdletProviderContext context)
                     at Microsoft.PowerShell.Commands.GetChildItemCommand.ProcessRecord()
        TargetObject         : C:\nofile.txt
        CategoryInfo         : ObjectNotFound: (C:\nofile.txt:String) [Get-ChildItem],
                                ItemNotFoundException
        FullyQualifiedErrorId : PathNotFound,Microsoft.PowerShell.Commands.GetChildItemCommand
        ErrorDetails         :
        InvocationInfo        : System.Management.Automation.InvocationInfo

$FormatEnumerationLimit
———————–
        Determines how many enumerated items are included in a display. This
        Variable does not affect the underlying objects; just the display.
        When the value of $FormatEnumerationLimit is less than the number of
        enumerated items, Windows PowerShell adds an ellipsis (…) to
        indicate items not shown.

        Valid values: Integers (Int32)
        Default value: 4

    EXAMPLES

        This example shows how to use the $FormatEnumerationLimit Variable
        to improve the display of enumerated items.

        The command in this example generates a table that lists all of the
        services running on the computer in two groups; one for running
        services and one for stopped services. It uses a Get-Service
        command to get all of the services, and then send the results
        through the pipeline to the Group-Object cmdlet, which groups the
        results by the service status.

        The resulting display is a table that lists the status in the Name
        column and the processes with that status in the Group column. (To
        change the column labels, use a hash table. For more information,
        see the examples in “Get-Help Format-Table -examples”.)

        There are a maximum of 4 services listed in the Group column for
        each status. To increase the number of items listed, increase
        the value of $FormatEnumerationLimit to 1000.

        In the resulting display, the list in the Group column is now
        limited by the line length. In the final command in the example, use
        the Wrap parameter of Format-Table to display all of the processes
        in each Status group.

        PS> $formatenumerationlimit         # Find the current value
        4

        PS> Get-Service | Group-Object -property status
                                            # List all services grouped by
                                             status

        Count Name                     Group
        —– —-                     —–
         60 Running                 {AdtAgent, ALG, Ati HotKey Poller, AudioSrv…}
         41 Stopped                 {Alerter, AppMgmt, aspnet_state, ATI Smart…}

                                         # The list is truncated after
                                             4 items.

        PS> $formatenumerationlimit = 1000
                                         # Increase the limit to 1000.

        PS> Get-Service | Group-Object -property status
                                         # Repeat the command.

        Count Name     Group
        —– —-     —–
         60 Running {AdtAgent, ALG, Ati HotKey Poller, AudioSrv, BITS, CcmExec…
         41 Stopped {Alerter, AppMgmt, aspnet_state, ATI Smart, Browser, CiSvc…

        PS> Get-Service | Group-Object -property status | Format-Table -wrap
                                         # Add the Wrap parameter.

        Count Name     Group
        —– —-     —–
         60 Running    {AdtAgent, ALG, Ati HotKey Poller, AudioSrv, BITS, CcmExec, Client
                         for NFS, CryptSvc, DcomLaunch, Dhcp, dmserver, Dnscache, ERSvc,
                         Eventlog, EventSystem, FwcAgent, helpsvc, HidServ, IISADMIN,
                         InoRPC, InoRT, InoTask, lanmanserver, lanmanworkstation, LmHosts,
                         MDM, Netlogon, Netman, Nla, NtLmSsp, PlugPlay, PolicyAgent,
                         ProtectedStorage, RasMan, RemoteRegistry, RpcSs, SamSs, Schedule,
                         seclogon, SENS, SharedAccess, ShellHWDetection, SMT PSVC, Spooler,
                         srservice, SSDPSRV, stisvc, TapiSrv, TermService, Themes, TrkWks,
                         UMWdf, W32Time, W3SVC, WebClient, winmgmt, wscsvc, wuauserv,
                         WZCSVC, zzInterix}

         41 Stopped    {Alerter, AppMgmt, aspnet_state, ATI Smart, Browser, CiSvc,
                         ClipSrv, clr_optimization_v2.0.50727_32, COMSysApp, CronService,
                         dmadmin, FastUserSwitchingCompatibility, HTTPFilter, ImapiService,
                         Mapsvc, Messenger, mnmsrvc, MSDTC, MSIServer, msvsmon80, NetDDE,
                         NetDDEdsdm, NtmsSvc, NVSvc, ose, RasAuto, RDSessMgr, RemoteAccess,
                         RpcLocator, RSVP, SCardSvr, SwPrv, SysmonLog, TlntSvr, upnphost,
                         UPS, VSS, WmdmPmSN, Wmi, WmiApSrv, xmlprov}

$Log*Event
———-
        The Log*Event preference Variables determine which types of events
        are written to the Windows PowerShell event log in Event Viewer. By
        default, only engine and provider events are logged, but you can use
        the Log*Event preference Variables to customize your log, such as
        logging events about commands.

        The Log*Event preference Variables are as follows:

            $LogCommandHealthEvent: Logs errors and exceptions in command initialization
                and processing. Default = $false (not logged).

            $LogCommandLifecycleEvent:
                Logs the starting and stopping of commands and command pipelines
                and security exceptions in command discovery. Default = $false (not logged).

            $LogEngineHealthEvent: Logs errors and failures of sessions. Default = $true (logged).

            $LogEngineLifecycleEvent: Logs the opening and closing of sessions.
                Default = $true (logged).

            $LogProviderHealthEvent: Logs provider errors, such as read and write errors,
                lookup errors, and invocation errors. Default = $true (logged).

            $LogProviderLifecycleEvent: Logs adding and removing of Windows PowerShell providers.
                Default = $true (logged). (For information about Windows PowerShell providers, type:
                “Get-Help about_provider”.

        To enable a Log*Event, type the Variable with a value of $true, for example:

            $LogCommandLifeCycleEvent

            – or –

            $LogCommandLifeCycleEvent = $true

        To disable an event type, type the Variable with a value of $false, for example:

            $LogCommandLifeCycleEvent = $false

        The events that you enable are effective only for the current Windows PowerShell
        console. To apply the configuration to all consoles, save the Variable settings
        in your Windows PowerShell profile.

$MaximumAliasCount
——————
        Determines how many Aliases are permitted in a Windows PowerShell
        session. The default value, 4096, should be sufficient for most
        uses, but you can adjust it to meet your needs.

        Valid values: 1024 – 32768 (Int32)
        Default: 4096

        To count the Aliases on your system, type:

        (Get-Alias).count

$MaximumDriveCount
——————
        Determines how many Windows PowerShell drives are permitted in a
        given session. This includes file system drives and data stores that
        are exposed by Windows PowerShell providers and appear as drives,
        such as the Alias: and HKLM: drives.

        Valid values: 1024 – 32768 (Int32)
        Default: 4096

        To count the Aliases on your system, type:

        (Get-PSDrive).count

$MaximumErrorCount
——————
        Determines how many errors are saved in the error history
        for the session.

        Valid values: 256 – 32768 (Int32)
        Default: 256

        Objects that represent each retained error are stored in the
        $Error automatic Variable. This Variable contains an array of error
        record objects, one for each error. The most recent error is the
        first object in the array ($Error[0]).

        To count the errors on your system, use the Count property of
        the $Error array. Type:

        $Error.count

        To display a specific error, use array notation to display
        the error. For example, to see the most recent error, type:

                $Error[0]

        To display the oldest retained error, type:

                $Error[($Error.Count -1]

        To display the properties of the ErrorRecord object, type:

                $Error[0] | Format-List -property * -force

        In this command, the Force parameter overrides the special
        formatting of ErrorRecord objects and reverts to the conventional
        format.

        To delete all errors from the error history, use the Clear method
        of the error array.

             PS> $Error.count
             17
             PS> $Error.clear()
             PS>
             PS> $Error.count
             0

     To find all properties and methods of an error array, use the
     Get-Member cmdlet with its InputObject parameter. When you pipe a
     collection of objects to Get-Member, Get-Member displays the
     properties and methods of the objects in the collection. When you use
     the InputObject parameter of Get-Member, Get-Member displays the
     properties and methods of the collection.

$MaximumFunctionCount
——————
        Determines how many Functions are permitted in a given session.

        Valid values: 1024 – 32768 (Int32)
        Default: 4096

        To see the Functions in your session, use the Windows PowerShell
        Function: drive that is exposed by the Windows PowerShell Function
        provider. (For more information about the Function provider, type
        “Get-Help Function“).

        To list the Functions in the current session, type:

            Get-ChildItem Function:

        To count the Functions in the current session, type:

            (Get-ChildItem Function:).count

$MaximumHistoryCount
——————
        Determines how many commands are saved in the command history
        for the current session.

        Valid values: 1 – 32768 (Int32)
        Default: 64

        To determine the number of commands current saved in the command
        history, type:

            (Get-History).count

        To see the command saved in your session history, use the
        Get-History cmdlet. For more information, type:
        “Get-Help about_History“.

$MaximumVariableCount
——————
        Determines how many Variables are permitted in a given session,
        including automatic Variables, preference Variables, and the
        Variables that you create in commands and scripts.

        Valid values: 1024 – 32768 (Int32)
        Default: 4096

        To see the Variables in your session, use the Get-Variable cmdlet
        and the features of the Windows PowerShell Variable: drive and the
        Windows PowerShell Variable provider. For information about the
        Variable provider, type “Get-Help Variable“.

        To find the current number of Variables on the system, type:

            (Get-Variable).count

$OFS
—-
        Output Field Separator. Specifies the character that separates the
        elements of an array when the array is converted to a string.

        Valid values: Any string.
        Default: Space

        By default, the $OFS Variable does not exist and the output file
        separator is a space, but you can add this Variable and set it to
        any string.

    EXAMPLES

    This example shows that a space is used to separate the values when an
    array is converted to a string. In this case, an array of integers is
    stored in a Variable and then the Variable is cast as a string.

     PS> $array = 1,2,3                 # Store an array of integers.

     PS> [string]$array                 # Cast the array to a string.
     1 2 3                             # Spaces separate the elements

    To change the separator, add the $OFS Variable by assigning a value
    to it. To work correctly, the Variable must be named $OFS.

     PS> $OFS = “+”                     # Create $OFS and assign a “+”

     PS> [string]$array                 # Repeat the command
     1+2+3                             # Plus signs separate the elements

    To restore the default behavior, you can assign a space (” “) to
    the value of $OFS or delete the Variable. This command deletes the
    Variable and then verifies that the separator is a space.

     PS> Remove-Variable OFS            # Delete $OFS
     PS>

     PS> [string]$array                 # Repeat the command
     1 2 3                             # Spaces separate the elements

$OutputEncoding
—————
     Determines the character encoding method used by Windows PowerShell
     when it sends text to other applications. For example, if an
     application returns Unicode strings to Windows PowerShell, you might
     need to change the value to to send the characters correctly.

        Valid values: Objects derived from an encoding class, such as
                     ASCIIEncoding, SBCSCodePageEncoding, UTF7Encoding,
                     UTF8Encoding, UTF32Encoding, and UnicodeEncoding.

        Default: ASCIIEncoding object (System.Text.ASCIIEncoding)

    EXAMPLES

     This example shows how to make the FINDSTR command in Windows
     work in Windows PowerShell on a computer that is localized for
     a language that uses Unicode characters, such as Chinese.

     The first command finds the value of $OutputEncoding. Because the
     value is an encoding object, display only its EncodingName property.

         PS> $OutputEncoding.EncodingName # Find the current value
         US-ASCII

     In this example, a FINDSTR command is used to search for two Chinese
     characters that are present in the Test.txt file. When this FINDSTR
     command is run in the Windows Command Prompt (Cmd.exe), FINDSTR finds
     the characters in the text file. However, when you run the same
     FINDSTR command in Windows PowerShell, the characters are not found
     because the Windows PowerShell sends them to FINDSTR in ASCII text,
     instead of in Unicode text.

         PS> findstr <Unicode-characters> # Use findstr to search.
         PS>                             # None found.

     To make the command work in Windows PowerShell, set the value of
     $OutputEncoding to the value of the OutputEncoding property of the
     console, which is based on the locale selected for Windows. Because
     OutputEncoding is a static property of the console, use
     double-colons (::) in the command.

         PS> $OutputEncoding = [console]::outputencoding
         PS>                             # Set the value equal to the
                                             OutputEncoding property of the
                                             console.
         PS> $OutputEncoding.EncodingName
         OEM United States
                                            # Find the resulting value.

     As a result of this change, the FINDSTR command finds the characters.

         PS> findstr <Unicode-characters>
         test.txt:         <Unicode-characters>

                    # Use findstr to search. It find the
                                         characters in the text file.

$ProgressPreference
——————-
    Determines how Windows PowerShell responds to progress updates
        generated by a script, cmdlet or provider, such as the progress bars
        generated by the Write-Progress cmdlet. The Write-Progress cmdlet
        creates progress bars that depict the status of a command.

        Valid values:
        Stop:             Does not display the progress bar. Instead,
                                it displays an error message and stops executing.

             Inquire:            Does not display the progress bar. Prompts
                                for permission to continue. If you reply
                                with Y or A, it displays the progress bar.

            Continue:         Displays the progress bar and continues with
            (Default)         execution.

            SilentlyContinue: Executes the command, but does not display
                                the progress bar.

$PSEmailServer
————–
     Specifies the default e-mail server that is used to send e-mail
     messages. This preference Variable is used by cmdlets that send
     e-mail, such as the Send-MailMessage cmdlet.

$PSSessionApplicationName
—————————
     Specifies the default application name for a remote command
     that uses WS-Management technology.

     The system default application name is WSMan, but you can use this
     preference Variable to change the default.

     The application name is the last node in a connection URI. For
     example, the application name in the following sample URI is
     WSMan.

         http://Server01:8080/WSMAN

     The default application name is used when the remote command
     does not specify a connection URI or an application name.

     The WinRM service uses the application name to select a listener
     to service the connection request. The value of this parameter
     should match the value of the URLPrefix property of a listener
     on the remote computer.

     To override the system default and the value of this Variable,
     and select a different application name for a particular session,
     use the ConnectionURI or ApplicationName parameters of the
     New-PSSession, Enter-PSSession or Invoke-Command cmdlets.

     This preference Variable is set on the local computer, but it
     specifies a listener on the remote computer. If the application
     name that you specify does not exist on the remote computer,
     the command to establish the session fails.

$PSSessionConfigurationName
—————————
     Specifies the default session configuration that is used for
     PSSessions created in the current session.

     This preference Variable is set on the local computer, but it
     specifies a session configuration that is located on the remote
     computer.

     The value of the $PSSessionConfigurationName Variable is a fully
     qualified resource URI.

     The default value:

         http://schemas.microsoft.com/powershell/microsoft.powershell

     indicates the Microsoft.PowerShell session configuration
     on the remote computer.

     If you specify only a configuration name, the following schema URI
     is prepended:

         http://schemas.microsoft.com/powershell/

     You can override the default and select a different session
     configuration for a particular session by using the
     ConfigurationName parameter of the New-PSSession, Enter-PSSession
     or Invoke-Command cmdlets.

     You can change the value of this Variable at any time. When you
     do, remember that the session configuration that you select must
     exist on the remote computer. If it does not, the command to
     create a session that uses the session configuration fails.

     This preference Variable does not determine which local session
     configurations are used when remote users create a session that
     connects to this computer. However, you can use the permissions
     for the local session configurations to determine which users
     may use them.

$PSSessionOption
—————-
        Establishes the default values for advanced user options in a
        remote session. These option preferences override the system
        default values for session options.

        You can also set custom options for a particular remote session by
        using the SessionOption parameter in cmdlets that create a session,
        such as New-PSSession, Enter-PSSession, and Invoke-Command. The
        SessionOption parameter value takes precedence over the system defaults
        and the defaults that are set in this Variable.

        The $PSSessionOption Variable contains a PSSessionOption object
        (System.Management.Automation.Remoting.PSSessionObject). Each
        property of the object represents a session option. For example,
        the NoCompression property turns of data compression during the
        session.

        To create the $PSSessionOption preference Variable, use the
        New-PSSessionOption cmdlet. Save the output in a Variable called
        $PSSessionOption.

        For example,

            $PSSessionOption = New-PSSessionOption -NoCompression

        To use the $PSSessionOption preference Variable in every
        Windows PowerShell session, add a New-PSSessionOption command
        that creates the $PSSessionOption Variable to your Windows
        PowerShell profile.

        For more information about the New-PSSessionOption cmdlet, see
        the help topic for New-PSSessionOption. For more information about
        remote commands and sessions, see about_remote and about_pssessions.
        For more information about using a profile, see about_profiles.

$VerbosePreference
——————
         Determines how Windows PowerShell responds to verbose messages
        generated by a script, cmdlet or provider, such as the messages
        generated by the Write-Verbose cmdlet. Typically, verbose messages
        describe the actions performed to execute a command.

        By default, verbose messages are not displayed, but you can change
        this behavior by changing the value of $VerbosePreference.

        You can also use the Verbose common parameter of a cmdlet to display
        or hide the verbose messages for a specific command. For more
        information, type: “Get-Help about_CommonParameters“.

        Valid values:
        Stop:             Displays the verbose message and an error
                                message and then stops executing.

             Inquire:            Displays the verbose message and then
                                displays a prompt that asks you whether you
                                want to continue.

            Continue:         Displays the verbose message and then continues with execution.

            SilentlyContinue: Does not display the verbose message. Continues executing.
            (Default)

    EXAMPLES

    These examples show the effect of the different values of $VerbosePreference and the use of the
    Verbose common parameter to override the preference value.

    This example shows the effect of the SilentlyContinue value, which is the default.

        PS> $VerbosePreference             # Find the current value.
        SilentlyContinue

        PS> Write-Verbose “Verbose message test.”
        PS>                                # Write a verbose message.
                                         # Message is not displayed.

        PS> Write-Verbose “Verbose message test.” -Verbose
        VERBOSE: Verbose message test.
                                     # Use the Verbose parameter.

    This example shows the effect of the Continue value.

        PS> $VerbosePreference = “Continue”
                                         # Change the value to Continue.
        PS> Write-Verbose “Verbose message test.”
                                         # Write a verbose message.
        VERBOSE: Verbose message test.
                                         # Message is displayed.

        PS> Write-Verbose “Verbose message test.” -Verbose:$false
                                         # Use the Verbose parameter with
                                             a value of $false.
        PS>
                                         # Message is not displayed.

    This example shows the effect of the Stop value.

        PS> $VerbosePreference = “Stop”
                                         # Change the value to Stop.
        PS> Write-Verbose “Verbose message test.”
                                         # Write a verbose message.
        VERBOSE: Verbose message test.
        Write-Verbose : Command execution stopped because the shell Variable “VerbosePreference”
        is set to Stop.
        At line:1 char:14
        + Write-Verbose <<<< “Verbose message test.”

     PS> Write-Verbose “Verbose message test.” -Verbose:$false
                                         # Use the Verbose parameter with
                                            a value of $false
     PS>
                                         # Message is not displayed.

    This example shows the effect of the Inquire value.

     PS> $VerbosePreference = “Inquire”
                                         # Change the value to Inquire.
     PS> Write-Verbose “Verbose message test.”
     VERBOSE: Verbose message test.
                                         # Write a verbose message.
     Confirm
     Continue with this operation?
     [Y] Yes [A] Yes to All [H] Halt Command [S] Suspend [?] Help (default is “Y”): y
     PS>

     PS> Write-Verbose “Verbose message test.” -Verbose:$false
                                        # Use the Verbose parameter.
     PS>
                                        # Message is not displayed.

$WarningPreference
——————
        Determines how Windows PowerShell responds to warning messages
        generated by a script, cmdlet or provider, such as the messages
        generated by the Write-Warning cmdlet.

        By default, warning messages are displayed and execution continues,
        but you can change this behavior by changing the value of
        $WarningPreference.

        You can also use the WarningAction common parameter of a cmdlet to
        determine how Windows PowerShell responds to warnings from a particular
        command. For more information, type: “Get-Help about_CommonParameters“.

        Valid values:
        Stop:             Displays the warning message and an error
                                message and then stops executing.

             Inquire:            Displays the warning message and then
                                prompts for permission to continue.

            Continue:         Displays the warning message and then
            (Default)         continues executing.

            SilentlyContinue: Does not display the warning message.
                                Continues executing.

    EXAMPLES

    These examples show the effect of the different values of
    $WarningPreference and the use of the WarningAction common parameter
    to override the preference value.

    This example shows the effect of the Continue value, which is the
    default.

            PS> $WarningPreference    # Find the current value.
            Continue

                                     # Write a warning message.
            PS> Write-Warning “This action can delete data.”
            WARNING: This action can delete data.

                                     # Use the WarningAction parameter to
                                     # suppress the warning for this command
            PS> Write-Warning “This action can delete data.” -WarningAction silentlycontinue

This example shows the effect of the SilentlyContinue value.

            PS> $WarningPreference = “SilentlyContinue”
                                     # Change the value to SilentlyContinue.

            PS> Write-Warning “This action can delete data.”
            PS>                        # Write a warning message.

            PS> Write-Warning “This action can delete data.” -WarningAction stop
                                     # Use the WarningAction parameter to stop
                                     # processing when this command generates a
                                     # warning.
            WARNING: This action can delete data.
            Write-Warning : Command execution stopped because the shell Variable
            “WarningPreference” is set to Stop.
            At line:1 char:14
            + Write-Warning <<<< “This action can delete data.” -WarningAction stop

    This example shows the effect of the Inquire value.

         PS> $WarningPreference = “Inquire”
                                     # Change the value to Inquire.
         PS> Write-Warning “This action can delete data.”
                                     # Write a warning message.
         WARNING: This action can delete data.

         Confirm
         Continue with this operation?
         [Y] Yes [A] Yes to All [H] Halt Command [S] Suspend [?] Help (default is “Y”): y
         PS>

         PS> Write-Warning “This action can delete data.” -WarningAction silentlycontinue
         PS>                         # Use the WarningAction parameter to change the
                                     # response to a warning for the current command.

     This example shows the effect of the Stop value.

         PS> $WarningPreference = “Stop”
                                     # Change the value to Stop.

         PS> Write-Warning “This action can delete data.”
                                     # Write a warning message.
         WARNING: This action can delete data.
         Write-Warning : Command execution stopped because the shell Variable
             “WarningPreference” is set to Stop.
         At line:1 char:14
         + Write-Warning <<<< “This action can delete data.”

         PS> Write-Warning “This action can delete data.” -WarningAction inquire
         WARNING: This action can delete data.

         Confirm
         Continue with this operation?
         [Y] Yes [A] Yes to All [H] Halt Command [S] Suspend [?] Help (default is “Y”):
                                     # Use the WarningAction parameter to change the
                                     # response to a warning for the current command.

$WhatIfPreference
——————
         Determines whether WhatIf is automatically enabled for every command
        that supports it. When WhatIf is enabled, the cmdlet reports the
        expected effect of the command, but does not execute the command.

        Valid values:
        0:                 WhatIf is not automatically enabled. To
            (Default)         enable it manually, use the WhatIf parameter
                                of the command.

             1:                 WhatIf is automatically enabled on any
                                command that supports it. Users can use the
                                WhatIf command with a value of False to
                                disable it manually (WhatIf:$false).

    DETAILED EXPLANATION

        When a cmdlet supports WhatIf, the cmdlet reports the expected
        effect of the command, instead of executing the command. For
        example, instead of deleting the test.txt file in response to a
        Remove-Item command, Windows PowerShell reports what it would
        delete. A subsequent Get-ChildItem command confirms that the file
        was not deleted.

             PS> Remove-Item test.txt
             What if: Performing operation “Remove-Item” on Target “Item:
                C:\test.txt
             PS> Get-ChildItem test.txt

             Directory: Microsoft.PowerShell.Core\FileSystem::C:

             Mode                LastWriteTime     Length     Name
             —-                ————-     ——     —-
             -a—         7/29/2006 7:15 PM         84     test.txt

    EXAMPLES

    These examples show the effect of the different values of
    $WhatIfPreference. They also show how to use the WhatIf cmdlet parameter
    to override the preference value for a specific command.

    This example shows the effect of the 0 (not enabled) value, which is the
    default.

             PS> $whatifpreference
             0                         # Check the current value.

             PS> Get-ChildItem test.txt | Format-List FullName
             FullName : C:\test.txt
                                     # Verify that the file exists.

             PS> Remove-Item test.txt
             PS>                     # Delete the file.

             PS> Get-ChildItem test.txt | Format-List -property FullName
                                     # Verify that the file is deleted.

             Get-ChildItem : Cannot find path ‘C:\test.txt’ because it does not exist.
             At line:1 char:14
             + Get-ChildItem <<<< test.txt | Format-List fullname

     This example shows the effect of using the WhatIf parameter when the
     value of $WhatIfPreference is 0.

             PS> Get-ChildItem test2.txt | Format-List -property FullName
             FullName : C:\test2.txt
                                     # Verify that the file exists.

             PS> Remove-Item test2.txt -whatif
             What if: Performing operation “Remove File” on Target “C:\test2.txt”.
                                     # Use the WhatIf parameter

             PS> Get-ChildItem test2.txt | Format-List -property FullName
             FullName : C:\test2.txt
                                     # Verify that the file was not deleted

    This example shows the effect of the 1 (WhatIf enabled) value. When you
    use Remove-Item to delete a cmdlet, Remove-Item displays the path to the
    file that it would delete, but it does not delete the file.

             PS> $whatifpreference = 1
             PS> $whatifpreference
             1                        # Change the value.

             PS> Remove-Item test.txt
             What if: Performing operation “Remove File” on Target “C:\test.txt”.
                                     # Try to delete a file.

             PS> Get-ChildItem test.txt | Format-List FullName
             FullName : C:\test.txt
                                     # Verify that the file exists.

     This example shows how to delete a file when the value of
     $WhatIfPreference is 1. It uses the WhatIf parameter with a value of
     $false.

             PS> Remove-Item test.txt -whatif:$false
                                     # Use the WhatIf parameter with $false.

     This example demonstrates that some cmdlets support WhatIf behavior and
     others do not. In this example, in which the value of $WhatIfPreference
     is 1 (enabled), a Get-Process command, which does not support WhatIf,
     is executed, but a Stop-Process command performs the WhatIf behavior.
     You can override the WhatIf behavior of the Stop-Process command by
     using the WhatIf parameter with a value of $false.

            PS> $whatifpreference = 1
                                     # Change the value to 1.

            PS> Get-Process winword
                                    # A Get-Process command completes.

            Handles NPM(K)    PM(K)     WS(K) VM(M) CPU(s)     Id ProcessName
            ——- ——    —–     —– —– ——     — ———–
                234     8     6324     15060 154     0.36 2312 WINWORD

         PS> Stop-Process -name winword
         What if: Performing operation “Stop-Process” on Target “WINWORD (2312)”.
                                    # A Stop-Process command uses WhatIf.

         PS> Stop-Process -name winword -whatif:$false
         PS>                     # WhatIf:$false overrides the preference.

         PS> Get-Process winword
         Get-Process : Cannot find a process with the name ‘winword’. Verify the process name
            and call the cmdlet again.
         At line:1 char:12
         + Get-Process <<<< winword
                                    # Verify that the process is stopped.

SEE ALSO
    about_Automatic_Variables
    about_CommonParameters
    about_environment_variables
    about_profiles
    about_remote
    about_scopes
    about_Variables

about_profiles

TOPIC
    about_profiles

SHORT DESCRIPTION
    Describes how to create and use a Windows PowerShell profile.

LONG DESCRIPTION
    You can create a Windows PowerShell profile to customize your Environment
    and to add session-specific elements to every Windows PowerShell session
    that you start.

    A Windows PowerShell profile is a script that runs when Windows PowerShell
    starts. You can use the profile as a logon script to customize the
    Environment. You can add commands, Aliases, Functions, Variables, snap-ins,
    modules, and Windows PowerShell drives. You can also add other
    session-specific elements to your profile so they are available in every
    session without having to import or re-create them.

    Windows PowerShell supports several profiles for users and host programs.
    However, it does not create the profiles for you. This topic describes the
    profiles, and it describes how to create and maintain profiles on your
    computer.

    It explains how to use the NoProfile parameter of the Windows PowerShell
    console (PowerShell.exe) to start Windows PowerShell without any profiles.
    And, it explains the effect of the Windows PowerShell execution policy on
    profiles.

THE PROFILE FILES

    Windows PowerShell supports several profile files. Also, Windows PowerShell
    host programs can support their own host-specific profiles.

    For example, the Windows PowerShell console supports the following basic
    profile files. The profiles are listed in precedence order. The first
    profile has the highest precedence.

        Description                Path
        ———–                —-
        Current User, Current Host $Home\[My ]Documents\WindowsPowerShell\Profile.ps1
        Current User, All Hosts    $Home\[My ]Documents\Profile.ps1
        All Users, Current Host    $PsHome\Microsoft.PowerShell_profile.ps1
        All Users, All Hosts     $PsHome\Profile.ps1

    The profile paths include the following Variables:

        – The $PsHome Variable, which stores the installation directory for
         Windows PowerShell.

        – The $Home Variable, which stores the current user’s home directory.

    In addition, other programs that host Windows PowerShell can support their
    own profiles. For example, Windows PowerShell Integrated Scripting
    Environment (ISE) supports the following host-specific profiles.

        Description                Path
        ———–                —–
        Current user, Current Host $Home\[My ]Documents\WindowsPowerShell\Microsoft.PowerShellISE_profile.ps1
        All users, Current Host    $PsHome\Microsoft.PowerShellISE_profile.ps1

    In Windows PowerShell Help, the “CurrentUser, Current Host” profile is the profile most
    often referred to as “your Windows PowerShell profile”.

THE $PROFILE Variable

    The $Profile automatic Variable stores the paths to the Windows PowerShell
    profiles that are available in the current session.

    To view a profile path, display the value of the $Profile Variable. You can
    also use the $Profile Variable in a command to represent a path.

    The $Profile Variable stores the path to the “Current User,
    Current Host” profile. The other profiles are saved in note properties of
    the $profile Variable.

    For example, the $Profile Variable has the following values in the Windows
    PowerShell console.

        Name                             Description
        ———–                        ———–
        $Profile                         Current User,Current Host
        $Profile.CurrentUserCurrentHost    Current User,Current Host
        $Profile.CurrentUserAllHosts     Current User,All Hosts
        $Profile.AllUsersCurrentHost     All Users, Current Host
        $Profile.AllUsersAllHosts         All Users, All Hosts

    Because the values of the $Profile Variable change for each user and in
    each host application, ensure that you display the values of the
    profile Variables in each Windows PowerShell host application that you use.

    To see the current values of the $Profile Variable, type:

        $profile | Get-Member -type noteproperty

    You can use the $Profile Variable in many commands. For example, the
    following command opens the “Current User, Current Host” profile in
    Notepad:

    notepad $profile

    The following command determines whether an “All Users, All Hosts” profile
    has been created on the local computer:

    Test-Path $profile.AllUsersAllHosts

HOW TO CREATE A PROFILE

    To create a Windows PowerShell profile, use the following command format:

        if (!(Test-Path <profile-name>))
         {New-Item -type file -path <profile-name> -force}

    For example, to create a profile for the current user in the current
    Windows PowerShell host application, use the following command:

        if (!(Test-Path $profile))
         {New-Item -type file -path $profile -force}

    In this command, the If statement prevents you from overwriting an existing
    profile. Replace the value of the <profile-path> placeholder with the path
    to the profile file that you want to create.

    Note: To create “All Users” profiles in Windows Vista and later versions
         of Windows, start Windows PowerShell with the “Run as administrator”
         option.

HOW TO EDIT A PROFILE

    You can open any Windows PowerShell profile in a text editor, such as
    Notepad.

    To open the profile of the current user in the current Windows PowerShell
    host application in Notepad, type:

        notepad $profile

    To open other profiles, specify the profile name. For example, to open the
    profile for all the users of all the host applications, type:

        notepad $profile.AllUsersAllHosts

    To apply the changes, save the profile file, and then restart Windows
    PowerShell.

HOW TO CHOOSE A PROFILE

    If you use multiple host applications, put the items that you use in all
    the host applications into your $Profile.CurrentUserAllHosts profile.
    Put items that are specific to a host application, such as a command that
    sets the background color for a host application, in a profile that is
    specific to that host application.

    If you are an administrator who is customizing Windows
    PowerShell for many users, follow these guidelines:

        — Store the common items in the $profile.AllUsersAllHosts profile.

        — Store items that are specific to a host application in
         $profile.AllUsersCurrentHost profiles that are specific to the host
         application.

        — Store items for particular users in the user-specific profiles.

    Be sure to check the host application documentation for any special
    implementation of Windows PowerShell profiles.

HOW TO USE A PROFILE

    Many of the items that you create in Windows PowerShell and most commands
    that you run affect only the current session. When you end the session,
    the items are deleted.

    The session-specific commands and items include Variables, preference
    Variables, Aliases, Functions, commands (except for Set-ExecutionPolicy),
    and Windows PowerShell snap-ins that you add to the session.

    To save these items and make them available in all future sessions, add
    them to a Windows PowerShell profile.

    Another common use for profiles is to save frequently-used Functions,
    Aliases, and Variables. When you save the items in a profile, you can
    use them in any applicable session without re-creating them.

HOW TO START A PROFILE

    When you open the profile file, it is blank. However, you can fill it with
    the Variables, Aliases, and commands that you use frequently.

    Here are a few suggestions to get you started.

    — Add commands that make it easy to open your profile. This is especially
     useful if you use a profile other than the “Current User, Current Host”
     profile. For example, add the following command:

         Function pro {notepad $profile.CurrentUserAllHosts}

    — Add a Function that opens Windows PowerShell Help in a compiled HTML
     Help file (.chm).

         Function Get-CHM
            {
             (Invoke-Item $env:windir\help\mui\0409\WindowsPowerShellHelp.chm)
            }

     This Function opens the English version of the .chm file. However, you
     can replace the language code (0409) to open other versions of the .chm
     file.

    — Add a Function that lists the Aliases for any cmdlet.

         Function Get-CmdletAlias ($cmdletname)
         {
             Get-Alias | Where {$_.definition -like “*$cmdletname*”} | ft Definition, Name -auto
         }

    — Add an Add-PSSnapin command to add any Windows PowerShell snap-ins that
     you use.

    — Customize your console.

         Function Color-Console
         {
            $host.ui.rawui.backgroundcolor = “white”
            $host.ui.rawui.foregroundcolor = “black”
                $hosttime = (dir $pshome\powershell.exe).creationtime
                $Host.UI.RawUI.WindowTitle = “Windows PowerShell $hostversion ($hosttime)”
                clear-host
         }
         Color-console

    — Add a customized Windows PowerShell prompt that includes the computer
     name and the current path.

         Function prompt
         {
             $env:computername + “\” + (Get-Location) + “> ”
         }

     For more information about the Windows PowerShell prompt, see
     about_prompts.

THE NOPROFILE PARAMETER

    To start Windows Powershell without profiles, use the NoProfile parameter
    of PowerShell.exe, the program that starts Windows PowerShell.

    To begin, open a program that can start Windows PowerShell, such as Cmd.exe
    or Windows PowerShell itself. You can also use the Run dialog box in
    Windows.

    Type:

    powershell -noprofile

    For a complete list of the parameters of PowerShell.exe,
    type:

    powershell -?

PROFILES AND EXECUTION POLICY

    The Windows PowerShell execution policy determines, in part, whether you
    can run scripts and load configuration files, including the profiles. The
    Restricted execution policy is the default. It prevents all scripts from
    running, including the profiles. If you use the Restricted policy, the
    profile does not run, and its contents are not applied.

    A Set-ExecutionPolicy command sets and changes your execution policy. It is
    one of the few commands that applies in all Windows PowerShell sessions
    because the value is saved in the Registry. You do not have to set it when
    you open the console, and you do not have to store a Set-ExecutionPolicy
    command in your profile.

PROFILES AND REMOTE SESSIONS

    Windows PowerShell profiles are not run automatically in remote sessions,
    so the commands that the profileS add are not present in the remote session.
    In addition, the $profile automatic Variable is not populated in remote sessions.

    To run a profile in a session, use the Invoke-Command cmdlet.

    For example, the following command runs the CurrentUserCurrentHost profile from
    the local computer in the session in $s.

        Invoke-Command -session $s -filepath $profile

    The following command runs the CurrentUserCurrentHost profile from the remote
    computer in the session in $s. Because the $profile Variable is not populated,
    the command uses the explicit path to the profile.

        Invoke-Command -session $s {Invoke-Expression “$home\Documents\WindowsPowerShell\Microsoft.PowerShell_profile.ps1”}

    After running this command, the commands that the profile adds to the session
    are available in $s.

SEE ALSO
    about_Automatic_Variables
    about_functions
    about_prompts
    about_execution_policies
    about_Signing
    about_remote
    Set-ExecutionPolicy

about_job_details

TOPIC
about_job_details

SHORT DESCRIPTION
Provides details about background jobs on local and remote computers.

DETAILED DESCRIPTION
This topic explains the concept of a background job and provides technical
information about how background jobs work in Windows PowerShell.

This topic is a supplement to the about_jobs and about_remote_Jobs topics.

Important: Background jobs that are started by using Start-Job or the AsJob
             parameter of Invoke-Command rely on the Windows PowerShell
             remoting infrastructure. To use these features, Windows
             PowerShell must be configured for remoting, even if the
             background job is runs only on the local computer.
             For more information, see about_remote_requirements.

ABOUT BACKGROUND JOBS
    A background job runs a command or expression asynchronously. It might run
    a cmdlet, a Function, a script, or any other command-based task. It is
    designed to run commands that take an extended period of time, but you
    can use it to run any command in the background.

    When a synchronous command runs, the Windows PowerShell command prompt is
    suppressed until the command is complete. But a background job does not
    suppress the Windows PowerShell prompt. A command to start a background job
    returns a job object. The prompt returns immediately so you can work on
    other tasks while the background job runs.

    However, when you start a background job, you do not get the results
    immediately even if the job runs very quickly. The job object that is
    returned contains useful information about the job, but it does not contain
    the job results. You must run a separate command to get the job results.
    You can also run commands to stop the job, to wait for the job to be
    completed, and to delete the job.

    To make the timing of a background job independent of other commands, each
    background job runs in its own Windows PowerShell Environment
    (a “session”). However, this can be a temporary connection that is created
    only to run the job and is then destroyed, or it can be a persistent
    session (a PSSession) that you can use to run several related jobs or
    commands.

USING THE JOB CMDLETS
    Use a Start-Job command to start a background job on a local computer.
    Start-Job returns a job object. You can also get objects representing the
    jobs that were started on the local computer by using the Get-Job cmdlet.

    To get the job results, use a Receive-Job command. If the job is not
    complete, Receive-Job returns partial results. You can also use the
    Wait-Job cmdlet to suppress the command prompt until one or all of the
    jobs that were started in the session are complete.

    To stop a background job, use the Stop-Job cmdlet. To delete a job, use
    the Remove-Job cmdlet.

    For more information about how the cmdlets work, see the Help topic for
    each cmdlet, and see about_jobs.

STARTING BACKGROUND JOBS ON REMOTE COMPUTERS
    You can create and manage background jobs on a local or remote computer. To
    run a background job remotely, use the AsJob parameter of a cmdlet such as
    Invoke-Command, or use the Invoke-Command cmdlet to run a Start-Job
    command remotely. You can also start a background job in an interactive
    session.

    For more information about remote background jobs, see about_remote_Jobs.

CHILD JOBS
    Each background job consists of a parent job and one or more child jobs. In
    jobs started by using Start-Job or the AsJob parameter of Invoke-Command,
    the parent job is an executive. It does not run any commands or return any
    results. The commands are actually run by the child jobs. (Jobs started by
    using other cmdlets might work differently.)

    The child jobs are stored in the ChildJobs property of the parent job
    object. The ChildJobs property can contain one or many child job objects.
    The child job objects have a name, ID, and instance ID that differ
    from the parent job so that you can manage the parent and child jobs
    individually or as a unit.

    To see the parent and child jobs in a job, use the Get-Job cmdlet to get
    the parent job, and then pipe the job to a Format-List command that displays
    the Name and ChildJobs properties of the objects, as shown in the following
    command.

        C:\PS> Get-Job | Format-List -property Name, ChildJobs

        Name         : Job1
        ChildJobs     : {Job2}

    You can also use a Get-Job command on the child job, as shown in the
    following command:

        C:\PS> Get-Job job2

        Id    Name State     HasMoreData Location    Command
        —    —- —–     ———– ——–    ——-
        2     Job2 Completed True         localhost Get-Process

    The configuration of the child job depends on the command that you use to
    start the job.

     — When you use Start-Job to start a job on a local computer, the job
         consists of an executive parent job and a child job that runs the
         command.

     — When you use the AsJob parameter of Invoke-Command to start a job on
         one or more computers, the job consists of an executive parent job
         and a child job for each job run on each computer.

     — When you use Invoke-Command to run a Start-Job command on one or more
         remote computers, the result is the same as a local command run on
         each remote computer. The command returns a job object for each
         computer. The job object consists of an executive parent job and
         one child job that runs the command.

    The parent job represents all of the child jobs. When you manage a parent
    job, you also manage the associated child jobs. For example, if you stop a
    parent job, all child jobs are stopped. If you get the results of a parent
    job, you get the results of all child jobs.

    However, you can also manage child jobs individually. This is most useful
    when you want to investigate a problem with a job or get the results of
    only one of a number of child jobs started by using the AsJob parameter of
    Invoke-Command. (The backtick character [`] is the continuation character.)

    The following command uses the AsJob parameter of Invoke-Command to start
    background jobs on the local computer and two remote computers. The command
    saves the job in the $j Variable.

        C:\PS> $j = Invoke-Command -computername localhost, Server01, Server02 `
             -command {Get-Date} -AsJob

    When you display the Name and ChildJob properties of the job in $j, it
    shows that the command returned a job object with three child jobs, one for
    each computer.

        C:\PS> $j | Format-List name, childjobs

        Name     : Job3
        ChildJobs : {Job4, Job5, Job6}

    When you display the parent job, it shows that the job failed.

        C:\PS> $j

        Id Name    State HasMoreData     Location             Command
        — —-    —– ———–     ——–             ——-
        1    Job3    Failed True            localhost,server… Get-Date

    But when you run a Get-Job command on each of the child jobs, it shows
    that only one failed.

        PS C:\ps-test> Get-Job job4, job5, job6

        Id Name State     HasMoreData     Location         Command
        — —- —–     ———–     ——–         ——-
        4    Job4 Completed True            localhost         Get-Date
        5    Job5 Failed     False         Server01         Get-Date
        6    Job6 Completed True            Server02         Get-Date

    To get the results of all child jobs, use the Receive-Job cmdlet to get
    the results of the parent job. But you can also get the results of a
    particular child job, as shown in the following command.

        C:\PS> Receive-Job -job6 -keep | Format-Table ComputerName, DateTime -auto

        ComputerName DateTime
        ———— ——–
        Server02     Thursday, March 13, 2008 4:16:03 PM

    The child jobs feature of Windows PowerShell background jobs gives you
    more control over the jobs that you run.

SEE ALSO
    about_jobs
    about_remote_Jobs
    about_remote
    Invoke-Command
    Start-Job
    Get-Job
    Wait-Job
    Stop-Job
    Remove-Job
    New-PSSession
    Enter-PSSession
    Exit-PSSession

about_prompts

TOPIC
    about_prompts

SHORT DESCRIPTION
    Describes the Prompt Function and demonstrates how to create a custom
    Prompt Function.

LONG DESCRIPTION
    The Windows PowerShell command prompt indicates that Windows PowerShell
    is ready to run a command:

    PS C:\>

    The Windows PowerShell prompt is determined by the Prompt Function. You
    can customize the prompt by creating your own Prompt Function. Then, you
    can save this Function in your Windows PowerShell profile.

The Prompt Function

     The Prompt Function determines the appearance of the Windows PowerShell
     prompt. Windows PowerShell comes with a built-in Prompt Function, but
     you can override it by defining your own Prompt Function.

     The Prompt Function has the following syntax:

     Function prompt { <function-body> }

     The Prompt Function must return an object, typically a string. We
     recommend that it return a string or an object that is formatted as a
     string. The string should fit on an 80-character line.

     For example:

     PS C:\> Function prompt {“Hello, World > “}
         Hello, World >

     Like all Functions, the Prompt Function is stored in the Function: drive.
     To display the code in the current Prompt Function, type:

     (Get-Item Function:prompt).definition

     This command uses the Get-Item cmdlet to display the Prompt item in the
     Function: drive. Then, it uses dot notation to display the value of the
     Definition property of the Prompt Function.

The Default Prompt

     The default Windows PowerShell prompt is:

     PS>

     This prompt appears only when the prompt Function generates an error or
     when the prompt Function does not return a string or object.

         PS C:\> Function prompt {$null}
         PS>

     Because Windows PowerShell comes with a built-in prompt, you usually do
     not see the default prompt until you write your own prompt Function.

The Built-in Prompt

     Windows PowerShell includes a built-in prompt Function that creates the
     familiar prompts. The built-in prompt Function is:

         Function prompt
         {
             $(if (Test-Path Variable:/PSDebugContext) { ‘[DBG]: ‘ }

             else { ” }) + ‘PS ‘ + $(Get-Location) `

             + $(if ($nestedpromptlevel -ge 1) { ‘>>’ }) + ‘> ‘
         }

     The Function uses the Test-Path cmdlet to determine whether the
     $PSDebugContext automatic Variable is populated. If $PSDebugContext is
     populated, you are in debugging mode, and “[DBG]” is added to the prompt,
     as follows:

     [DBG] PS C:\ps-test>

     If $PSDebugContext is not populated, the Function adds “PS” to the
     prompt. And, the Function uses the Get-Location cmdlet to get the current
     file system directory location. Then, it adds a right angle bracket (>).
     For example:

     PS C:\ps-test>

     If you are in a nested prompt, the Function adds two angle brackets (>>)
     to the prompt. (You are in a nested prompt if the value of the
     $NestedPromptLevel automatic Variable is greater than 1.)

     For example, when you are debugging in a nested prompt, the prompt
     resembles the following prompt:

     [DBG] PS C:\ps-test>>>

     The Enter-PSSession cmdlet prepends the name of the remote computer to
     the current Prompt Function. When you use the Enter-PSSession cmdlet to
     start a session with a remote computer, the command prompt changes to
     include the name of the remote computer. For example:

         PS Hello, World> Enter-PSSession Server01

         [Server01]: PS Hello, World>

     Other Windows PowerShell host applications and alternate shells might
     have their own custom command prompts.

     For more information about the $PSDebugContext and $NestedPromptLevel
     automatic Variables, see about_Automatic_Variables.

Customizing the Prompt

     To customize the prompt, write a new Prompt Function. The Function is not
     protected, so you can overwrite it.

     To write a prompt Function, type the following:

     Function prompt { }

     Then, between the curly braces, enter the commands or the string that
     creates your prompt.

     For example, the following prompt includes your computer name:

     Function prompt {“PS [$env:COMPUTERNAME]> “}

     On the Server01 computer, the prompt resembles the following prompt:

     PS [Server01] >

     The following prompt Function includes the current date and time:

     Function prompt {“$(Get-Date)> “}

     The prompt resembles the following prompt:

     01/01/2008 17:49:47>

     You can also modify the default Prompt Function:

         Function prompt
         {
             $(if (Test-Path Variable:/PSDebugContext) { ‘[DBG]: ‘ }

             else { ” }) + “$(Get-Date)” `

             + $(if ($nestedpromptlevel -ge 1) { ‘>>’ }) + ‘> ‘
         }

     For example, the following modified Prompt Function adds “[ADMIN]:” to
     the built-in Windows PowerShell prompt when Windows PowerShell is opened
     by using the “Run as administrator” option:

         Function prompt
         {
             $identity = [Security.Principal.WindowsIdentity]::GetCurrent()
             $principal = [Security.Principal.WindowsPrincipal] $identity

             $(if (Test-Path Variable:/PSDebugContext) { ‘[DBG]: ‘ }

             elseif($principal.IsInRole([Security.Principal.WindowsBuiltInRole] “Administrator”))
                 { “[ADMIN]: ” }

             else { ” }) + ‘PS ‘ + $(Get-Location) + $(if ($nestedpromptlevel -ge 1) { ‘>>’ }) + ‘> ‘
         }

     When you start Windows PowerShell by using the “Run as administrator”
     option, a prompt that resembles the following prompt appears:

     [ADMIN]: PS C:\ps-test>

     The following Prompt Function displays the history ID of the next
     command. To view the command history, use the Get-History
     cmdlet.

         Function prompt
         {
             # The at sign creates an array in case only one history item exists.
             $history = @(Get-History)
             if($history.Count -gt 0)
             {
                $lastItem = $history[$history.Count – 1]
                $lastId = $lastItem.Id
             }

             $nextCommand = $lastId + 1
             $currentDirectory = Get-Location
             “PS: $nextCommand $currentDirectory >”
         }

     The following prompt uses the Write-Host and Get-Random cmdlets to create
     a prompt that changes color randomly. Because Write-Host writes to the
     current host application but does not return an object, this Function
     includes a Return statement. Without it, Windows PowerShell uses the
     default prompt, “PS>”.

         Function prompt
         {
             $color = Get-Random -min 1 -max 16
             Write-Host (“PS ” + $(Get-Location) +”>”) -nonewline -foregroundcolor $color
             return ” ”
         }

Saving the Prompt

     Like any Function, the Prompt Function applies only in the current
     session. To save the Prompt Function for future sessions, add it to your
     Windows PowerShell profiles. For more information about profiles,
     see about_profiles.

SEE ALSO
    Get-Location
    Enter-PSSession
    Get-History
    Get-Random
    Write-Host
    about_profiles
    about_functions
    about_scopes
    about_debuggers
    about_Automatic_Variables

about_join

TOPIC
    about_join

SHORT DESCRIPTION
    Describes how the join operator (-join) combines multiple strings into a
    single string.

LONG DESCRIPTION
    The join operator concatenates a set of strings into a single string. The
    strings are appended to the resulting string in the order that they appear
    in the command.

Syntax
     The following diagram shows the syntax for the join operator.

    -Join <String[]>
    <String[]> -Join <Delimiter>

Parameters
     String[]
         Specifies one or more strings to be joined.

     Delimiter
     Specifies one or more characters placed between the concatenated strings.
         The default is no delimiter (“”).

Remarks
     The unary join operator (-join <string[]>) has higher precedence than
     a comma. As a result, if you submit a comma-separated list of strings to
     the unary join operator, only the first string (before the first comma)
     is submitted to the join operator.

     To use the unary join operator, enclose the strings in parentheses, or
     store the strings in a Variable, and then submit the Variable to join.

     For example:

         -join “a”, “b”, “c”
         a
         b
         c

         -join (“a”, “b”, “c”)
         abc

         $z = “a”, “b”, “c”
         -join $z
         abc

Examples
     The following statement joins three strings:

         -join (“Windows”, “PowerShell”, “2.0”)
         WindowsPowerShell2.0

     The following statement joins three strings delimited by a space:

         “Windows”, “PowerShell”, “2.0” -join ” ”
         Windows PowerShell 2.0

     The following statements use a multiple-character delimiter to join
     three strings:

         $a = “WIND”, “SP”, “ERSHELL”
         $a -join “OW”
         WINDOWSPOWERSHELL

     The following statement joins the lines in a here-string into
     a single string. Because a here-string is one string, the lines in the
     here-string must be split before they can be joined. You can use this
     method to rejoin the strings in an XML file that has been saved in a
     here-string:

         $a = @’
         a
         b
         c
         ‘@

         (-split $a) -join ” ”
         a b c

SEE ALSO
    about_operators
    about_Comparison_Operators
    about_split

about_Language_Keywords

TOPIC
    about_Language_Keywords

SHORT DESCRIPTION
    Describes the keywords in the Windows PowerShell scripting language.

LONG DESCRIPTION
    Windows PowerShell has the following language keywords. For more
    information, see the about topic for the keyword and the information that
    follows the table.

        Keyword            Reference
        ——-            ———
        Begin             about_functions, about_functions_advanced
        Break             about_Break, about_trap
        Catch             about_try_catch_finally
        Continue         about_Continue, about_trap
        Data             about_data_sections
        Do                 about_do, about_While
        Dynamicparam     about_functions_advanced_parameters
        Else             about_If
        Elseif             about_If
        End                about_functions, about_functions_advanced_methods
        Exit             Described in this topic.
        Filter             about_functions
        Finally            about_try_catch_finally
        For                about_For
        Foreach            about_Foreach
        From             Reserved for future use.
        Function         about_functions, about_functions_advanced
        If                 about_If
        In                 about_Foreach
        Param             about_functions
        Process            about_functions, about_functions_advanced
        Return             about_Return
        Switch             about_Switch
        Throw             about_Throw, about_functions_advanced_methods
        Trap             about_trap, about_Break, about_try_catch_finally
        Try                about_try_catch_finally
        Until             about_do
        While             about_While, about_do

Language Keywords

     Begin
     —–

     Specifies one part of the body of a Function, along with the
     Dynamicparam, Process, and End keywords. The Begin statement list runs
     one time before any objects are received from the pipeline.

     Syntax:

         Function <name> {
             dynamicparam {<statement list>}
             begin {<statement list>}
             process {<statement list>}
             end {<statement list>}
         }

     Break
     —–

     Causes a script to exit a loop.

     Syntax:

         while (<condition>) {
             <statements>
                 …
             break
                 …
             <statements>
         }

     Catch
     —–

     Specifies a statement list to run if an error occurs in the
     accompanying Try statement list. An error type requires brackets. The
     second pair of brackets indicates that the error type is optional.

     Syntax:

         try {<statement list>}
         catch [[<error type>]] {<statement list>}

     Continue
     ——–

     Causes a script to stop running a loop and to go back to the condition.
     If the condition is met, the script begins the loop again.

     Syntax:

         while (<condition>) {
             <statements>
                 …
             continue
                 …
             <statements>
         }

     Data
     —-

     In a script, defines a section that isolates data from the script logic.
     Can also include If statements and some limited commands.

     Syntax:

     data <variable> [-supportedCommand <cmdlet-name>] {<permitted content>}

     Do
     —

     Used with the While or Until keyword as a looping construct. Windows
     PowerShell runs the statement list at least one time, unlike a loop that
     uses While.

     Syntax:

         do {<statement list>} while (<condition>)

         do {<statement list>} until (<condition>)

     Dynamicparam
     ————

     Specifies one part of the body of a Function, along with the Begin,
     Process, and End keywords. Dynamic parameters are added at run time.

     Syntax:

         Function <name> {
             dynamicparam {<statement list>}
             begin {<statement list>}
             process {<statement list>}
             end {<statement list>}
         }

     Else
     —-

     Used with the If keyword to specify the default statement list.

     Syntax:

         if (<condition>) {<statement list>}
         else {<statement list>}

     Elseif
     ——

     Used with the If and Else keywords to specify additional conditionals.
     The Else keyword is optional.

     Syntax:

         if (<condition>) {<statement list>}
         elseif (<condition>) {<statement list>}
         else {<statement list>}

     End
     —

     Specifies one part of the body of a Function, along with the
     Dynamicparam, Begin, and End keywords. The End statement list runs one
     time after all the objects have been received from the pipeline.

     Syntax:

         Function <name> {
             dynamicparam {<statement list>}
             begin {<statement list>}
             process {<statement list>}
             end {<statement list>}
         }

     Exit
     —-

     Causes Windows PowerShell to exit a script or a Windows PowerShell
     instance.

     Syntax:

         exit

     Filter
     ——

     Specifies a Function in which the statement list runs one time for each
     input object. It has the same effect as a Function that contains only a
     Process block.

     Syntax:

         filter <name> {<statement list>}

     Finally
     ——-

     Defines a statement list that runs after statements that are associated
     with Try and Catch. A Finally statement list runs even if you press
     CTRL+C to leave a script or if you use the Exit keyword in the script.

     Syntax:

         try {<statement list>}
         catch [<error type] {<statement list>}
         finally {<statement list>}

     For
     —

     Defines a loop by using a condition.

     Syntax:

         for (<initialize>; <condition>; <iterate>) {<statement list>}

     Foreach
     ——-

     Defines a loop by using each member of a collection.

     Syntax:

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

     From
     —–

     Reserved for future use.

     Function
     ——–

     Creates a named statement list of reusable code. You can name the scope a
     Function belongs to. And, you can specify one or more named parameters by
     using the Param keyword. Within the Function statement list, you can
     include Dynamicparam, Begin, Process, and End statement lists.

     Syntax:

         Function [<scope:>]<name> {
             param ([type]<$pname1> [, [type]<$pname2>])
             dynamicparam {<statement list>}
             begin {<statement list>}
             process {<statement list>}
             end {<statement list>}
         }

     You also have the option of defining one or more parameters outside the
     statement list after the Function name.

     Syntax:

         Function [<scope:>]<name> [([type]<$pname1>, [[type]<$pname2>])] {
             dynamicparam {<statement list>}
             begin {<statement list>}
             process {<statement list>}
             end {<statement list>}
         }

     If
     —

     Defines a conditional.

     Syntax:

         if (<condition>) {<statement list>}

     In
     —

     Used in a Foreach statement to create a loop that uses each member of a
     collection.

     Syntax:

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

     Param
     —–

     Defines the parameters in a Function.

     Syntax:

         Function [<scope:>]<name> {
             param ([type]<$pname1>[, [[type]<$pname2>]])
             <statement list>
         }

     Process
     ——-

     Specifies a part of the body of a Function, along with the Dynamicparam,
     Begin, and End keywords. When a Process statement list receives input
     from the pipeline, the Process statement list runs one time for each
     element from the pipeline. If the pipeline provides no objects, the
     Process statement list does not run. If the command is the first command
     in the pipeline, the Process statement list runs one time.

     Syntax:

         Function <name> {
             dynamicparam {<statement list>}
             begin {<statement list>}
             process {<statement list>}
             end {<statement list>}
         }

     Return
     ——

     Causes Windows PowerShell to leave the current scope, such as a script or
     Function, and writes the optional expression to the output.

     Syntax:

         return [<expression>]

     Switch
     ——

     Specifies a variety of actions to be performed on items from the pipeline
     or from a file. You can use either of the following syntax models.

     Syntax 1:

         switch [-regex|-wildcard|-exact][-casesensitive] ( pipeline )

         {
             <string>|<number>|<variable>|{ <expression> } {<statement list>}
             <string>|<number>|<variable>|{ <expression> } {<statement list>}
                    …
             default {<statement list>}
         }

     Syntax 2:

         switch [-regex|-wildcard|-exact][-casesensitive] -file filename
         {
             <string>|<number>|<variable>|{ <expression> } {<statement list>}
             <string>|<number>|<variable>|{ <expression> } {<statement list>}
                    …
             default {<statement list>}
         }

     Throw
     —–

     Throws an object as an error.

     Syntax:

         throw [<object>]

     Trap
     —-

     Defines a statement list to be run if an error is encountered. An error
     type requires brackets. The second pair of brackets indicates that the
     error type is optional.

     Syntax:

         trap [[<error type>]] {<statement list>}

     Try
     —

     Defines a statement list to be checked for errors while the statements
     run. If an error occurs, Windows PowerShell continues running in a Catch
     or Finally statement. An error type requires brackets. The second pair of
     brackets indicates that the error type is optional.

     Syntax:

         try {<statement list>}
         catch [[<error type]] {<statement list>}
         finally {<statement list>}

     Until
     —–

     Used in a Do statement as a looping construct where the statement list is
     executed at least one time.

     Syntax:

         do {<statement list>} until (<condition>)

     While
     —–

     Used in a Do statement as a looping construct where the statement list is
     executed at least one time.

     Syntax:

         do {<statement list>} while (<condition>)

SEE ALSO
     about_escape_characters
     about_Special_Characters
     about_wildcards

about_Line_Editing

TOPIC
    about_Line_Editing

SHORT DESCRIPTION
    Describes how to edit commands at the Windows PowerShell command prompt.

LONG DESCRIPTION
    The Windows PowerShell console has some useful features to help
    you to edit commands at the Windows PowerShell command prompt.

    Move Left and Right
        To move the cursor one character to the left, press the LEFT ARROW
        key. To move the cursor one word to the left, press CTRL+LEFT ARROW.
        To move the cursor one character to the right, press the RIGHT ARROW
        key. To move the cursor one word to the right, press CTRL+RIGHT ARROW.

    Line Start and End
        To move to the beginning of a line, press the HOME key. To move to the
        end of a line, press the END key.

    Delete Characters
        To delete the character in behind the cursor, press the BACKSPACE key.
        To delete the character in front of the cursor, press the DELETE key.

    Delete the Remainder of a Line
        To delete all the characters in the line after the cursor, press
        CTRL+END.

    Insert/Overstrike Mode
        To change to overstrike mode, press the INSERT key. To return to insert
        mode, press INSERT again.

    Tab Completion
        To complete a command, such as the name of a cmdlet, a cmdlet
        parameter, or a path, press the TAB key. If the first suggestion that
        is displayed is not what you want, press the TAB key again.

SEE ALSO
    about_Command_Syntax
    about_Path_Syntax

about_locations

TOPIC
    about_locations

SHORT DESCRIPTION
    Describes how to access items from the working location in Windows
    PowerShell.

LONG DESCRIPTION
    The current working location is the default location to which commands
    point. In other words, this is the location that Windows PowerShell uses
    if you do not supply an explicit path to the item or location that is
    affected by the command. In most cases, the current working location is
    a drive accessed through the Windows PowerShell FileSystem provider and,
    in some cases, a directory on that drive. For example, you might set your
    current working location to the following location:

        C:\Program Files\Windows PowerShell

    As a result, all commands are processed from this location unless
    another path is explicitly provided.

    Windows PowerShell maintains the current working location for each drive
    even when the drive is not the current drive. This allows you to access
    items from the current working location by referring only to the drive of
    another location. For example, suppose that your current working location
    is C:\Windows. Now, suppose you use the following command to change your
    current working location to the HKLM: drive:

        Set-Location HKLM:

    Although your current location is now the Registry drive, you can still
    access items in the C:\Windows directory simply by using the C: drive,
    as shown in the following example:

        Get-ChildItem C:

    Windows PowerShell remembers that your current working location for that
    drive is the Windows directory, so it retrieves items from that directory.
    The results would be the same if you ran the following command:

        Get-ChildItem C:\Windows

    In Windows PowerShell, you can use the Get-Location command to determine
    the current working location, and you can use the Set-Location command to
    set the current working location. For example, the following command sets
    the current working location to the Windows directory of the C: drive:

        Set-Location c:\windows

    After you set the current working location, you can still access items
    from other drives simply by including the drive name (followed by a
    colon) in the command, as shown in the following example:

        Get-ChildItem HKLM :\software

    The example command retrieves a list of items in the Software container
    of the HKEY Local Machine hive in the Registry.

    Windows PowerShell also allows you to use special characters to represent
    the current working location and its parent location. To represent the
    current working location, use a single period. To represent the parent of
    the current working location, use two periods. For example, the following
    specifies the System subdirectory in the current working location:

        Get-ChildItem .\system

    If the current working location is C:\Windows, this command
    returns a list of all the items in C:\Windows\System. However, if you
    use two periods, the parent directory of the current working
    directory is used, as shown in the following example:

        Get-ChildItem ..\”program files”

    In this case, Windows PowerShell treats the two periods as the C: drive,
    so the command retrieves all the items in the C:\Program Files directory.

    A path beginning with a slash identifies a path from the root of the
    current drive. For example, if your current working location is
    C:\Program Files\Windows PowerShell, the root of your drive is C.
    Therefore, the following command lists all items in the C:\Windows
    directory:

        Get-ChildItem \windows

    If you do not specify a path beginning with a drive name, slash, or
    period when supplying the name of a container or item, the
    container or item is assumed to be located in the current working
    location. For example, if your current working location is C:\Windows,
    the following command returns all the items in the C:\Windows\System
    directory:

        Get-ChildItem system

    If you specify a file name rather than a directory name, Windows
    PowerShell returns details about that file (assuming that file is located
    in the current working location).

SEE ALSO
    Set-Location
    about_providers
    about_Path_Syntax

about_logical_operators

TOPIC
    about_logical_operators

SHORT DESCRIPTION
    Describes the operators that connect statements in Windows PowerShell.

LONG DESCRIPTION
    The Windows PowerShell logical operators connect expressions and
    statements, allowing you to use a single expression to test for multiple
    conditions.

    For example, the following statement uses the and operator and
    the or operator to connect three conditional statements. The statement is
    true only when the value of $a is greater than the value of $b, and
    either $a or $b is less than 20.

        ($a -gt $b) -and (($a -lt 20) -or ($b -lt 20))

    Windows PowerShell supports the following logical operators.

        Operator Description                     Example
        ——– —————————— ————————
        -and     Logical and. TRUE only when     (1 -eq 1) -and (1 -eq 2)
                 both statements are TRUE.         False

        -or     Logical or. TRUE when either     (1 -eq 1) -or (1 -eq 2)
                 or both statements are TRUE.     True

        -xor     Logical exclusive or. TRUE     (1 -eq 1) -xor (2 -eq 2)
                 only when one of the statements False
                 is TRUE and the other is FALSE.

        -not     Logical not. Negates the         -not (1 -eq 1)
                 statement that follows it.     False

        !         Logical not. Negates the         !(1 -eq 1)
                 statement that follows it.     False
                 (Same as -not)

    Note: The previous examples also use the equal to comparison
         operator (-eq). For more information, see about_Comparison_Operators.
         The examples also use the Boolean values of integers. The integer 0
         has a value of FALSE. All other integers have a value of TRUE.

    The syntax of the logical operators is as follows:

        <statement> {-AND | -OR | -XOR} <statement>
        {! | -NOT} <statement>

    Statements that use the logical operators return Boolean (TRUE or FALSE)
    values.

    The Windows PowerShell logical operators evaluate only the statements
    required to determine the truth value of the statement. If the left operand
    in a statement that contains the and operator is FALSE, the right operand
    is not evaluated. If the left operand in a statement that contains
    the or statement is TRUE, the right operand is not evaluated. As a result,
    you can use these statements in the same way that you would use
    the If statement.

SEE ALSO
    about_operators
    Compare-Object
    about_Comparison_Operators
    about_If

about_methods

TOPIC
    about_methods

SHORT DESCRIPTION
    Describes how to use methods to perform actions on objects in Windows
    PowerShell.

LONG DESCRIPTION
    Windows PowerShell uses structured collections of information, called
    objects, to represent the items in data stores or the state of the
    computer. For example, when you access a file in Windows PowerShell, you
    are not working with the actual file. Instead, you are working with a
    FileInfo object, a type of object that acts as the file’s proxy.

    Most objects include methods. A method is a set of instructions that
    specify a particular action you can take with that object. For instance,
    the FileInfo object includes a method called CopyTo, which allows you to
    copy the file represented by the object.

    To view a list of methods and method definitions associated with a
    particular object, you can use the Get-Member cmdlet. However, to use
    the cmdlet, the object must already exist in some form, either as
    represented through a Variable, as an object created when you specify a
    command as an argument to the Get-Member command, or as an object
    passed down a pipeline. For example, suppose that the $a Variable has
    been assigned a string value, which means that the Variable is
    associated with a string object. To view a list of the object’s
    methods, enter the following command at the Windows PowerShell command
    prompt:

        Get-Member -inputobject $a -membertype method

    If you want to see which methods and method definitions are associated
    with an object that is passed down the pipeline, you would use a
    Get-Member command within the pipeline, as shown in the following example:

        Get-ChildItem c:\final.txt | Get-Member -membertype method

    The most common way to invoke a method is to specify the method name
    after an object reference (such as a Variable or expression). You must
    separate the object reference and the method with a period. Additionally,
    you must use parentheses immediately following the method name to enclose
    any arguments that should be passed to the method.

    If no arguments are being passed in a method signature, you must still
    use a set of empty parentheses.

    For example, the following command uses the GetType method to return the
    data type associated with the $a string object:

        $a.GetType()

    The GetType method will return the data type for any object, and a
    Variable always represents an object. The type of object depends on the
    type of data stored within that Variable.

    Every action you take in Windows PowerShell is associated with objects,
    whether you are declaring a Variable or combining commands into a pipeline.
    As a result, methods can be used in a variety of situations. For example,
    you can use a method to take an action on a property value, as shown in
    the following command:

        (Get-ChildItem c:\final.txt).name.ToUpper()

    In this case, the object on which the ToUpper method is being invoked is
    the string object associated with the name property. (Note that the
    Final.txt file must exist on the root of the C: drive for this example
    to work.) The name property is actually a property of the FileInfo object
    returned by the Get-ChildItem command. This demonstrates not only the
    object-oriented nature of Windows PowerShell, but shows how methods can be
    called on any accessible object.

    You can achieve the same results as the last example by using a
    Variable to store the Get-ChildItem command output, as shown in the
    following example:

        $a = (Get-ChildItem c:\final.txt).name
        $a.ToUpper()

    The command again uses the ToUpper method of the string object
    associated with the Variable, which contains the file name returned by
    the Get-ChildItem command.

    In some cases, a method requires an argument to direct the action of
    that method. For example, the FileInfo object includes the MoveTo
    method, which provides a way to move a file from one location to
    another. The method requires an argument that specifies the target
    location for the file. The following command demonstrates how to
    include that argument:

        (Get-ChildItem c:\final.txt).MoveTo(“c:\techdocs\final.txt”)

    The Get-ChildItem command returns a FileInfo object for the Final.txt
    file and then uses the MoveTo method of that object to initiate the
    action and to specify the file’s new location.

    To determine the arguments associated with a method, review the
    corresponding method definition. A method definition contains one or
    more method signatures (also known as overloads in the Microsoft
    .NET Framework). A method signature contains the name of a method and zero
    or more parameters that you must supply when you call the method. Each
    method signature is separated from the prior signature with a comma in the
    Get-Member cmdlet display. For example, the CopyTo method of the
    FileInfo class contains the following two method signatures:

        1. CopyTo(String destFileName)
        2. CopyTo(String destFileName, Boolean overwrite)

    The first method signature takes the destination file name (including
    the path) in which to copy the source file. In the following example,
    the first CopyTo method is used to copy Final.txt to the C:\Bin
    directory:

        (Get-ChildItem c:\final.txt).CopyTo(“c:\bin\final.txt”)

    If the file already exists in the destination location, the CopyTo
    method fails, and Windows PowerShell reports the following error:

        Exception calling “CopyTo” with “1” argument(s): “The file
        ‘c:\bin\final.txt’ already exists.”.

    In the second method signature, you pass the destination file name just
    as you did in the first case, but you also pass a Boolean value to
    specify whether you want an existing file of the same name in the
    destination location to be overwritten, as the following example shows:

        (Get-ChildItem c:\final.txt).CopyTo(“c:\bin\final.txt”, $true)

    When you pass the Boolean value, you must use the $True Variable, which
    is created automatically by Windows PowerShell. The $True Variable
    contains the “true” Boolean value. (As you would expect, the $False
    Variable contains the “false” Boolean value.)

SEE ALSO
    about_objects
    Get-Member