All posts by Adam

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_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_pipelines

TOPIC
    about_pipelines

SHORT DESCRIPTION
    Combining commands into pipelines in the Windows PowerShell

LONG DESCRIPTION
    A pipeline is a series of commands connected by pipeline operators
(|)(ASCII 124). Each pipeline operator sends the results of the preceding
    command to the next command.

    You can use pipelines to send the objects that are output by one command
    to be used as input to another command for processing. And you can send the
    output of that command to yet another command. The result is a very powerful
    command chain or “pipeline” that is comprised of a series of simple commands.

    For example,

    Command-1 | Command-2 | Command-3

    In this example, the objects that Command-1 emits are sent to Command-2.
    Command-2 processes the objects and sends them to Command-3. Command-3 processes
    the objects and send them down the pipeline. Because there are no more commands in
    the pipeline, the results are displayed at the console.

    In a pipeline, the commands are processed from left to right in the order
    that they appear. The processing is handled as a single operation and
    output is displayed as it is generated.

    Here is a simple example. The following command gets the Notepad process
    and then stops it.

         Get-Process notepad | Stop-Process

    The first command uses the Get-Process cmdlet to get an object representing
    the Notepad process. It uses a pipeline operator (|) to send the process object
    to the Stop-Process cmdlet, which stops the Notepad process. Notice that the
    Stop-Process command does not have a Name or ID parameter to specify the process,
    because the specified process is submitted through the pipeline.

    Here is a practical example. This command pipeline gets the text files in the
    current directory, selects only the files that are more than 10,000 bytes long,
    sorts them by length, and displays the name and length of each file in a table.

        Get-ChildItem -path *.txt | Where-Object {$_.length -gt 10000} |
        Sort-Object -property Length | Format-Table -property name, length

    This pipeline is comprised of four commands in the specified order. The command
    is written horizontally, but we will show the process vertically in the following
    graphic.

     Get-ChildItem -path *.txt

                 |
                 | (FileInfo objects )
                 | (    .txt         )
                 |
                 V

     Where-Object {$_.length -gt 10000}

                 |
                 | (FileInfo objects )
                 | (    .txt         )
                 | ( Length > 10000 )
                 |
                 V

     Sort-Object -property Length

                 |
                 | (FileInfo objects )
                 | (    .txt         )
                 | ( Length > 10000 )
                 | ( Sorted by length )
                 |
                 V

     Format-Table -property name, length

                 |
                 | (FileInfo objects     )
                 | (    .txt             )
                 | ( Length > 10000     )
                 | ( Sorted by length    )
                 | (Formatted in a table )
                 |
                 V
        Name                     Length
        —-                     ——
        tmp1.txt                    82920
        tmp2.txt                 114000
        tmp3.txt                 114000

USING PIPELINES

    The Windows PowerShell cmdlets were designed to be used in pipelines. For example,
    you can usually pipe the results of a Get cmdlet to an action cmdlet (such as a Set,
    Start, Stop, or Rename cmdlet) for the same noun.

    For example, you can pipe any service from the Get-Service cmdlet to the Start-Service
    or Stop-Service cmdlets (although disabled services cannot be restarted in this way).

    This command pipeline starts the WMI service on the computer:

    Get-Service wmi | Start-Service

    The cmdlets that get and set objects of the Windows PowerShell providers, such as the
    Item and ItemProperty cmdlets, are also designed to be used in pipelines.

    For example, you can pipe the results of a Get-Item or Get-ChildItem command in the
    Windows PowerShell Registry provider to the New-ItemProperty cmdlet. This command adds
    a new Registry entry, NoOfEmployees, with a value of 8124, to the MyCompany Registry key.

     Get-Item -path HKLM:\Software\MyCompany | New-Itemproperty -name NoOfEmployees -value 8124

    Many of the utility cmdlets, such as Get-Member, Where-Object, Sort-Object, Group-Object,
    and Measure-Object are used almost exclusively in pipelines. You can pipe any objects to
    these cmdlets.

    For example, you can pipe all of the processes on the computer to the Sort-Object command
    and have them sorted by the number of handles in the process.

    Get-Process | Sort-Object -property handles

    Also, you can pipe any objects to the formatting cmdlets, such as Format-List and
    Format-Table, the Export cmdlets, such as Export-Clixml and Export-Csv, and the Out
    cmdlets, such as Out-Printer.

    For example, you can pipe the Winlogon process to the Format-List cmdlet to display all
    of the properties of the process in a list.

    Get-Process winlogon | Format-List -property *

    With a bit of practice, you’ll find that combining simple commands into pipelines
    saves time and typing, and makes your scripting more efficient.

HOW PIPELINES WORK

     When you “pipe” objects, that is send the objects in the output of one command to another
     command, Windows Powershell tries to associate the piped objects with one of the parameters
     of the receiving cmdlet.

     To do so, the Windows Powershell “parameter binding” component, which associates input objects
     with cmdlet parameters, tries to find a parameter that meets the following criteria:

     — The parameter must accept input from a pipeline (not all do)
     — The parameter must accept the type of object being sent or a type that the object
        can be converted to.
     — The parameter must not already be used in the command.

     For example, the Start-Service cmdlet has many parameters, but only two of them, Name and InputObject
     accept pipeline input. The Name parameter takes strings and the InputObject parameter takes
     service objects. Therefore, you can pipe strings and service objects (and objects with properties
     that can be converted to string and service objects) to Start-Service.

     If the parameter binding component of Windows PowerShell cannot associate the piped objects
     with a parameter of the receiving cmdlet, the command fails and Windows PowerShell prompts you
     for the missing parameter values.

     You cannot force the parameter binding component to associate the piped objects with a particular
     parameter — you cannot even suggest a parameter. Instead, the logic of the component manages
     the piping as efficiently as possible.

