All posts by Adam

about_regular_expressions

TOPIC
    about_regular_expressions

SHORT DESCRIPTION
    Describes regular expressions in Windows PowerShell.

LONG DESCRIPTION
    Windows PowerShell supports the following regular expression characters.

        Format Logic                            Example
        ——– ——————————- ———————–
        value    Matches exact characters         “book” -match “oo”
                 anywhere in the original value.

        .        Matches any single character.    “copy” -match “c..y”

        [value] Matches at least one of the     “big” -match “b[iou]g”
                 characters in the brackets.

        [range] Matches at least one of the     “and” -match “[a-e]nd”
                 characters within the range.
                 The use of a hyphen (–) allows
                 you to specify an adjacent
                 character.

        [^]     Matches any characters except    “and” -match “[^brt]nd”
                 those in brackets.

        ^        Matches the beginning            “book” -match “^bo”
                 characters.

        $        Matches the end characters.     “book” -match “ok$”

        *        Matches any instances            “baggy” -match “g*”
                 of the preceding character.

        ?        Matches one instance             “baggy” -match “g?”
                 of the preceding character.

        \        Matches the character that     “Try$” -match “Try\$”
                 follows as an escaped character.

    Windows PowerShell supports the character classes available in
    Microsoft .NET Framework regular expressions.

        Format Logic                            Example
        ——– ——————————- ———————–
        \p{name} Matches any character in the     “abcd defg” -match “\p{Ll}+”
                 named character class specified
                 by {name}. Supported names are
                 Unicode groups and block
                 ranges such as Ll, Nd,
                 Z, IsGreek, and IsBoxDrawing.

        \P{name} Matches text not included in     1234 -match “\P{Ll}+”
                 the groups and block ranges
                 specified in {name}.

        \w     Matches any word character.     “abcd defg” -match “\w+”
                 Equivalent to the Unicode        (this matches abcd)
                 character categories [\p{Ll}
                 \p{Lu}\p{Lt}\p{Lo}\p{Nd}\p{Pc}].
                 If ECMAScript-compliant behavior
                 is specified with the ECMAScript
                 option, \w is equivalent to
                 [a-zA-Z_0-9].

        \W     Matches any nonword character. “abcd defg” -match “\W+”
                 Equivalent to the Unicode        (This matches the space)
                 categories [^\p{Ll}\p{Lu}\p{Lt}
                 \p{Lo}\p{Nd}\p{Pc}].

        \s     Matches any white-space         “abcd defg” -match “\s+”
                 character. Equivalent to the
                 Unicode character categories
                 [\f\n\r\t\v\x85\p{Z}].

        \S     Matches any non-white-space     “abcd defg” -match “\S+”
                 character. Equivalent to the
                 Unicode character categories
                 [^\f\n\r\t\v\x85\p{Z}].

        \d     Matches any decimal digit.     12345 -match “\d+”
                 Equivalent to \p{Nd} for
                 Unicode and [0-9] for non-
                 Unicode behavior.

        \D     Matches any nondigit.            “abcd” -match “\D+”
                 Equivalent to \P{Nd} for
                 Unicode and [^0-9] for non-
                 Unicode behavior.

    Windows PowerShell supports the quantifiers available in .NET Framework
    regular expressions. The following are some examples of quantifiers.

        Format Logic                            Example
        ——– ——————————- ———————–
        *        Specifies zero or more matches; “abc” -match “\w*”
                 for example, \w* or (abc)*.
                 Equivalent to {0,}.

        +        Matches repeating instances of “xyxyxy” -match “xy+”
                 the preceding characters.

        ?        Specifies zero or one matches; “abc” -match “\w?”
                 for example, \w? or (abc)?.
                 Equivalent to {0,1}.

        {n}     Specifies exactly n matches;     “abc” -match “\w{2}”
                 for example, (pizza){2}.

        {n,}     Specifies at least n matches;    “abc” -match “\w{2,}”
                 for example, (abc){2,}.

        {n,m}    Specifies at least n, but no     “abc” -match “\w{2,3}”
                 more than m, matches.

    All the comparisons shown in the preceding table evaluate to true.

    Notice that the escape character for regular expressions, a backslash (\),
    is different from the escape character for Windows PowerShell. The
    escape character for Windows PowerShell is the backtick character (`)
    (ASCII 96).

    For more information, see the “Regular Expression Language Elements” topic
    in the Microsoft Developer Network (MSDN) library
    at http://go.microsoft.com/fwlink/?LinkId=133231.

SEE ALSO
    about_Comparison_Operators
    about_operators

about_Ref

TOPIC
    about_Ref

SHORT DESCRIPTION
    Describes how to create and use a reference Variable type.

LONG DESCRIPTION
    You can use the reference Variable type to permit a method to change the
    value of a Variable that is passed to it.

    When the [ref] type is associated with an object, it returns a reference
    to that object. If the reference is used with a method, the method can
    refer to the object that was passed to it. If the object is changed within
    the method, the change appears as a change in the value of the Variable
    when control returns to the calling method.

    To use referencing, the parameter must be a reference Variable. If it is
    not, an InvalidArgument exception is thrown.

    The parameters used in method invocations must match the type required
    by the methods.

    Examples:

        PS> Function swap([ref]$a,[ref]$b)
        >> {
        >>     $a.value,$b.value = $b.value,$a.value
        >> }

        PS> $a = 1
        PS> $b = 10
        PS> $a,$b
        1
        10
        PS> swap ([ref]$a) ([ref]$b)
        PS> $a,$b
        10
        1

        PS C:\ps-test> Function double
        >> {
        >>     param ([ref]$x) $x.value = $x.value * 2
        >> }

        PS C:> $number = 8
        PS C:> $number
        8
        PS C> double ([ref]$number)
        PS C> $number
        16

        The Variable must be a reference Variable.

        PS C:\ps-test> double $number
        double : Reference type is expected in argument.
        At line:1 char:7
        + double <<<< $number

SEE ALSO
    about_Variables
    about_environment_variables
    about_functions
    about_script_blocks

about_Redirection

TOPIC
    about_Redirection

SHORT DESCRIPTION
    Describes how to redirect output from Windows PowerShell to text files.

LONG DESCRIPTION
    By default, Windows PowerShell sends its command output to the Windows
    PowerShell console. However, you can direct the output to a text
    file, and you can redirect error output to the regular output stream.

    You can use the following methods to redirect output:

        – Use the Out-File cmdlet, which sends command output to a text file.
         Typically, you use the Out-File cmdlet when you need to use its
         parameters, such as the Encoding, Force, Width, or NoClobber
         parameters.

        – Use the Tee-Object cmdlet, which sends command output to a text file
         and then sends it to the pipeline.

        – Use the Windows PowerShell redirection operators.

     The Windows PowerShell redirection operators are as follows.

     Operator Description                Example
     ——– ———————-     ——————————
     >         Sends output to the        Get-Process > process.txt
                specified file.

     >>        Appends the output to     dir *.ps1 >> scripts.txt
                the contents of the
                specified file.

     2>        Sends errors to the        Get-Process none 2> errors.txt
                specified file.

     2>>     Appends the errors to     Get-Process none 2>> save-errors.txt
                the contents of the
                specified file.

     2>&1     Sends errors to the        Get-Process none, powershell 2>&1
                success output stream.

    The syntax of the redirection operators is as follows:

     <input> <operator> [<path>\]<file>

    If the specified file already exists, the redirection operators that do not
    append data (> and 2>) overwrite the current contents of the file without
    warning. However, if the file is a read-only, hidden, or system file, the
    redirection fails. The append redirection operators (>> and 2>>) do not
    write to a read-only file, but they append content to a system or hidden
    file.

    To force the redirection of content to a read-only, hidden, or system file,
    use the Out-File cmdlet with its Force parameter. When you are writing to
    files, the redirection operators use Unicode encoding. If the file has a
    different encoding, the output might not be formatted correctly. To
    redirect content to non-Unicode files, use the Out-File cmdlet with its
    Encoding parameter.

SEE ALSO
    Out-File
    Tee-Object
    about_operators
    about_Command_Syntax
    about_Path_Syntax

about_Quoting_Rules

TOPIC
    about_Quoting_Rules

SHORT DESCRIPTION
    Describes rules for using single and double quotation marks
    in Windows PowerShell.

LONG DESCRIPTION
    Quotation marks are used to specify a literal string. You can enclose a
    string in single quotation marks (‘) or double quotation marks (“).

    Quotation marks are also used to create a here-string. A here-string is a
    single-quoted or double-quoted string in which quotation marks are
    interpreted literally. A here-string can span multiple lines. All the
    lines in a here-string are interpreted as strings, even though they are
    not enclosed in quotation marks.

    In commands to remote computers, quotation marks define the parts of
    the command that are run on the remote computer. In a remote session,
    quotation marks also determine whether the Variables in a command are
    interpreted first on the local computer or on the remote computer.

Single and Double-Quoted Strings

     When you enclose a string in double quotation marks (a double-quoted
     string), Variable names that are preceded by a dollar sign ($) are
     replaced with the Variable‘s value before the string is passed to the
     command for processing.

     For example:

         $i = 5
         “The value of $i is $i.”

     The output of this command is:

         The value of 5 is 5.

     Also, in a double-quoted string, expressions are evaluated, and the
     result is inserted in the string. For example:

     “The value of $(2+3) is 5.”

     The output of this command is:

     The value of 5 is 5.

     When you enclose a string in single-quotation marks (a single-quoted
     string), the string is passed to the command exactly as you type it.
     No substitution is performed. For example:

         $i = 5
         ‘The value of $i is $i.’

     The output of this command is:

         The value $i is $i.

     Similarly, expressions in single-quoted strings are not evaluated. They
     are interpreted as literals. For example:

     ‘The value of $(2+3) is 5.’

     The output of this command is:

     The value of $(2+3) is 5.

     To prevent the substitution of a Variable value in a double-quoted
     string, use the backtick character (`)(ASCII 96), which is the
     Windows PowerShell escape character.

     In the following example, the backtick character that precedes the first
     $i Variable prevents Windows PowerShell from replacing the Variable name
     with its value. For example:

         $i = 5
         “The value of `$i is $i.”

     The output of this command is:

         The value $i is 5.

     To make double-quotation marks appear in a string, enclose the entire
     string in single quotation marks. For example:

         ‘As they say, “live and learn.”‘

     The output of this command is:

         As they say, “live and learn.”

     You can also enclose a single-quoted string in a double-quoted string.
     For example:

         “As they say, ‘live and learn.'”

     The output of this command is:

         As they say, ‘live and learn.’

     Or, double the quotation marks around a double-quoted phrase. For
     example:

         “As they say, “”live and learn.”””

     The output of this command is:

         As they say, “live and learn.”

     To include a single quotation mark in a single-quoted string, use a
     second consecutive single quote. For example:

         ‘don”t’

     The output of this command is:

         don’t

     To force Windows PowerShell to interpret a double quotation mark
     literally, use a backtick character. This prevents Windows PowerShell
     from interpreting the quotation mark as a string delimiter. For example:

         “Use a quotation mark (`”) to begin a string.”

     Because the contents of single-quoted strings are
     interpreted literally, you cannot use the backtick character to
     force a literal character interpretation in a single-quoted string.

     For example, the following command generates an error because Windows
     PowerShell does not recognize the escape character. Instead, it
     interprets the second quotation mark as the end of the string.

     PS C:\> ‘Use a quotation mark (`’) to begin a string.’
         Unexpected token ‘)’ in expression or statement.
         At line:1 char:27
         + ‘Use a quotation mark (`’) <<<< to begin a string.’