ONE-AT-A-TIME PROCESSING

     Piping objects to a command is much like using a parameter of the command to submit the
     objects.

     For example, piping objects representing the services on the computer to a Format-Table command,
     such as:

         Get-Service | Format-Table -property name, dependentservices

     is much like saving the service objects in a Variable and using the InputObject parameter
     of Format-Table to submit the service object.

         $services = Get-Service
                 Format-Table -inputobject $services -property name, dependentservices

     or imbedding the command in the parameter value

                 Format-Table -inputobject (Get-Service wmi) -property name, dependentservices

     However, there is an important difference. When you pipe multiple objects to a command,
     Windows PowerShell sends the objects to the command one at a time. When you use a
     command parameter, the objects are sent as a single array object.

     This seemingly technical difference can have interesting, and sometimes useful, consequences.

     For example, if you pipe multiple process objects from the Get-Process cmdlet to the
     Get-Member cmdlet, Windows PowerShell sends each process object, one at a time, to Get-Member.
     Get-Member displays the .NET class (type) of the process objects, and their properties and methods.
     (Get-Member eliminates duplicates, so if the objects are all of the same type, it displays only
     one object type.)

     In this case, Get-Member displays the properties and methods of each process object, that is, a
     System.Diagnostics.Process object.

                 Get-Process | Get-Member

                    TypeName: System.Diagnostics.Process

                 Name                         MemberType     Definition
                 —-                         ———-     ———-
                 Handles                        AliasProperty Handles = Handlecount
                 Name                         AliasProperty Name = ProcessName
                 NPM                            AliasProperty NPM = NonpagedSystemMemorySize
                 …

     However, if you use the InputObject parameter of Get-Member, then Get-Member receives an
     array of System.Diagnostics.Process objects as a single unit, and it displays the properties
     of an array of objects. (Note the array symbol ([]) after the System.Object type name.)

                Get-Member -inputobject (Get-Process)

                TypeName: System.Object[]

                Name             MemberType    Definition
                —-             ———-    ———-
                Count             AliasProperty Count = Length
                Address            Method        System.Object& Address(Int32 )
                Clone             Method        System.Object Clone()
                …

     This result might not be what you intended, but after you understand it, you can use it. For
     example, an array of process objects has a Count property that you can use to count the number
     of processes on the computer.

        (Get-Process).count

     This distinction can be important, so remember that when you pipe objects to a cmdlet, they
     are delivered one at a time.

ACCEPTS PIPELINE INPUT

    In order to receive objects in a pipeline, the receiving cmdlet must have a parameter
    that accepts pipeline input. You can use a Get-Help command with the Full or Parameter
    parameters to determine which, if any, of a cmdlet’s parameters accepts pipeline input.

    In the Get-Help default display, the “Accepts pipeline input” item appears in a table
    of parameter attributes. This table is displayed only when you use the Full or Parameter
    parameters of the Get-Help cmdlet.

    For example, to determine which of the parameters of the Start-Service cmdlet accepts
    pipeline input, type:

        Get-Help Start-Service -full

        Get-Help Start-Service -parameter *

    For example, the help for the Start-Service cmdlet shows that the Name and InputObject
    parameters accept pipeline input (“true”). All other parameters have a value of “false”
    in the “Accept pipeline input?” row.

        -name <string[]>
         Specifies the service names for the service to be started.
         The parameter name is optional. You can use “-Name” or its Alias,
         “-ServiceName”, or you can omit the parameter name.

         Required?                    true
         Position?                    1
         Default value
     –> Accept pipeline input?     true (ByValue, ByPropertyName)
         Accept wildcard characters? true

        -inputObject <ServiceController[]>
         Specifies ServiceController objects representing the services to be started. Enter
         a Variable that contains the objects or type a command or expression that gets the
         objects.

         Required?                    false
         Position?                    named
         Default value
     –> Accept pipeline input?     true (ByValue)
         Accept wildcard characters? false

     This means that you can send objects (PsObjects) through the pipeline to the
     Where-Object cmdlet and Windows PowerShell will associate the object with the
     InputObject parameter.

METHODS OF ACCEPTING PIPELINE INPUT

     Cmdlets parameters can accept pipeline input in one of two different ways:

     — ByValue: Parameters that accept input “by value” can accept piped objects
        that have the same .NET type as their parameter value or objects that can be
        converted to that type.

        For example, the Name parameter of Start-Service accepts pipeline input
        by value. It can accept string objects or objects that can be converted to
        strings.

     — ByPropertyName: Parameters that accept input “by property name” can accept piped
        objects only when a property of the object has the same name as the parameter.

        For example, the Name parameter of Start-Service can accept objects that have
        a Name property.

        (To list the properties of an object, pipe it to Get-Member.)

     Some parameters can accept objects by value or by property name. These parameters are
     designed to take input from the pipeline easily.

INVESTIGATING PIPELINE ERRORS

     If a command fails because of a pipeline error, you can investigate the failure and
     rewrite the command.

     For example, the following command tries to move a Registry entry from one
     Registry key to another by using the Get-Item cmdlet to get the destination path and
     then piping the path to the Move-ItemProperty cmdlet.

     Specifically, the command uses the Get-Item cmdlet to get the destination path. It uses
     a pipeline operator to send the result to the Move-ItemProperty cmdlet. The Move-ItemProperty
     command specifies the current path and name of the Registry entry to be moved.

         Get-Item -path hklm:\software\mycompany\sales |
         Move-Itemproperty -path hklm:\software\mycompany\design -name product

     The command fails and Windows PowerShell displays the following error
     message:

         Move-ItemProperty : The input object cannot be bound to any parameters for the
         command either because the command does not take pipeline input or the input
         and its properties do not match any of the parameters that take pipeline input.
         At line:1 char:23
         + $a | Move-Itemproperty <<<< -path hklm:\software\mycompany\design -name product

    To investigate, use the Trace-Command cmdlet to trace the Parameter Binding component of
    Windows PowerShell. The following command traces the Parameter Binding component while the
    command is processing. It uses the -pshost parameter to display the results at the console
    and the -filepath command to send them to the debug.txt file for later reference.

         Trace-Command -name parameterbinding -expression {Get-Item -path hklm:\software\mycompany\sales |
             Move-Itemproperty -path hklm:\software\mycompany\design -name product} -pshost -filepath debug.txt

    The results of the trace are lengthy, but they show the values being bound to the Get-Item cmdlet
    and then the named values being bound to the Move-ItemProperty cmdlet.

     …
        BIND NAMED cmd line args [Move-ItemProperty]
            BIND arg [hklm:\software\mycompany\design] to parameter [Path]
        …
            BIND arg [product] to parameter [Name]
        ….
        BIND POSITIONAL cmd line args [Move-ItemProperty]
        …

    Finally, it shows that the attempt to bind the path to the Destination parameter
    of Move-ItemProperty failed.
        …
        BIND PIPELINE object to parameters: [Move-ItemProperty]
            PIPELINE object TYPE = [Microsoft.Win32.RegistryKey]
            RESTORING pipeline parameter’s original values
            Parameter [Destination] PIPELINE INPUT ValueFromPipelineByPropertyName NO COERCION
            Parameter [Credential] PIPELINE INPUT ValueFromPipelineByPropertyName NO COERCION
        …

     To investigate the failure, use the Get-Help cmdlet to view the attributes of the
     Destination parameter. The following command gets detailed information about the
     Destination parameter.

    Get-Help Move-Itemproperty -parameter destination

     The results show that Destination takes pipeline input only “by property name”.
     That is, the piped object must have a property named Destination.

        -destination <string>
            Specifies the path to the destination location.

            Required?                    true
            Position?                    2
            Default value
            Accept pipeline input?     true (ByPropertyName)
            Accept wildcard characters? true

     To see the properties of the object being piped to the Move-ItemProperty cmdlet,
     pipe it to the Get-Member cmdlet. The following command pipes the results of the
     first part of the command to the Get-Member cmdlet.

         Get-Item -path hklm:\software\mycompany\sales | Get-Member

     The output shows that the item is a Microsoft.Win32.RegistryKey that does not
     have a Destination property. That explains why the command failed.

     To fix the command, we must specify the destination in the Move-ItemProperty cmdlet. We can
     use a Get-ItemProperty command to get the path, but the name and destination must be specified
     in the Move-ItemProperty part of the command.

         Get-Item -path hklm:\software\mycompany\design |
             Move-Itemproperty -dest hklm:\software\mycompany\design -name product

     To verify that the command worked, use a Get-ItemProperty command:

    Get-Itemproperty hklm:\software\mycompany\sales

     The results show that the Product Registry entry was moved to the Sales key.

        PSPath     : Microsoft.PowerShell.Core\Registry::HKEY_LOCAL_MACHINE\software\mycompany\sales
        PSParentPath : Microsoft.PowerShell.Core\Registry::HKEY_LOCAL_MACHINE\software\mycompany
        PSChildName : sales
        PSDrive     : HKLM
        PSProvider : Microsoft.PowerShell.Core\Registry
        Product     : 18

SEE ALSO
    about_objects
    about_parameters
    about_Command_Syntax
    about_Foreach

about_Path_Syntax

TOPIC
    about_Path_Syntax

SHORT DESCRIPTION
    Describes the full and relative path name formats in Windows PowerShell.