Single and Double-Quoted Here-Strings

     The quotation rules for here-strings are slightly different.

     A here-string is a single-quoted or double-quoted string in
     which quotation marks are interpreted literally. A here-string can
     span multiple lines. All the lines in a here-string are interpreted
     as strings even though they are not enclosed in quotation marks.

     Like regular strings, Variables are replaced by their values in
     double-quoted here-strings. In single-quoted here-strings, Variables
     are not replaced by their values.

     You can use here-strings for any text, but they are particularly
     useful for the following kinds of text:

         – Text that contains literal quotation marks
         – Multiple lines of text, such as the text in an HTML or XML document
         – The Help text for a script or Function

     A here-string can have either of the following formats, where <Enter>
     represents the linefeed or newline hidden character that is added when
     you press the ENTER key.

     Format 1:

     @”<Enter>
         <string> [string] …<Enter>
         “@

     Format 2:

     @'<Enter>
         <string> [string] …<Enter>
         ‘@

     In either format, the closing quotation mark must be the first character
     in the line.

     A here-string contains all the text between the two hidden characters.
     In the here-string, all quotation marks are interpreted literally.
     For example:

     @”
     For help, type “Get-Help
     “@

     The output of this command is:

     For help, type “Get-Help

     Using a here-string can simplify using a string in a command. For
     example:

     @”
         Use a quotation mark (‘) to begin a string.
         “@

     The output of this command is:

         Use a quotation mark (‘) to begin a string.

     In single-quoted here-strings, Variables are interpreted literally and
     reproduced exactly. For example:

         @’
     The $profile Variable contains the path
         of your Windows PowerShell profile.
         ‘@

     The output of this command is:

     The $profile Variable contains the path
         of your Windows PowerShell profile.

     In double-quoted here-strings, Variables are replaced by their values.
     For example:

     @”
         Even if you have not created a profile,
         the path of the profile file is:
         $profile.
         “@

     The output of this command is:

     Even if you have not created a profile,
     the path of the profile file is:
     C:\Users\User01\Documents\WindowsPowerShell\Microsoft.PowerShell_profile.ps1.

     Here-strings are typically used to assign multiple lines to
     a Variable. For example, the following here-string assigns a
     page of XML to the $page Variable.

        $page = [XML] @”
        <command:command xmlns:maml=”http://schemas.microsoft.com/maml/2004/10″
        xmlns:command=”http://schemas.microsoft.com/maml/dev/command/2004/10″
        xmlns:dev=”http://schemas.microsoft.com/maml/dev/2004/10″>
        <command:details>
                <command:name>
                     Format-Table
            </command:name>
            <maml:description>
            <maml:para>Formats the output as a table.</maml:para>
            </maml:description>
            <command:verb>format</command:verb>
            <command:noun>table</command:noun>
            <dev:version></dev:version>
        </command:details>
        …
        </command:command>
        “@

     Here-strings are also a convenient format for input to the
     ConvertFrom-StringData cmdlet, which converts here-strings to hash
     tables. For more information, see ConvertFrom-StringData.