LONG DESCRIPTION
    All items in a data store accessible through a Windows PowerShell provider
    can be uniquely identified by their path names. A path name is a
    combination of the item name, the container and subcontainers in which
    the item is located, and the Windows PowerShell drive through which the
    containers are accessed.

    In Windows PowerShell, path names are divided into one of two types: fully
    qualified and relative. A fully qualified path name consists of all
    elements that make up a path. The following syntax shows the elements in
    a fully qualified path name:

        [<provider>::]<drive>:[\<container>[\<subcontainer>…]]\<item>

    The <provider> placeholder refers to the Windows PowerShell provider
    through which you access the data store. For example, the FileSystem
    provider allows you to access the files and directories on your computer.
    This element of the syntax is optional and is never needed because the
    drive names are unique across all providers.

    The <drive> placeholder refers to the Windows PowerShell drive that is
    supported by a particular Windows PowerShell provider. In the case of the
    FileSystem provider, the Windows PowerShell drives map to the Windows
    drives that are configured on your system. For example, if your system
    includes an A: drive and a C: drive, the FileSystem provider creates the
    same drives in Windows PowerShell.

    After you have specified the drive, you must specify any containers and
    subcontainers that contain the item. The containers must be specified
    in the hierarchical order in which they exist in the data store. In
    other words, you must start with the parent container, then the child
    container in that parent container, and so on. In addition, each
    container must be preceded by a backslash. (Note that Windows PowerShell
    allows you to use forward slashes for compatibility with other
    powershells.)

    After the container and subcontainers have been specified, you must
    provide the item name, preceded by a backslash. For example, the fully
    qualified path name for the Shell.dll file in the C:\Windows\System32
    directory is as follows:

        C:\Windows\System32\Shell.dll

    In this case, the drive through which the containers are accessed is
    the C: drive, the top-level container is Windows, the subcontainer is
    System32 (located within the Windows container), and the item is Shell.dll.

    In some situations, you do not need to specify a fully qualified path
    name and can instead use a relative path name. A relative path name is
    based on the current working location. Windows PowerShell allows you to
    identify an item based on its location relative to the current working
    location. You can specify relative path names by using special characters.
    The following table describes each of these characters and provides
    examples of relative path names and fully qualified path names. The
    examples in the table are based on the current working directory being
    set to C:\Windows.

    Symbol Description                Relative path    Fully qualified path
    —— ————————– —————- ——————–
    .     Current working location .\System         c:\Windows\System
    ..     Parent of current working ..\Program Files c:\Program Files
         location
    \     Drive root of current     \Program Files c:\Program Files
         working location
    [none] No special characters     System         c:\Windows\System

    When using a path name in a command, you enter that name in the same
    way whether you use a fully qualified path name or a relative one. For
    example, suppose that your current working directory is C:\Windows. The
    following Get-ChildItem command retrieves all items in the C:\Techdocs
    directory:

        Get-ChildItem \techdocs

    The backslash indicates that the drive root of the current working
    location should be used. Because the working directory is C:\Windows,
    the drive root is the C: drive. Because the techdocs directory is located
    off the root, you need to specify only the backslash.

    You can achieve the same results by using the following command:

        Get-ChildItem c:\techdocs

    Regardless of whether you use a fully qualified path name or a relative
    path name, a path name is important not only because it locates an item
    but also because it uniquely identifies the item even if that item
    shares the same name as another item in a different container.

    For instance, suppose that you have two files that are each named
    Results.txt. The first file is in a directory named C:\Techdocs\Jan,
    and the second file is in a directory named C:\Techdocs\Feb. The path
    name for the first file (C:\Techdocs\Jan\Results.txt) and the path name
    for the second file (C:\Techdocs\Feb\Results.txt) allow you to clearly
    distinguish between the two files.

SEE ALSO
    about_locations

about_Parsing

TOPIC
    about_Parsing

SHORT DESCRIPTION
    Describes how Windows PowerShell parses commands.