SEE ALSO
    about_escape_characters
    ConvertFrom-StringData

about_PSSnapins

TOPIC
    about_PSSnapins

SHORT DESCRIPTION
    Describes Windows PowerShell snap-ins and shows how to use and manage them.

LONG DESCRIPTION
    A Windows PowerShell snap-in is a Microsoft .NET Framework assembly that
    contains Windows PowerShell providers and/or cmdlets. Windows PowerShell
    includes a set of basic snap-ins, but you can extend the power and value
    of Windows PowerShell by adding snap-ins that contain providers and cmdlets
    that you create or get from others.

    When you add a snap-in, the cmdlets and providers that it contains are
    immediately available for use in the current session, but the change
    affects only the current session.

    To add the snap-in to all future sessions, save it in your Windows
    PowerShell profile. You can also use the Export-Console cmdlet to save
    the snap-in names to a console file and then use it in future sessions.
    You can even save multiple console files, each with a different set of
    snap-ins.

BUILT-IN SNAP-INS
    Windows PowerShell includes a set of Windows PowerShell snap-ins that
    contain the built-in providers and cmdlets.

    Microsoft.PowerShell.Core
        Contains providers and cmdlets used to manage the basic features of
        Windows PowerShell. It includes the FileSystem, Registry, Alias,
        Environment, Function, and Variable providers and basic cmdlets like
        Get-Help, Get-Command, and Get-History.

    Microsoft.PowerShell.Host
     Contains cmdlets used by the Windows PowerShell host, such as
     Start-Transcript and Stop-Transcript.

    Microsoft.PowerShell.Management
        Contains cmdlets such as Get-Service and Get-ChildItem that are used to
        manage Windows-based features.

    Microsoft.PowerShell.Security
        Contains cmdlets used to manage Windows PowerShell security, such as
        Get-Acl, Get-AuthenticodeSignature, and ConvertTo-SecureString.

    Microsoft.PowerShell.Utility
        Contains cmdlets used to manipulate objects and data, such as
        Get-Member, Write-Host, and Format-List.

FINDING SNAP-INS
    To get a list of the Windows PowerShell snap-ins on your computer, type:

    Get-PSSnapin

    To get the snap-in for each Windows PowerShell provider, type:

        Get-PSProvider | Format-List name, pssnapin

    To get a list of the cmdlets in a Windows PowerShell snap-in, type:

        Get-Command -module <snap-in_name>

INSTALLING A SNAP-IN
    The built-in snap-ins are registered in the system and added to the
    default session when you start Windows PowerShell. However, you have to
    register snap-ins that you create or obtain from others and then add the
    snap-ins to your session.

REGISTERING A SNAP-IN
    A Windows PowerShell snap-in is a program written in a .NET Framework
    language that is compiled into a .dll file. To use the providers and
    cmdlets in a snap-in, you must first register the snap-in (add it to the
    Registry).

    Most snap-ins include an installation program (an .exe or .msi file)
    that registers the .dll file for you. However, if you receive a snap-in as
    a .dll file, you can register it on your system. For more information, see
    “How to Register Cmdlets, Providers, and Host Applications” in the MSDN
    (Microsoft Developer Network) library at
    http://go.microsoft.com/fwlink/?LinkID=143619.

    To get all the registered snap-ins on your system or to verify that a
    snap-in is registered, type:

    Get-PSSnapin -registered

ADDING THE SNAP-IN TO THE CURRENT SESSION
    To add a registered snap-in to the current session, use the Add-PSSnapin
    cmdlet. For example, to add the Microsoft SQL Server snap-in to the
    session, type:

    Add-PSSnapin sql

    After the command is completed, the providers and cmdlets in the snap-in
    are available in the session. However, they are available only in the
    current session unless you save them.

SAVING THE SNAP-INS
    To use a snap-in in future Windows PowerShell sessions, add the
    Add-PSSnapin command to your Windows PowerShell profile. Or, export
    the snap-in names to a console file.

    If you add the Add-PSSnapin command to your profile, it is available
    in all future Windows PowerShell sessions. If you export the names of
    the snap-ins in your session, you can use the export file only when you
    need the snap-ins.

    To add the Add-PSSnapin command to your Windows PowerShell profile,
    open your profile, paste or type the command, and then save the profile.
    For more information, see about_profiles.

    To save the snap-ins from a session in console file (.psc1), use
    the Export-Console cmdlet. For example, to save the snap-ins in
    the current session configuration to the NewConsole.psc1 file in the
    current directory, type:

    Export-Console NewConsole

    For more information, see Export-Console.

OPENING WINDOWS POWERSHELL WITH A CONSOLE FILE
    To use a console file that includes the snap-in, start Windows PowerShell
    (Powershell.exe) from the command prompt in Cmd.exe or in another
    Windows PowerShell session. Use the PsConsoleFile parameter to specify
    the console file that includes the snap-in. For example, the following
    command starts Windows PowerShell with the NewConsole.psc1 console file:

    powershell.exe -psconsolefile NewConsole.psc1

    The providers and cmdlets in the snapin are now available for use in
    the session.

REMOVING A SNAP-IN
    To remove a Windows PowerShell snap-in from the current session, use the
    Remove-PSSnapin cmdlet. For example, to remove the SQL Server
    snap-in from the current session, type:

    Remove-PSSnapin sql

    This cmdlet removes the snap-in from the session. The snap-in is still
    loaded, but the providers and cmdlets that it supports are no longer
    available.

SEE ALSO
    Add-PSSnapin
    Get-PSSnapin
    Remove-PSSnapin
    Export-Console
    Get-Command
    about_profiles

about_pssession_details

TOPIC
    about_pssession_details

SHORT DESCRIPTION
    Provides detailed information about Windows PowerShell sessions and the
    role they play in remote commands.

LONG DESCRIPTION
    A session is an Environment in which Windows PowerShell runs. A session is
    created for you whenever you start Windows PowerShell. You can create
    additional sessions, called “Windows PowerShell sessions” or “PSSessions”
    on your computer or another computer.

    Unlike the sessions that Windows PowerShell creates for you, you control
    and manage the PSSessions that you create.

    PSSessions play an important role in remote computing. When you create a
    PSSession that is connected to a remote computer, Windows PowerShell
    establishes a persistent connection to the remote computer to support the
    PSSession. You can use the PSSession to run a series of commands,
    Functions, and scripts that share data.

    This topic provides detailed information about sessions and PSSessions
    in Windows PowerShell. For basic information about the tasks that you
    can perform with sessions, see about_pssessions.

ABOUT SESSIONS

    Technically, a session is an execution Environment in which Windows
    PowerShell runs. Each session includes an instance of the
    System.Management.Automation engine and a host program in which Windows
    PowerShell runs. The host can be the familiar Windows PowerShell console
    or another program that runs commands, such as Cmd.exe, or a program built
    to host Windows PowerShell, such as Windows PowerShell Integrated Scripting
    Environment (ISE). From a Windows perspective, a session is a Windows
    process on the target computer.

    Each session is configured independently. It includes its own properties,
    its own execution policy, and its own profiles. The Environment that exists
    when the session is created persists for its lifetime even if you change
    the Environment on the computer. All sessions are created in a global
    scope, even sessions that you create in a script.

    You can run only one command (or command pipeline) in a session at one
    time. A second command run synchronously (one at a time) waits up to four
    minutes for the first command to be completed. A second command run
    asynchronously (concurrently) fails.

ABOUT PSSESSIONS

    A session is created each time that you start Windows PowerShell. And,
    Windows PowerShell creates temporary sessions to run individual commands.
    However, you can also create sessions (called “Windows PowerShell sessions”
    or “PSSessions”) that you control and manage.

    PSSessions are critical to remote commands. If you use the ComputerName
    parameter of the Invoke-Command or Enter-PSSession cmdlets, Windows
    PowerShell establishes a temporary session to run the command and then
    closes the session as soon as the command or the interactive session
    is complete.

    However, if you use the New-PSSession cmdlet to create a PSSession, Windows
    PowerShell establishes a persistent session on the remote computer in which
    you can run multiple commands or interactive sessions. The PSSessions that
    you create remain open and available for use until you delete them or until
    you close the session in which they were created.

    When you create a PSSession on a remote computer, the system creates a
    PowerShell process on the remote computer and establishes a connection
    from the local computer to the process on the remote computer. When you
    create a PSSession on the local computer, both the new process and the
    connections are created on the local computer.

WHEN DO I NEED A PSSESSION?

    The Invoke-Command and Enter-PSSession cmdlets have both ComputerName and
    Session parameters. You can use either to run a remote command.

    Use the ComputerName parameter to run a single command or a series of
    unrelated commands on one or many computers.

    To run commands that share data, you need a persistent connection to the
    remote computer. In that case, create a PSSession, and then use the Session
    parameter to run commands in the PSSession.

    Many other cmdlets that get data from remote computers, such as
    Get-Process, Get-Service, Get-EventLog, and Get-WmiObject have only a
    ComputerName parameter. They use technologies other than Windows PowerShell
    remoting to gather data remotely. These cmdlets do not have a Session
    parameter, but you can use the Invoke-Command cmdlet to run these commands
    in a PSSession.

HOW DO I CREATE A PSSESSION?

    To create a PSSession, use the New-PSSession cmdlet. You can use
    New-PSSession to create a PSSession on a local or remote computer.

CAN I CREATE A PSSESSION ON ANY COMPUTER?

    To create a PSSession that is connected to a remote computer, the computer
    must be configured for remoting in Windows PowerShell. The current user
    must be a member of the Administrators group on the remote computer, or
    the current user must be able to supply the credentials of a member of
    the Administrators group. For more information,
    see about_remote_requirements.

CAN I SEE THE PSSESSIONS THAT OTHERS HAVE CREATED ON MY COMPUTER?

    No. You can get and manage only the PSSessions that you have created in the
    current session. You cannot see PSSessions that others have created, even
    if they run commands on the local computer.