LONG DESCRIPTION
    When you enter a command at the command prompt, Windows PowerShell
    breaks the command text into a series of segments called tokens
    and then determines how to interpret each one. For example, Windows
    PowerShell breaks the following command into two tokens, “Write-Host
    and “book”, and interprets each token separately:

        Write-Host book

    When processing a command, the Windows PowerShell parser operates
    in expression mode or in argument mode:

        – In expression mode, character string values must be contained in
         quotation marks. Numbers not enclosed in quotation marks are treated
         as numerical values (rather than as a series of characters).

        – In argument mode, each value is treated as an expandable string
         unless it begins with one of the following special characters: dollar
         sign ($), at sign (@), single quotation mark (‘), double quotation
         mark (“), or an opening parenthesis (().

    If preceded by one of these characters, the value is treated as a value
    expression.

    The following table provides several examples of commands processed in
    expression mode and argument mode and the results produced by those
    commands.

    Example            Mode         Result
    —————— ———- —————-
    2+2                Expression 4 (integer)
    Write-Output 2+2 Argument     “2+2” (string)
    Write-Output (2+2) Expression 4 (integer)
    $a = 2+2         Expression $a = 4 (integer)
    Write-Output $a    Expression 4 (integer)
    Write-Output $a/H Argument     “4/H” (string)

    Every token can be interpreted as some kind of object type, such
    as Boolean or string. Windows PowerShell attempts to determine the
    object type from the expression. The object type depends on the
    type of parameter a command expects and on whether Windows PowerShell
    knows how to convert the argument to the correct type. The
    following table shows several examples of the types assigned to
    values returned by the expressions.

    Example            Mode         Result
    —————— ———- —————
    Write-Output !1    argument     “!1” (string)
    Write-Output (!1) expression False (Boolean)
    Write-Output (2) expression 2 (integer)

SEE ALSO
    about_Command_Syntax

about_parameters

TOPIC
    about_parameters

SHORT DESCRIPTION
    Describes how to work with cmdlet parameters in Windows PowerShell.

LONG DESCRIPTION
    Most Windows PowerShell cmdlets and Functions rely on parameters to allow
    users to select options or provide input. The parameters follow the cmdlet
    or Function name and typically have the following form:

        -<parameter_name> <parameter_value>

    The name of the parameter is preceded by a hyphen (-), which signals to
    Windows PowerShell that the word following the hyphen is a parameter and
    not a value being passed to the cmdlet or Function. Not all parameters
    require a value, and not all parameter names must be specified. In some
    cases, the parameter name is implied and does not need to be included in
    the command.

    The type of parameters and the requirements for those parameters vary by
    cmdlet and by Function from cmdlet to cmdlet. To find information about the
    parameters of a cmdlet, use the Get-Help cmdlet. For example, to find
    information about the parameters of the Get-ChildItem cmdlet, type:

        Get-Help Get-ChildItem

    To find information about the parameters of a Function, review the
    parameter definitions. Parameters are defined either after the Function
    name or inside the body of the Function, using the Param keyword. For more
    information, see about_functions.

    Some Functions also contain comment-based Help about parameters. Use the
    Get-Help cmdlet with these Functions. For more information, see the help
    topic for Get-Help and about_Comment_Based_Help.

    The Get-Help Cmdlet returns various details about the cmdlet or Function,
    including a description of the cmdlet or Function, the command syntax,
    information about the parameters, and examples showing how to use the
    cmdlet or Function.

    You can also use the Parameter parameter of the Get-Help cmdlet or Function
    to find information about a particular parameter. Or, you can use the
    wildcard character (*) with the Parameter parameter to find information
    about all the parameters of the cmdlet or Function. For example, the
    following command gets information about all the parameters of the
    Get-Member cmdlet or Function:

        Get-Help Get-Member -parameter *

    This information includes the details you need to know to use the
    parameter. For example, the Help topic for the Get-ChildItem cmdlet
    includes the following details about its Path parameter:

        -path <string[]>
            Specifies a path of one or more locations. Wildcard characters are
            permitted. The default location is the current directory (.).

        Required?                    false
        Position?                    1
        Default value                Current directory
        Accept pipeline input?     true (ByValue, ByPropertyName)
        Accept wildcard characters? true

    The parameter information includes the parameter syntax,
    a description of the parameter, and the parameter attributes.
    The following sections describe the parameter attributes.

Parameter Required?
    This setting indicates whether the parameter is mandatory, that
    is, whether all commands that use this cmdlet must include this
    parameter. When the value is “True” and the parameter is missing
    from the command, Windows PowerShell prompts you for a value for
    the parameter.

Parameter Position?
    This setting indicates whether you can supply a parameter’s value
    without preceding it with the parameter name. If set to “0” or “named,”
    a parameter name is required. This type of parameter is referred to as
    a named parameter. A named parameter can be listed in any position
    after the cmdlet name.

    If the “Parameter position?” setting is set to an integer other than 0,
    the parameter name is not required. This type of parameter is referred
    to as a positional parameter, and the number indicates the position
    in which the parameter must appear in relation to other positional
    parameters. If you include the parameter name for a positional
    parameter, the parameter can be listed in any position after the
    cmdlet name.

    For example, the Get-ChildItem cmdlet has Path and Exclude parameters.
    The “Parameter position?” setting for Path is 1, which means that it
    is a positional parameter. The “Parameter position?” setting for Exclude
    is 0, which means that it is a named parameter.

    This means that Path does not require the parameter name, but its
    parameter value must be the first or only unnamed parameter value
    in the command. However, because the Exclude parameter is a named
    parameter, you can place it in any position in the command.

    As a result of the “Parameter position?” settings for these two
    parameters, you can use any of the following commands:

        Get-ChildItem -path c:\techdocs -exclude *.ppt
        Get-ChildItem c:\techdocs -exclude *.ppt
        Get-ChildItem -exclude *.ppt -path c:\techdocs
        Get-ChildItem -exclude *.ppt c:\techdocs

    If you were to include another positional parameter without including
    the parameter name, that parameter would have to be placed in the order
    specified by the “Parameter position?” setting.

Parameter Type
    This setting specifies the Microsoft .NET Framework type of the parameter
    value. For example, if the type is Int32, the parameter value must be an
    integer. If the type is string, the parameter value must be a
    character string. If the string contains spaces, the value must be
    enclosed in quotation marks, or the spaces must be preceded by the
    escape character (`).

Default Value
    This setting specifies the value that the parameter will assume
    if no other value is provided. For example, the default value of
    the Path parameter is often the current directory. Required
    parameters never have a default value. For many optional parameters,
    there is no default because the parameter has no effect if it is
    not used.

Accepts Multiple Values?
    This setting indicates whether a parameter accepts multiple
    parameter values. When a parameter accepts multiple values,
    you can type a comma-separated list as the value of the parameter
    in the command, or save a comma-separated list (an array) in a
    Variable, and then specify the Variable as the parameter value.

    For example, the ServiceName parameter of the Get-Service
    cmdlet accepts multiple values. The following commands are both valid:

        Get-Service -servicename winrm, netlogon

        $s = “winrm”, “netlogon”
        Get-Service -servicename $s

Accepts Pipeline Input?
    This setting indicates whether you can use the pipeline operator
    (|) to send a value to the parameter.

    Value                    Description
    —–                    ———–
    False                    Indicates that you cannot pipe a value to the
                             parameter.

    True (by Value)         Indicates that you can pipe any value to the
                             parameter, just so the value has the .NET
                             Framework type specified for the parameter or the
                             value can be converted to the specified .NET
                             Framework type.

                             When a parameter is “True (by Value)”, Windows
                             PowerShell tries to associate any piped values
                             with that parameter before it tries other methods
                             to interpret the command.

    True (by Property Name) Indicates that you can pipe a value to the
                             parameter, but the .NET Framework type of the
                             parameter must include a property with the same
                             name as the parameter.

                             For example, you can pipe a value to a Name
                             parameter only when the value has a property
                             called “Name”.

Accepts Wildcard Characters?
    This setting indicates whether the parameter’s value can contain
    wildcard characters so that the parameter value can be matched to more
    than one existing item in the target container.

Common Parameters
    Common parameters are parameters that you can use with any cmdlet.
    For more information, about common parameters, type:

        help about_CommonParameters

SEE ALSO
    about_Command_Syntax
    about_Comment_Based_Help
    about_functions_advanced
    about_pipelines
    about_wildcards

about_operators

TOPIC
    about_operators

SHORT DESCRIPTION
    Describes the operators that are supported by Windows PowerShell.

LONG DESCRIPTION
    An operator is a language element that you can use in a command or
    expression. Windows PowerShell supports several types of operators to
    help you manipulate values.

Arithmetic Operators
     Use arithmetic operators (+, -, *, /, %) to calculate values in a command
     or expression. With these operators, you can add, subtract, multiply, or
     divide values, and calculate the remainder (modulus) of a division
     operation.

     You can also use arithmetic operators with strings, arrays, and hash
     tables. The addition operator concatenates elements. The multiplication
     operator returns the specified number of copies of each element.

     For more information, see about_Arithmetic_Operators.

Assignment Operators
     Use assignment operators (=, +=, -=, *=, /=, %=) to assign one or more
     values to Variables, to change the values in a Variable, and to append
     values to Variables. You can also cast the Variable as any Microsoft .NET
     Framework data type, such as string or DateTime, or Process Variable.

     For more information, see about_Assignment_Operators.

Comparison Operators
     Use comparison operators (-eq, -ne, -gt, -lt, -le, -ge) to compare values
     and test conditions. For example, you can compare two string values to
     determine whether they are equal.

     The comparison operators include the match operators (-match, -notmatch)
     to find patterns using regular expressions; the replace operator
     (-replace), which uses regular expressions to change input values; and
     the like operators (-like, -notlike), which find patterns using wildcard
     characters (*).

     They also include the bitwise operators (-bAND, -bOR, -bXOR, -bNOT) to
     manipulate the bit patterns in values.

    For more information, see about_Comparison_Operators

Logical Operators
     Use logical operators (-and, -or, -xor, -not, !) to connect conditional
     statements into a single complex conditional. For example, you can use a
     logical -and operator to create an object filter with two different
     conditions.

     For more information, see about_logical_operators.

Redirection Operators
     Use redirection operators (>, >>, 2>, 2>, and 2>&1) to send the output of
     a command or expression to a text file. The redirection operators work
     like the Out-File cmdlet (without parameters) but they also let you
     redirect error output to specified files. You can also use the Tee-Object
     cmdlet to redirect output.

     For more information, see about_Redirection.

Split and Join Operators
     The -split and -join operators divide and combine substrings. The -split
     operator splits a string into substrings. The -join operator concatenates
     multiple strings into a single string.

     For more information, see about_split and about_join.

Type Operators
     Use the type operators (-is, -isnot, -as) to find or change the .NET
     Framework type of an object.

     For more information, see about_type_operators.

Unary Operators
     Use unary operators to increment or decrement Variables or object
     properties and to set integers to positive or negative numbers. For
     example, to increment the Variable $a from 9 to 10, you type $a++.

Special Operators
     Use special operators to perform tasks that cannot be performed by the
     other types of operators. For example, special operators allow you to
     perform operations such as running commands and changing a value’s data
     type.

     & Call operator
        Description: Runs a command, script, or script block. Because the call
        operator does not parse, it cannot interpret command parameters. The
        call operator, also known as the “invocation operator, indicates that
        the value it precedes is a command. This enables you to run commands
        stored in Variables and represented by strings. Examples:

            & “new cmdlet”
            $c = “Get-ExecutionPolicy
            & $c

     . Property dereference operator
        Description: Accesses the properties and methods of an object.
        Examples:

            $myString.length
            $myString.substring(1,3)

     . dot sourcing operator
        Description: Runs a script so that the items in the script are part
        of the calling scope. For more information, see about_Scopes/”>about_Scope. Example:

            . c:\scripts.sample.ps1

        Note: The dot (.) symbol is also used as the parent directory symbol,
             as in this example:

                .\sample.ps1

             This command runs the sample.ps1 script, but not as part of the
             calling scope.

     :: Static member operator
        Description: Calls the static properties operator and methods of a .NET
        Framework class. To find the static properties and methods of an
        object, use the Static parameter of the Get-Member cmdlet. Example:

            [datetime]::now

     .. Range operator
        Description: Represents the sequential integers in an integer array,
        given an upper and lower boundary. Examples:

            1..10
            10..1
            foreach ($a in 1..$max) {Write-Host $a}

     -f Format operator
        Description: Formats strings by using the format method of string
        objects. Enter the format string on the left side of the operator
        and the objects to be formatted on the right side of the operator.
        Examples:

            C:\PS> “{0} {1,-10} {2:N}” -f
            C:\PS> 1,”hello”,[math]::pi
            1 hello 3.14

     $( ) Subexpression operator
        Description: Returns the result of one or more statements. For a
        single result, returns a scalar. For multiple results, returns an
        array. Examples:

            $($x * 23)
            $(Get-WmiObject win32_Directory)

     @( ) Array subexpression operator
        Description: Returns the result of one or more statements as an array.
        If there is only one item, the array has only one member. Example:

            @(Get-WmiObject win32_logicalDisk)

     , operator
        Description: As a binary operator, the comma creates an array. As a
        unary operator, the comma creates an array with one member. Place the
        comma before the member. Examples:

            $myArray = 1,2,3
            $SingleArray = ,1

SEE ALSO
    about_Arithmetic_Operators
    about_Assignment_Operators
    about_Comparison_Operators
    about_logical_operators
    about_type_operators
    about_split
    about_join
    about_Redirection

about_objects

TOPIC
    about_objects

SHORT DESCRIPTION
    Provides essential information about objects in Windows PowerShell.

LONG DESCRIPTION
    Every action you take in Windows PowerShell occurs within the context of
    objects. As data moves from one command to the next, it moves as one or
    more identifiable objects. An object, then, is a collection of data that
    represents an item in a namespace. An object is made up of three types
    of data: the object’s type, its methods, and its properties.

    The data about an object’s type provides details about what kind of
    object it is. For example, an object that represents a file is a
    FileInfo object.

    An object’s method is an action that you can perform on the item that
    the object represents. For instance, a FileInfo object includes a
    method that you can use to cause the file to be copied. That is, when
    you invoke the copy method of the object, the file that the object
    represents is copied.

    An object’s property is information about the state of that object. For
    example, a FileInfo object includes the length property, which
    specifies the size of the file represented by the object.

    When working with objects, you can use their methods and properties in
    your commands to take specific actions and manipulate data. This is
    especially useful when you combine multiple commands into a single
    pipeline.

    When commands are combined in a pipeline, they pass information to each
    other as objects. When the first command runs, it sends one or more
    objects down the pipeline to the second command. The second command
    receives the objects from the first command, processes the objects, and
    then passes new or revised objects to the next command in the pipeline.
    This continues until all commands in the pipeline run.

    The following example demonstrates how objects are passed from one
    command to the next:

        Get-ChildItem c: | where {$_.PsIsContainer -eq $false} |
        Format-List

    The first command (Get-ChildItem c:) returns an object for each item in
    the root directory of the file system. Those objects are passed down
    the pipeline to the second command (where {$_.PsIsContainer -eq
    $false}). The second command uses the PsIsContainer property of the
    object to filter the data from the input objects so that no directories
    (containers) are returned. The command then passes the information as
    objects to the third command (Format-List), which displays the contents
    of each piped object in a list format.

SEE ALSO
    about_methods
    about_properties
    about_pipelines
    Get-Member

about_modules

TOPIC
    about_modules

SHORT DESCRIPTION
    Explains how to install, import, and use Windows PowerShell modules.

LONG DESCRIPTION
    A module is a package that contains Windows PowerShell commands, such as
    cmdlets, providers, Functions, Variables, and Aliases.

    People who write commands can use modules to organize their commands and
    share them with others. People who receive modules can add the commands
    in the modules to their Windows PowerShell sessions and use them just like
    the built-in commands.

    This topic explains how to use Windows PowerShell modules. For information
    about how to write Windows PowerShell modules, see “Writing a Windows
    PowerShell Module” in the MSDN (Microsoft Developer Network) library
    at http://go.microsoft.com/fwlink/?LinkId=144916.

HOW TO USE A MODULE
    To use a module, perform the following tasks:

        1. Install the module. (This is often done for you.)
        2. Import the module into your Windows PowerShell session.
        3. Find the commands that the module added.
        4. Use the commands that the module added.

    This topic explains how to perform these tasks. It also includes
    other useful information about managing modules.

HOW TO INSTALL A MODULE
    If you receive a module as a folder with files in it, you need
    to install it on your computer before you can import it into Windows
    PowerShell.

    Most modules are installed for you. Windows PowerShell comes with
    several pre-installed modules. In Windows Server 2008 R2, the
    Add Features Wizard in Server Manager automatically installs the
    feature modules that you select. Many other modules come in an
    installer or Setup program that installs the module.

    To install a module folder:

        1. Create a Modules directory for the current user if one does
         not exist.

         To create a Modules directory, type:

             New-Item -type directory -path $home\Documents\WindowsPowerShell\Modules

        2. Copy the entire module folder into the Modules directory.

         You can use any method to copy the folder, including Windows
         Explorer and Cmd.exe, as well as Windows PowerShell.

         In Windows PowerShell use the Copy-Item cmdlet. For example, to copy the
         MyModule folder from C:\ps-test\MyModule to the Modules directory, type:

             Copy-Item -path c:\ps-test\MyModule -dest $home\Documents\WindowsPowerShell\Modules

    You can install a module in any location, but installing your modules in a
    default module location makes them easier to manage. For more information about
    the default module locations, see the “Module Locations and PSModulePath” section.

HOW TO FIND INSTALLED MODULEs
     When a module is installed, you can import it into your Windows
     PowerShell session.

     To find modules that are installed in a default module location,
     at the Windows PowerShell prompt, type:

         Get-Module -listAvailable

     To find the modules that have already been imported into your session,
     at the Windows PowerShell prompt, type:

         Get-Module

     For more information about the Get-Module cmdlet, see Get-Module.

HOW TO IMPORT A MODULE
    To use the commands in a module, import the module into a
    Windows PowerShell session.

    To import modules from a default module location into the
    current session, use the following command format.

        Import-Module <module-name>

    For example, the following command imports the BitsTransfer module
    into the current session.

        Import-Module BitsTransfer

    To import a module that is not in a default module location, use
    the fully qualified path to the module folder in the command.

    For example, to add the TestCmdlets module in the C:\ps-test directory
    to your session, type:

        Import-Module c:\ps-test\TestCmdlets

    For more information about adding modules to your session, see
    Import-Module.

HOW TO IMPORT ALL MODULES INTO YOUR WINDOWS POWERSHELL SESSION
    In Windows 7 and Windows Server 2008 R2, the “Import all modules”
    task opens a Windows PowerShell session that includes all the
    available Windows PowerShell modules and snap-ins.

    To start a Windows PowerShell session with all the available Windows
    PowerShell modules and snap-ins, use the following procedure.

    — Right-click the Windows PowerShell icon in the taskbar, and then click
     “Import all modules”.

    Note: In Windows Server 2008 R2, the Windows PowerShell icon is pinned to
         the taskbar by default. However, you must start Windows PowerShell
         one time to make the “Import all modules” task appear.

    In other versions of Windows, to import all the available modules into your
    session, at the Windows PowerShell prompt, type:

        Get-Module -listAvailable | Import-Module

HOW TO FIND THE COMMANDS IN A MODULE
    After you import a module into your Windows PowerShell session, you can
    use the commands in the module.

    To find the commands that a module added, at the Windows PowerShell prompt,
    type:

        Get-Command -module <module-name>

    For example, to find the commands that the BitsTransfer module adds, type:

        Get-Command -module BitsTransfer

    For more information about the Get-Command cmdlet, see Get-Command.

HOW TO FIND HELP FOR THE COMMANDS IN A MODULE
    If the module contains Help topics for the commands that it exports,
    the Get-Help cmdlet will display the Help topics. Use the same command
    format that you would use for any Help topic in Windows PowerShell.

    To find the Help topic for the commands in a module, at the Windows
    PowerShell prompt, type:

        Get-Help <command-name>

    For more detailed Help, type:

        Get-Help <command-name> -detailed

    For example, to find detailed Help for the Start-BitsTransfer cmdlet,
    type:

        Get-Help Start-BitsTransfer -detailed

    For more information about the Get-Help module, see Get-Help.

HOW TO REMOVE A MODULE
    When you remove a module, the commands that the module added are deleted
    from the session.

    To remove a module from your session, use the following command
    format.

        Remove-Module <module-name>

    For example, the following command removes the BitsTransfer module
    from the current session.

        Remove-Module BitsTransfer

    Removing a module reverses the operation of importing a module. Removing
    a module does not uninstall the module. For more information about the
    Remove-Module cmdlet, see Remove-Module.

HOW TO IMPORT A MODULE INTO EVERY SESSION
    The Import-Module command imports modules into your current Windows
    PowerShell session. This command affects only the current session.

    To import a module into every Windows PowerShell session that you
    start, add the Import-Module command to your Windows PowerShell
    profile.

    For more information about profiles, see about_profiles.

MODULE LOCATIONS AND PSMODULEPATH
    There are two default locations for Windows PowerShell modules, one for
    the system and one for the current user.

        System:        $pshome\Modules
                         (%windir%\System32\WindowsPowerShell\v1.0\Modules)

        Current user: $home\Documents\WindowsPowerShell\Modules
                         (%UserProfile%\Documents\WindowsPowerShell\Modules)

                     – or –

                     $home\My Documents\WindowsPowerShell\Modules
                         (%UserProfile%\My Documents\WindowsPowerShell\Modules)

        Note: In Windows Vista, Windows Server 2008, and later versions of
             Windows, to add or change files in the %Windir%\System32 directory,
             start Windows PowerShell with the “Run as administrator” option.

    You can change the default module locations on your system by changing the
    value of the PSModulePath Environment Variable ($env:psmodulepath). The
    PSModulePath Environment Variable is modeled on the Path Environment Variable
    and has the same format.

    To view the default module locations, type:

        $env:psmodulepath

    To add a default module location, use the following command format.

        $env:psmodulepath = $env:psmodulepath + “;<path>”

    The semi-colon (;) in the command separates the new path from the
    path that precedes it in the list.

    For example, to add the “C:\ps-test\Modules” directory, type:

        $env:psmodulepath + “;c:\ps-test\Modules”

    When you add a path to PSModulePath, Get-Module and Import-Module
    commands include modules in that path.

    The value that you set affects only the current session. To make the
    change persistent, add the command to your Windows PowerShell profile
    or use the System item in Control Panel to change the value of the
    PSModulePath Environment Variable in the Registry.

    For more information about the PSModulePath Variable, see
    about_environment_variables.

MODULES AND NAME CONFLICTS
    Name conflicts occur when more than one command in the session
    has the same name. Importing a module causes a name conflict when
    commands in the module have the same names as commands or items
    in the session.

    Name conflicts can result in commands being hidden or replaced.

        — Hidden. A command is hidden when it is not the command
         that runs when you type the command name, but you can run it
         by using another method, such as by qualifying the command
         name with the name of the module or snap-in in which it
         originated.

        — Replaced. A command is replaced when you cannot run it because
         it has been overwritten by a command with the same name. Even
         when you remove the module that caused the conflict, you cannot
         run a replaced command unless you restart the session.

    Import-Module might add commands that hide and replace commands in the
    current session. Also, commands in your session can hide commands that
    the module added.

    To prevent name conflicts, use the Prefix parameter of Import-Command
    to create unique names for the imported commands.

    You can also use the Alias, Cmdlet, Function, and Variable parameters
    of Import-Module to select only the commands that you want to import,
    and you can exclude commands that cause name conflicts in your session.

    Even if a command is hidden, you can run it by qualifying the command
    name with the name of the module or snap-in in which it originated.

    The Windows PowerShell command precedence rules determine which command
    runs when the session includes commands with the same name.

    For example, when a session includes a Function and a cmdlet with the same
    name, Windows PowerShell runs the Function by default. When the session
    includes commands of the same type with the same name, such as two cmdlets
    with the same name, by default, it runs the most recently added command.

    For more information, including an explanation of the precedence rules and
    instructions for running hidden commands, see about_command_precedence.

MODULES AND SNAP-INS
    You can add commands to your session from modules and snap-ins. Modules
    can add all types of commands, including cmdlets, providers, and Functions,
    and items, such as Variables, Aliases, and Windows PowerShell drives.
    Snap-ins can add only cmdlets and providers.

    In fact, although you can add Functions, Aliases, Variables, and drives
    to your session by typing them or running a script that adds them, all
    the cmdlets and providers in your session come from a module or a snap-in.

    Before removing a module or snap-in from your session, use the following
    commands to determine which commands will be removed.

    To find the source of a cmdlet in your session, use the following command
    format:

        Get-Command <cmdlet-name> | Format-List -property verb, noun, pssnapin, module

    For example, to find the source of the Get-Date cmdlet, type:

        Get-Command Get-Date | Format-List -property verb, noun, pssnapin, module

    For more information about Windows PowerShell snap-ins, see about_PSSnapins.

SEE ALSO
    about_command_precedence
    about_PSSnapins
    Get-Command
    Get-Help
    Get-Module
    Import-Module
    Remove-Module

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