CAN I RUN A BACKGROUND JOB IN A PSSESSION?

    Yes. A background job is a command that runs asynchronously in the
    background without interacting with the current session. When you submit
    a command to start a job, the command returns a job object, but the job
    continues to run in the background until it is complete.

    To start a background job on a local computer, use the Start-Job command.
    You can run the background job in a temporary connection (by using the
    ComputerName parameter) or in a PSSession (by using the Session parameter).

    To start a background job on a remote computer, use the Invoke-Command
    cmdlet with its AsJob parameter, or use the Invoke-Command cmdlet to run a
    Start-Job command on a remote computer. When using the AsJob parameter,
    you can use the ComputerName or Session parameters.

    When using Invoke-Command to run a Start-Job command, you must run the
    command in a PSSession. If you use the ComputerName parameter, Windows
    PowerShell ends the connection when the job object returns, and the job is
    interrupted.

    For more information, see about_jobs.

CAN I RUN AN INTERACTIVE SESSION?

    Yes. To start an interactive session with a remote computer, use the
    Enter-PSSession cmdlet. In an interactive session, the commands that you
    type run on the remote computer, just as if you typed them directly on the
    remote computer.

    You can run an interactive session in a temporary session (by using the
    ComputerName parameter) or in a PSSession (by using the Session parameter).
    If you use a PSSession, the PSSession retains the data from previous
    commands, and the PSSession retains any data generated during the
    interactive session for use in later commands.

    When you end the interactive session, the PSSession remains open and
    available for use.

    For more information, see Enter-PSSession and Exit-PSSession.

MUST I DELETE THE PSSESSIONS?

    Yes. A PSSession is a process, which is a self-contained Environment that
    uses memory and other resources even when you are not using it. When you are
    finished with a PSSession, delete it. If you create multiple PSSessions,
    close the ones that you are not using, and maintain only the ones currently
    in use.

    To delete PSSessions, use the Remove-PSSession cmdlet. It deletes the
    PSSessions and releases all of the resources that they were using.

    You can also use the TimeOut parameter of New-PSSession to close an idle
    PSSession after an interval that you specify. For more information,
    see New-PSSession.

    If you do not delete the PSSession or set a time-out, the PSSession remains
    open and available for use until you close it, until you close the session
    in which it was created, or until you exit Windows PowerShell. However, a
    PSSession on a remote computer will be disconnected if the remote computer
    does not respond for four minutes. (The remote computer is configured to
    send a heartbeat pulse every three minutes.)

    If you save a PSSession object in a Variable and then delete the PSSession
    or let it time out, the Variable still contains the PSSession object, but
    the PSSession is not active and cannot be used or repaired.

ARE ALL SESSIONS AND PSSESSIONS ALIKE?

    No. Developers can create custom sessions that include only selected
    providers and cmdlets. If a command works in one session but not in
    another, it might be because the session is restricted.

SEE ALSO
    about_jobs
    about_pssessions
    about_remote
    about_remote_requirements
    Invoke-Command
    New-PSSession
    Get-PSSession
    Remove-PSSession
    Enter-PSSession
    Exit-PSSession

about_pssessions

TOPIC
    about_pssessions

SHORT DESCRIPTION
    Describes Windows PowerShell sessions (PSSessions) and explains how to
    establish a persistent connection to a remote computer.

LONG DESCRIPTION
    To run Windows PowerShell commands on a remote computer, you can use the
    ComputerName parameter of a cmdlet, or you can create a Windows PowerShell
    session (PSSession) and run commands in the PSSession.

    When you create a PSSession, Windows PowerShell establishes a persistent
    connection to the remote computer. Use a PSSession to run a series of
    related commands on a remote computer. Commands that run in the same
    PSSession can share data, such as the values of Variables, Aliases, and
    Functions.

    You can also create a PSSession on the local computer and run commands
    in it. A local PSSession uses the Windows PowerShell remoting
    infrastructure to create and maintain the PSSession.

    This topic explains how to create, use, get, and delete PSSessions.
    For more advanced information, see about_pssession_details.

    Note: PSSessions use the Windows PowerShell remoting infrastructure.
         To use PSSessions, the local and remote computers must be configured
         for remoting. For more information, see about_remote_requirements.

         In Windows Vista and later versions of Windows, to create a
         PSSession on a local computer, you must start Windows PowerShell
         with the “Run as administrator” option.

WHAT IS A SESSION?

    A session is an Environment in which Windows PowerShell runs.

    Each time you start Windows PowerShell, a session is created for you, and
    you can run commands in the session. You can also add items to your session,
    such as modules and snap-ins, and you can create items, such as Variables,
    Functions, and Aliases. These items exist only in the session and are
    deleted when the session ends.

    You can also create additional sessions, known as “Windows PowerShell
    sessions” or “PSSessions,” on the local computer or on a remote computer.
    Like the default session, you can run commands in a PSSession and add and
    create items.

    However, unlike the session that starts automatically, you can control the
    PSSessions that you create. You can get, create, configure, and remove them,
    and you can run multiple commands in the same PSSession. The PSSession
    remains open and available until you delete it from your session.

    Typically, you create a PSSession to run a series of related commands on a
    remote computer. When you create a PSSession on a remote computer,
    Windows PowerShell establishes a persistent connection to the remote
    computer to support the session.

    If you use the computerName parameter of the Invoke-Command or
    Enter-PSSession cmdlet to run a remote command or to start an interactive
    session, Windows PowerShell creates a temporary session on the remote
    computer and closes the session as soon as the command is complete or as
    soon as the interactive session ends. You cannot control these temporary
    sessions, and you cannot use them for more than a single command or a
    single interactive session.

    In Windows PowerShell, the “current session” is the session that you are
    working in. The “current session” can refer to any session, including a
    temporary session or a PSSession.

WHY USE A PSSESSION?

    Use a PSSession when you need a persistent connection to a remote computer.
    With a PSSession, you can run a series of commands that share data, such as
    the value of Variables, the contents of a Function, or the definition of an
    Alias.

    You can run remote commands without creating a PSSession. Use the
    ComputerName parameter of remote-enabled cmdlets to run a single command
    or a series of unrelated commands on one or many computers.

    When you use the ComputerName parameter of Invoke-Expression or
    Enter-PSSession, Windows PowerShell establishes a temporary connection to
    the remote computer and then closes the connection as soon as the command
    is complete. Any data elements that you create are lost when the connection
    is closed.

    Other cmdlets that have a ComputerName parameter, such as Get-Eventlog and
    Get-WmiObject, use different remoting technologies to gather data. None
    create a persistent connection like a PSSession.

HOW TO CREATE A PSSESSION

    To create a PSSession, use the New-PSSession cmdlet. To create the
    PSSession on a remote computer, use the ComputerName parameter of the
    New-PSSession cmdlet.

    For example, the following command creates a new PSSession on the
    Server01 computer.

        New-PSSession -computername Server01

    When you submit the command, New-PSSession creates the PSSession and
    returns an object that represents the PSSession. You can save the object in
    a Variable when you create the PSSession, or you can use a Get-PSSession
    command to get the PSSession at a later time.

    For example, the following command creates a new PSSession on the Server01
    computer and saves the resulting object in the $ps Variable.

        $ps = New-PSSession -computername Server01

HOW TO CREATE PSSESSIONS ON MULTIPLE COMPUTERS

    To create PSSessions on multiple computers, use the ComputerName parameter
    of the New-PSSession cmdlet. Type the names of the remote computers in a
    comma-separated list.

    For example, to create PSSessions on the Server01, Server02, and Server03
    computers, type:

        New-PSSession -computername Server01, Server02, Server03

    New-PSSession creates one PSSession on each of the remote computers.

HOW TO GET PSSESSIONS

    To get the PSSessions that were created in your current session, use the
    Get-PSSession cmdlet. Get-PSSession returns the same type of object that
    New-PSSession returns.

    The following command gets all the PSSessions that were created in the
    current session.

        Get-PSSession

    The default display of the PSSessions shows their ID and a default display
    name. You can assign an alternate display name when you create the
    session.

        Id Name     ComputerName    State    ConfigurationName
        — —-     ————    —–    ———————
        1    Session1 Server01        Opened Microsoft.PowerShell
        2    Session2 Server02        Opened Microsoft.PowerShell
        3    Session3 Server03        Opened Microsoft.PowerShell

    You can also save the PSSessions in a Variable. The following command gets
    the PSSessions and saves them in the $ps123 Variable.

        $ps123 = Get-PSSession

    When using the PSSession cmdlets, you can refer to a PSSession by its ID, by
    its name, or by its instance ID (a GUID). The following command gets a
    PSSession by its ID and saves it in the $ps01 Variable.

        $ps01 = Get-PSSession -id 1

    Get-PSSession gets only the PSSessions that were created in the current
    session. It does not get PSSessions that were created in other sessions or
    on other computers, even if the sessions are connected to and are running
    commands on the local computer.

HOW TO RUN COMMANDS IN A PSSESSION

    To run a command in one or more PSSessions, use the Invoke-Command cmdlet.
    Use the Session parameter to specify the PSSessions and the ScriptBlock
    parameter to specify the command.

    For example, to run a Get-ChildItem (“dir”) command in each of the three
    PSSessions saved in the $ps123 Variable, type:

        Invoke-Command -session $ps123 -scriptblock {Get-ChildItem}

HOW TO DELETE PSSESSIONS

    When you are finished with the PSSession, use the Remove-PSSession cmdlet
    to delete the PSSession and to release the resources that it was using.

        Remove-PSSession -session $ps

        – or –

        Remove-PSSession -id 1

    If you do not delete the PSSession, the PSSession remains open and
    available for use until you close the current session or until you exit
    Windows PowerShell.

    You can also use the TimeOut parameter of New-PSSession to set an
    expiration time for an idle PSSession. For more information,
    see New-PSSession.

THE PSSESSION CMDLETS

    Cmdlet                Description
    —————–     ——————————————————
    New-PSSession         Creates a new PSSession on a local or remote computer.

    Get-PSSession         Gets the PSSessions in the current session.

    Remove-PSSession     Deletes the PSSessions in the current session.

    Enter-PSSession     Starts an interactive session.

    Exit-PSSession        Ends an interactive session.

    For a list of PSSession cmdlets, type:

    Get-Help *-PSSession

FOR MORE INFORMATION

    For more information about PSSessions, see about_pssession_details.

SEE ALSO
    about_remote
    about_remote_requirements
    New-PSSession
    Get-PSSession
    Remove-PSSession
    Enter-PSSession
    Exit-PSSession
    Invoke-Command

about_providers

TOPIC
    about_providers

SHORT DESCRIPTION
    Describes how Windows PowerShell providers provide access to data and
    components that would not otherwise be easily accessible at the command
    line. The data is presented in a consistent format that resembles a file
    system drive.

LONG DESCRIPTION
    Windows PowerShell providers are Microsoft .NET Framework-based programs
    that make the data in a specialized data store available in Windows
    PowerShell so that you can view and manage it.

    The data that a provider exposes appears in a drive, and you access the
    data in a path like you would on a hard disk drive. You can use any of the
    built-in cmdlets that the provider supports to manage the data in the
    provider drive. And, you can use custom cmdlets that are designed
    especially for the data.

    The providers can also add dynamic parameters to the built-in cmdlets.
    These are parameters that are available only when you use the cmdlet with
    the provider data.

BUILT-IN PROVIDERS
    Windows PowerShell includes a set of built-in providers that you can use
    to access the different types of data stores.

    Provider     Drive         Data store
    ——–     —–         ———-
    Alias         Alias:        Windows PowerShell Aliases

    Certificate Cert:         x509 Certificates for digital signatures

    Environment Env:         Windows Environment Variables

    FileSystem    *             File system drives, directories, and files

    Function     Function:     Windows PowerShell Functions

    Registry     HKLM:, HKCU Windows Registry

    Variable     Variable:     Windows PowerShell Variables

    WS-Management WSMan         WS-Management configuration information

* The FileSystem drives vary on each system.

    You can also create your own Windows PowerShell providers, and you can
    install providers that others develop. To list the providers that are
    available in your session, type:

     Get-PSProvider

INSTALLING AND REMOVING PROVIDERS
    Windows PowerShell providers are delivered to you in Windows PowerShell
    snap-ins, which are .NET Framework-based programs that are compiled
    into .dll files. The snap-ins can include providers and cmdlets.

    Before you use the provider features, you have to install the snap-in and
    then add it to your Windows PowerShell session. For more information, see
    about_PSSnapins.

    You cannot uninstall a provider, although you can remove the Windows
    PowerShell snap-in for the provider from the current session. If you do,
    you will remove all the contents of the snap-in, including its cmdlets.

    To remove a provider from the current session, use the Remove-PSSnapin
    cmdlet. This cmdlet does not uninstall the provider, but it makes
    the provider unavailable in the session.

    You can also use the Remove-PSDrive cmdlet to remove any drive from the
    current session. This data on the drive is not affected, but the drive is
    no longer available in that session.

VIEWING PROVIDERS
    To view the Windows PowerShell providers on your computer, type:

    Get-PSProvider

    The output lists the built-in providers and the providers that you added
    to the session.

THE PROVIDER CMDLETS
    The following cmdlets are designed to work with the data exposed by
    any provider. You can use the same cmdlets in the same way to manage
    the different types of data that providers expose. After you
    learn to manage the data of one provider, you can use the same
    procedures with the data from any provider.

    For example, the New-Item cmdlet creates a new item. In the C: drive that
    is supported by the FileSystem provider, you can use New-Item to create a
    new file or folder. In the drives that are supported by the Registry
    provider, you can use New-Item to create a new Registry key. In the Alias:
    drive, you can use New-Item to create a new Alias.

    For detailed information about any of the following cmdlets, type:

        Get-Help <cmdlet-name> -detailed

    CHILDITEM CMDLETS
        Get-ChildItem

    CONTENT CMDLETS
        Add-Content
        Clear-Content
        Get-Content
        Set-Content

    ITEM CMDLETS
        Clear-Item
        Copy-Item
        Get-Item
        Invoke-Item
        Move-Item
        New-Item
        Remove-Item
        Rename-Item
        Set-Item

    ITEMPROPERTY CMDLETS
        Clear-ItemProperty
        Copy-ItemProperty
        Get-ItemProperty
        Move-ItemProperty
        New-ItemProperty
        Remove-ItemProperty
        Rename-ItemProperty
        Set-ItemProperty

    LOCATION CMDLETS
        Get-Location
        Pop-Location
        Push-Location
        Set-Location

    PATH CMDLETS
        Join-Path
        Convert-Path
        Split-Path
        Resolve-Path
        Test-Path

    PSDRIVE CMDLETS
        Get-PSDrive
        New-PSDrive
        Remove-PSDrive

    PSPROVIDER CMDLETS
        Get-PSProvider

VIEWING PROVIDER DATA
    The primary benefit of a provider is that it exposes its data in a familiar
    and consistent way. The model for data presentation is a file system
    drive.

    To use data that the provider exposes, you view it, move through it,
    and change it as though it were data on a hard drive. Therefore, the most
    important information about a provider is the name of the drive
    that it supports.

    The drive is listed in the default display of the Get-PSProvider cmdlet,
    but you can get information about the provider drive by using the
    Get-PSDrive cmdlet. For example, to get all the properties of the
    Function: drive, type:

    Get-PSDrive Function | Format-List *

    You can view and move through the data in a provider drive just as
    you would on a file system drive.

    To view the contents of a provider drive, use the Get-Item or Get-ChildItem
    cmdlets. Type the drive name followed by a colon (:). For example, to
    view the contents of the Alias: drive, type:

        Get-Item Alias:

    You can view and manage the data in any drive from another drive by
    including the drive name in the path. For example, to view the
    HKLM\Software Registry key in the HKLM: drive from another drive, type:

        Get-ChildItem hklm:\software

    To open the drive, use the Set-Location cmdlet. Remember the colon
    when you specify the drive path. For example, to change your location
    to the root directory of the Cert: drive, type:

        Set-Location cert:

    Then, to view the contents of the Cert: drive, type:

    Get-ChildItem

MOVING THROUGH HIERARCHICAL DATA
    You can move through a provider drive just as you would a hard disk drive.
    If the data is arranged in a hierarchy of items within items, use a
    backslash (\) to indicate a child item. Use the following format:

    drive:\location\child-location\…

    For example, to change your location to the HKLM\Software Registry key,
    type a Set-Location command, such as:

        Set-Location hklm:\software

    You can also use relative references to locations. A dot (.) represents the
    current location. For example, if you are in the HKLM:\Software\Microsoft
    Registry key, and you want to list the Registry subkeys in the
    HKLM:\Software\Micrsoft\PowerShell key, type the following command:

        Get-ChildItem .\powershell

FINDING DYNAMIC PARAMETERS
    Dynamic parameters are cmdlet parameters that are added to a cmdlet
    by a provider. These parameters are available only when the cmdlet is
    used with the provider that added them.

    For example, the Cert: drive adds the CodeSigningCert parameter
    to the Get-Item and Get-ChildItem cmdlets. You can use this parameter
    only when you use Get-Item or Get-ChildItem in the Cert: drive.

    For a list of the dynamic parameters that a provider supports, see the
    Help file for the provider. Type:

    Get-Help <provider-name>

    For example:

    Get-Help Certificate

LEARNING ABOUT PROVIDERS
    Although all provider data appears in drives, and you use the same methods
    to move through them, the similarity stops there. The data stores that
    the provider exposes can be as varied as Active Directory locations and
    Microsoft Exchange Server mailboxes.

    For information about individual Windows PowerShell providers, type:

    Get-Help <ProviderName>

    For example:

    Get-Help Registry

    For a list of Help topics about the providers, type:

    Get-Help * -category provider

SEE ALSO
    about_locations
    about_Path_Syntax

about_properties

TOPIC
    about_properties

SHORT DESCRIPTION
    Describes how to use object properties 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.
    Typically, you work with object that are part of the Microsoft .NET
    Framework, but you can also create custom objects in Windows PowerShell.

    The association between an item and its object is very close. When you
    change an object, you change the item that it represents. For example,
    when you get a file in Windows PowerShell, you do not get the actual file.
    Instead, you get a FileInfo object that represents the file. When you
    change the FileInfo object, the file changes too.

    Most objects have properties. Properties are the data that is associated
    with an object. This data describes the object. For example, a FileInfo
    object has a property called Length that describes the size of the file
    that is represented by the object.

Object Properties

     To list the properties of an object, use the Get-Member cmdlet. For
     example, to get the properties of a FileInfo object, use the Get-ChildItem
     cmdlet to get the FileInfo object that represents a file. Then, use a
     pipeline operator (|) to send the FileInfo object to Get-Member. The
     following command gets the PowerShell.exe file and sends it to Get-Member.
     The $Pshome automatic Variable contains the path of the Windows PowerShell
     installation directory.

         Get-ChildItem $pshome\powershell.exe | Get-Member

     The output of the command lists the members of the FileInfo object.
     Members include both properties and methods. When you work in
     Windows PowerShell, you have access to all the members of the objects.

     To get only the properties of an object and not the methods, use the
     MemberType parameter of the Get-Member cmdlet with a value of “property”,
     as shown in the following example.

         Get-ChildItem $pshome\powershell.exe | Get-Member -membertype property

            TypeName: System.IO.FileInfo

         Name             MemberType Definition
         —-             ———- ———-
         Attributes        Property System.IO.FileAttributes Attributes {get;set;}
         CreationTime     Property System.DateTime CreationTime {get;set;}
         CreationTimeUtc Property System.DateTime CreationTimeUtc {get;set;}
         Directory         Property System.IO.DirectoryInfo Directory {get;}
         DirectoryName     Property System.String DirectoryName {get;}
         Exists            Property System.Boolean Exists {get;}
         Extension         Property System.String Extension {get;}
         FullName         Property System.String FullName {get;}
         IsReadOnly        Property System.Boolean IsReadOnly {get;set;}
         LastAccessTime    Property System.DateTime LastAccessTime {get;set;}
         LastAccessTimeUtc Property System.DateTime LastAccessTimeUtc {get;set;}
         LastWriteTime     Property System.DateTime LastWriteTime {get;set;}
         LastWriteTimeUtc Property System.DateTime LastWriteTimeUtc {get;set;}
         Length            Property System.Int64 Length {get;}
         Name             Property System.String Name {get;}

     After you find the properties, you can use them in your Windows PowerShell
     commands.

Property Values

     Although every object of a specific type has the same properties, the
     values of those properties describe the particular object. For example,
     every FileInfo object has a CreationTime property, but the value of that
     property differs for each file.

     The most common way to get the values of the properties of an object is to
     use the dot method. Type a reference to the object, such as a Variable
     that contains the object, or a command that gets the object. Then, type a
     dot (.) followed by the property name.

     For example, the following command displays the value of the CreationTime
     property of the PowerShell.exe file. The Get-ChildItem command returns a
     FileInfo object that represents the PowerShell.exe file. The command is
     enclosed in parentheses to make sure that it is executed before any
     properties are accessed. The Get-ChildItem command is followed by a dot
     and the name of the CreationTime property, as follows:

         C:\PS> (Get-ChildItem $pshome\powershell.exe).creationtime
         Tuesday, March 18, 2008 12:07:52 AM

     You can also save an object in a Variable and then get its properties by
     using the dot method, as shown in the following example:

         C:\PS> $a = Get-ChildItem $pshome\powershell.exe
         C:\PS> $a.CreationTime
         Tuesday, March 18, 2008 12:07:52 AM

     You can also use the Select-Object and Format-List cmdlets to display the
     property values of an object. Select-Object and Format-List each have a
     Property parameter. You can use the Property parameter to specify one or
     more properties and their values. Or, you can use the wildcard
     character (*) to represent all the properties.

     For example, the following command displays the values of all the
     properties of the PowerShell.exe file.

         C:\PS> Get-ChildItem $pshome\powershell.exe | Format-List -property *

         PSPath            : Microsoft.PowerShell.Core\FileSystem::C:\Windows\system32\WindowsPowerShell\v1.0\powershell.exe
         PSParentPath     : Microsoft.PowerShell.Core\FileSystem::C:\Windows\system32\WindowsPowerShell\v1.0
         PSChildName     : powershell.exe
         PSDrive         : C
         PSProvider        : Microsoft.PowerShell.Core\FileSystem
         PSIsContainer     : False
         VersionInfo     : File:             C:\Windows\system32\WindowsPowerShell\v1.0\powershell.exe
                             InternalName:     POWERSHELL
                             OriginalFilename: PowerShell.EXE.MUI
                             File Version:     6.1.6570.1 (fbl_srv_powershell(nigels).070711-0102)
                             FileDescription: PowerShell.EXE
                             Product:         Microsoft® Windows® Operating System
                             ProductVersion: 6.1.6570.1
                             Debug:            False
                             Patched:         False
                             PreRelease:     False
                             PrivateBuild:     True
                             SpecialBuild:     False
                             Language:         English (United States)

         BaseName         : powershell
         Mode             : -a—
         Name             : powershell.exe
         Length            : 160256
         DirectoryName     : C:\Windows\system32\WindowsPowerShell\v1.0
         Directory         : C:\Windows\system32\WindowsPowerShell\v1.0
         IsReadOnly        : False
         Exists            : True
         FullName         : C:\Windows\system32\WindowsPowerShell\v1.0\powershell.exe
         Extension         : .exe
         CreationTime     : 3/18/2008 12:07:52 AM
         CreationTimeUtc : 3/18/2008 7:07:52 AM
         LastAccessTime    : 3/19/2008 8:13:58 AM
         LastAccessTimeUtc : 3/19/2008 3:13:58 PM
         LastWriteTime     : 3/18/2008 12:07:52 AM
         LastWriteTimeUtc : 3/18/2008 7:07:52 AM
         Attributes        : Archive

SEE ALSO
    about_objects
    Get-Member
    Select-Object
    Format-List

about_prompts

TOPIC
    about_prompts

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

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

    PS C:\>

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

The Prompt Function

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

     The Prompt Function has the following syntax:

     Function prompt { <function-body> }

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

     For example:

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

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

     (Get-Item Function:prompt).definition

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

The Default Prompt

     The default Windows PowerShell prompt is:

     PS>

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

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

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

The Built-in Prompt

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

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

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

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

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

     [DBG] PS C:\ps-test>

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

     PS C:\ps-test>

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

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

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

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

         PS Hello, World> Enter-PSSession Server01

         [Server01]: PS Hello, World>

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

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

Customizing the Prompt

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

     To write a prompt Function, type the following:

     Function prompt { }

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

     For example, the following prompt includes your computer name:

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

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

     PS [Server01] >

     The following prompt Function includes the current date and time:

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

     The prompt resembles the following prompt:

     01/01/2008 17:49:47>

     You can also modify the default Prompt Function:

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

Saving the Prompt

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

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