Category Archives: HelpFile

about_requires

TOPIC
    about_requires

SHORT DESCRIPTION
    Prevents a script from running by requiring the specified snap-ins and
    version.

LONG DESCRIPTION
    The #Requires statement prevents a script from running unless the Windows
    PowerShell version, snap-in, and snap-in version prerequisites are met. If
    the prerequisites are not met, Windows PowerShell does not run the script.

    You can use #Requires statements in any script. You cannot use them in
    Functions, cmdlets, or snap-ins.

Syntax

     Use the following syntax to specify the snap-in and the version of the
     snap-in that you want to require:

         #requires –PsSnapIn <PsSnapIn> [-Version <N>[.<n>]]

     Use the following syntax to specify the minimum version of
     Windows PowerShell that you want to require:

         #requires -Version <N>[.<n>]

     Use the following syntax to specify the shell that you want to require:

         #requires –ShellId <ShellId>

Rules for Use

     – The #Requires statement must be the first item on a line in a script.

     – A script can include more than one #Requires statement.

     – The #Requires statements can appear on any line in a script.

Examples

     The following statement requires the Microsoft.PowerShell.Security
     snap-in:

         #requires –PsSnapIn Microsoft.PowerShell.Security

     If the Microsoft.PowerShell.Security snap-in is not loaded, the script
     does not run, and Windows PowerShell displays the following error
     message:

         “The script ‘<script-name>’ cannot be run because the following
         Windows PowerShell snap-ins that are specified by its “#requires”
         statements are missing: Microsoft.PowerShell.Security.”

     The following statement requires the Windows PowerShell 2.0 version or
     any later version of the Microsoft.PowerShell.Security snap-in:

         #requires –PsSnapIn Microsoft.PowerShell.Security –Version 2

     The following statement requires Windows PowerShell 2.0 or a later
     version:

         #requires –Version 2.0

     The following script has two #Requires statements. The requirements
     specified in both statements must be met. Otherwise, the script will not
     run. Each #Requires statement must be the first item on a line:

         #requires –PsSnapIn Microsoft.PowerShell.Security –Version 2
         Get-WmiObject WIN32_LogicalDisk | Out-File K:\status\DiskStatus.txt
         #requires –Version 2

     The following #Requires statement prevents a script from running if the
     specified shell ID does not match the current shell ID. The current
     shell ID is stored in the $ShellId Variable:

         #requires –ShellId MyLocalShell

SEE ALSO
    about_Automatic_Variables
    about_Language_Keywords
    about_PSSnapins
    Get-PSSnapin

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_Reserved_Words

TOPIC
    about_Reserved_Words

SHORT DESCRIPTION
    Lists the reserved words that cannot be used as identifiers because they
    have a special meaning in Windows PowerShell.

LONG DESCRIPTION
    There are certain words that have special meaning in Windows PowerShell.
    When these words appear without quotation marks, Windows PowerShell
    attempts to apply their special meaning rather than treating them as
    character strings. To use these words as parameter arguments in a command
    or script without invoking their special meaning, enclose the reserved
    words in quotation marks.

    The following are the reserved words in Windows PowerShell:

        Break
        Continue
        Do
        Else
        Elseif
        Filter
        For
        Foreach
        Function
        If
        In
        Local
        Private
        Return
        Switch
        Until
        Where
        While

    For information about language statements, such as Foreach, If,
    For, and While, type “Get-Help“, type the prefix “about_”, and then type
    the name of the statement. For example, to get information about the
    Foreach statement, type:

    Get-Help about_Foreach

    For information about the Filter statement or the Return statement
    syntax, type:

        Get-Help about_functions

SEE ALSO
    about_Command_Syntax
    about_escape_characters
    about_Language_Keywords
    about_Parsing
    about_Quoting_Rules
    about_script_blocks
    about_Special_Characters

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_Return

TOPIC
    about_Return

SHORT DESCRIPTION
    Exits the current scope, which can be a Function, script, or script block.

LONG DESCRIPTION
    The Return keyword exits a Function, script, or script block. It can be
    used to exit a scope at a specific point, to return a value, or to indicate
    that the end of the scope has been reached.

    Users who are familiar with languages like C or C# might want to use the
    Return keyword to make the logic of leaving a scope explicit.

    In Windows PowerShell, the results of each statement are returned as
    output, even without a statement that contains the Return keyword.
    Languages like C or C# return only the value or values that are specified
    by the Return keyword.

Syntax

     The syntax for the Return keyword is as follows:

         return [<expression>]

     The Return keyword can appear alone, or it can be followed by a value or
     expression, as follows:

         return
         return $a
         return (2 + $a)

Examples

     The following example uses the Return keyword to exit a Function at a
     specific point if a conditional is met:

         Function ScreenPassword($instance)
         {
             if (!($instance.screensaversecure)) {return $instance.name}
             <additional statements>
         }

         foreach ($a in @(Get-WmiObject win32_desktop)) { ScreenPassword($a) }

     This script checks each user account. The ScreenPassword Function returns
     the name of any user account that does not have a password-protected
     screen saver. If the screen saver is password protected, the Function
     completes any other statements to be run, and Windows PowerShell does not
     return any value.

     In Windows PowerShell, values can be returned even if the Return keyword
     is not used. The results of each statement are returned. For example, the
     following statements return the value of the $a Variable:

         $a
         return

     The following statement also returns the value of $a:

         return $a

     The following example includes a statement intended to let the user know
     that the Function is performing a calculation:

         Function calculation {
             param ($value)

             “Please wait. Working on calculation…”
             $value += 73
             return $value
             }

     Running this Function and assigning the result to a Variable has the
     following effect:

         C:\PS> $a = calculation 14
         C:\PS>

     The “Please wait. Working on calculation…” string is not displayed.
     Instead, it is assigned to the $a Variable, as in the following example:

         C:\PS> $a
         Please wait. Working on calculation…
         87

     Both the informational string and the result of the calculation are
     returned by the Function and assigned to the $a Variable.

SEE ALSO
    about_functions
    about_scopes
    about_script_blocks

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_scopes

TOPIC
    about_scopes

SHORT DESCRIPTION
    Explains the concept of scope in Windows PowerShell and shows how to set
    and change the scope of elements.

LONG DESCRIPTION
    Windows PowerShell protects access to Variables, Aliases, Functions, and
    Windows PowerShell drives (PSDrives) by limiting where they can be read and
    changed. By enforcing a few simple rules for scope, Windows PowerShell
    helps to ensure that you do not inadvertently change an item that should
    not be changed.

    The following are the basic rules of scope:

        – An item you include in a scope is visible in the scope in which it
         was created and in any child scope, unless you explicitly make it
         private. You can place Variables, Aliases, Functions, or Windows
         PowerShell drives in one or more scopes.

        – An item that you created within a scope can be changed only in the
         scope in which it was created, unless you explicitly specify a
         different scope.

    If you create an item in a scope, and the item shares its name with an
    item in a different scope, the original item might be hidden under the
    new item. But, it is not overridden or changed.

Windows PowerShell Scopes

    Scopes in Windows PowerShell have both names and numbers. The named
    scopes specify an absolute scope. The numbers are relative and reflect
    the relationship between scopes.

    Global:
        The scope that is in effect when Windows PowerShell
        starts. Variables and Functions that are present when
        Windows PowerShell starts have been created in the
        global scope. This includes automatic Variables and
        preference Variables. This also includes the Variables, Aliases,
        and Functions that are in your Windows PowerShell
        profiles.

    Local:
        The current scope. The local scope can be the global
        scope or any other scope.

    Script:
        The scope that is created while a script file runs. Only
        the commands in the script run in the script scope. To
        the commands in a script, the script scope is the local
        scope.

    Private:
        Items in private scope cannot be seen outside of the current
        scope. You can use private scope to create a private version
        of an item with the same name in another scope.

    Numbered Scopes:
        You can refer to scopes by name or by a number that
        describes the relative position of one scope to another.
        Scope 0 represents the current, or local, scope. Scope 1
        indicates the immediate parent scope. Scope 2 indicates the
        parent of the parent scope, and so on. Numbered scopes
        are useful if you have created many recursive
        scopes.

Parent and Child Scopes

    You can create a new scope by running a script or Function, by creating
    a session, or by starting a new instance of Windows PowerShell. When you
    create a new scope, the result is a parent scope (the original scope) and
    a child scope (the scope that you created).

    In Windows PowerShell, all scopes are child scopes of the global scope,
    but you can create many scopes and many recursive scopes.

    Unless you explicitly make the items private, the items in the parent scope
    are available to the child scope. However, items that you create and change
    in the child scope do not affect the parent scope, unless you explicitly
    specify the scope when you create the items.

Inheritance

    A child scope does not inherit the Variables, Aliases, and Functions from
    the parent scope. Unless an item is private, the child scope can view the
    items in the parent scope. And, it can change the items by explicitly
    specifying the parent scope, but the items are not part of the child scope.

    However, a child scope is created with a set of items. Typically, it
    includes all the Aliases that have the AllScope option. This option is
    discussed later in this topic. It includes all the Variables that have the
    AllScope option, plus some Variables that can be used to customize the
    scope, such as MaximumFunctionCount.

    To find the items in a particular scope, use the Scope parameter of
    Get-Variable or Get-Alias.

    For example, to get all the Variables in the local scope, type:

    Get-Variable -scope local

    To get all the Variables in the global scope, type:

    Get-Variable -scope global

Scope Modifiers

    To specify the scope of a new Variable, Alias, or Function, use a scope
    modifier. The valid values of a modifier are Global and Script.

    The syntax for a scope modifier in a Variable is:

        $[<scope-modifier>]:<name> = <value>

    The syntax for a scope modifier in a Function is:

        Function [<scope-modifier>]:<name> {<function-body>}

    The default scope for scripts is the script scope. The default scope for
    Functions and Aliases is the local scope, even if they are defined in a
    script.

    The following command, which does not use a scope modifier, creates a
    Variable in the current or local scope:

     $a = “one”

    To create the same Variable in the global scope, use the Global scope
    modifier:

     $global:a = “one”

    To create the same Variable in the script scope, use the script
    scope modifier:

     $script:a = “one”

    You can also use a scope modifier in Functions. The following Function
    definition creates a Function in the global scope:

     Function global:Hello
     {
        Write-Host “Hello, World”
     }

    You can also use scope modifiers to refer to a Variable in a different
    scope. The following command refers to the $test Variable, first in the
    local scope and then in the global scope:

     $test

     $global:test

The AllScope Option

    Variables and Aliases have an Option property that can take a value of
    AllScope. Items that have the AllScope property become part of any child
    scopes that you create, although they are not retroactively inherited by
    parent scopes.

    An item that has the AllScope property is visible in the child scope, and
    it is part of that scope. Changes to the item in any scope affect all the
    scopes in which the Variable is defined.

Managing Scope

    Several cmdlets have a Scope parameter that lets you get or set (create
    and change) items in a particular scope. Use the following command to find
    all the cmdlets in your session that have a Scope parameter:

         Get-Help * -parameter scope

    To find the Variables that are visible in a particular scope, use the
    Scope parameter of Get-Variable. The visible parameters include global
    parameters, parameters in the parent scope, and parameters in the current
    scope.

    For example, the following command gets the Variables that are visible in
    the local scope:

        Get-Variable -scope local

    To create a Variable in a particular scope, use a scope modifier or the
    Scope parameter of Set-Variable. The following command creates a Variable
    in the global scope:

    New-Variable -scope global -name a -value “One”

    You can also use the Scope parameter of the New-Alias, Set-Alias, or
    Get-Alias cmdlets to specify the scope. The following command creates an
    Alias in the global scope:

    New-Alias -scope global -name np -value Notepad.exe

    To get the Functions in a particular scope, use the Get-Item cmdlet when
    you are in the scope. The Get-Item cmdlet does not have a scope parameter.

Using Dot Source Notation with Scope

    Scripts and Functions follow all the rules of scope. You create them in a
    particular scope, and they affect only that scope unless you use a cmdlet
    parameter or a scope modifier to change that scope.

    But, you can add a script or Function to the current scope by using dot
    source notation. Then, when a script runs in the current scope, any
    Functions, Aliases, and Variables that the script creates are available
    in the current scope.

    To add a Function to the current scope, type a dot (.) and a space before
    the path and name of the Function in the Function call.

    For example, to run the Sample.ps1 script from the C:\Scripts directory in
    the script scope (the default for scripts), use the following command:

        c:\scripts\sample.ps1

    To run the Sample.ps1 script in the local scope, use the following command:

        . c:\scripts.sample.ps1

    When you use the call operator (&) to run a Function or script, it is not
    added to the current scope. The following example uses the call operator:

        & c:\scripts.sample.ps1

    Any Aliases, Functions, or Variables that the Sample.ps1 script creates
    are not available in the current scope.

Restricting Without Scope

    A few Windows PowerShell concepts are similar to scope or interact with
    scope. These concepts may be confused with scope or the behavior of scope.

    Sessions, modules, and nested prompts are self-contained Environments,
    but they are not child scopes of the global scope in the session.

    Sessions:
        A session is an Environment in which Windows PowerShell runs.
        When you create a session on a remote computer, Windows
        PowerShell establishes a persistent connection to the remote
        computer. The persistent connection lets you use the session for
        multiple related commands.

        Because a session is a contained Environment, it has its own
        scope, but a session is not a child scope of the session in
        which is was created. The session starts with its own global
        scope. This scope is independent of the global scope of the session.
        You can create child scopes in the session. For example, you can run
        a script to create a child scope in a session.

    Modules:
        You can use a Windows PowerShell module to share and deliver
        Windows PowerShell tools. A module is a unit that can contain
        cmdlets, scripts, Functions, Variables, Aliases, and other useful
        items. Unless explicitly defined, the items in a module are not
        accessible outside the module. Therefore, you can add the module to
        your session and use the public items without worrying that the
        other items might override the cmdlets, scripts, Functions, and other
        items in your session.

        The privacy of a module behaves like a scope, but adding a module
        to a session does not change the scope. And, the module does not have
        its own scope, although the scripts in the module, like all Windows
        PowerShell scripts, do have their own scope.

    Nested Prompts:
        Similarly, nested prompts do not have their own scope. When you enter
        a nested prompt, the nested prompt is a subset of the Environment.
        But, you remain within the local scope.

        Scripts do have their own scope. If you are debugging a script, and
        you reach a breakpoint in the script, you enter the script scope.

    Private Option:
        Aliases and Variables have an Option property that can take a value
        of Private. Items that have the Private option can be viewed and
        changed in the scope in which they are created, but they cannot be
        viewed or changed outside that scope.

        For example, if you create a Variable that has a private option in the
        global scope and then run a script, Get-Variable commands in the script
        do not display the private Variable. This occurs even if you use
        the global scope modifier.

        You can use the Option parameter of the New-Variable, Set-Variable,
        New-Alias, and Set-Alias cmdlets to set the value of the Option
        property to Private.

    Visibility:
        The Visibility property of a Variable or Alias determines whether you
        can see the item outside the container, such as a module, in which it
        was created. Visibility is designed for containers in the same way that
        the Private value of the Option property is designed for scopes.

        The Visibility property takes the Public and Private values. Items
        that have private visibility can be viewed and changed only in the
        container in which they were created. If the container is added or
        imported, the items that have private visibility cannot be viewed or
        changed.

        Because Visibility is designed for containers, it works differently
        in a scope. If you create an item that has private visibility in the
        global scope, you cannot view or change the item in any scope. If you
        try to view or change the value of a Variable that has private
        visibility, Windows PowerShell returns an error message.

        You can use the New-Variable and Set-Variable cmdlets to create a
        Variable that has private visibility.

EXAMPLES

Example 1: Change a Variable Value Only in a Script

     The following command changes the value of the $ConfirmPreference
     Variable in a script. The change does not affect the global scope.

     First, to display the value of the $ConfirmPreference Variable in
     the local scope, use the following command:

         C:\PS> $ConfirmPreference
         High

     Create a Scope.ps1 script that contains the following commands:

         $ConfirmPreference = “Low”
         “The value of `$ConfirmPreference is $ConfirmPreference.”

     Run the script. The script changes the value of the $ConfirmPreference
     Variable and then reports its value in the script scope. The output
     should resemble the following output:

         The value of $ConfirmPreference is Low.

     Next, test the current value of the $ConfirmPreference Variable in the
     current scope.

         C:\PS> $ConfirmPreference
         High

     This example shows that changes to the value of a Variable in the script
     scope do not affect the value of that Variable in the parent scope.

Example 2: View a Variable Value in Different Scopes

     You can use scope modifiers to view the value of a Variable in the local
     scope and in a parent scope.

     First, define a $test Variable in the global scope.

     $test = “Global”

     Next, create a Sample.ps1 script that defines the $test
     Variable. In the script, use a scope modifier to refer
     to either the global or local versions of the $test Variable.

         # In Sample.ps1

         $test = “Local”
         “The local value of `$test is $test.”
         “The global value of `$test is $global:test.”

     When you run Sample.ps1, the output should resemble the following output:

         The local value of $test is Local.
         The global value of $test is Global.

     When the script is complete, only the global value of $test is defined
     in the session.

         C:\PS> $test
         Global

Example 3: Change the Value of a Variable in a Parent Scope

     Unless you protect an item by using the Private option or another
     method, you can view and change the value of a Variable in a parent
     scope.

     First, define a $test Variable in the global scope.

     $test = “Global”

     Next, create a Sample.ps1 script that defines the $test Variable. In the
     script, use a scope modifier to refer to either the global or local
     versions of the $test Variable.

         # In Sample.ps1

         $global:test = “Local”
         “The global value of `$test is $global:test.”

     When the script is complete, the global value of $test is changed.

         C:\PS> $test
         Local

Example 4: Creating a Private Variable

     A private Variable is a Variable that has an Option property that has a
     value of Private. Private Variables are inherited by the child scope, but
     they can be viewed or changed only in the scope in which they were
     created.

     The following command creates a private Variable called $ptest in the
     local scope.

     New-Variable -name ptest -value 1 -option private

     You can display and change the value of $ptest in the local scope.

     C:\PS> $ptest
         1
         C:\PS> $ptest = 2
         C:\PS> $ptest
     2

     Next, create a Sample.ps1 script that contains the following commands.
     The command tries to display and change the value of $ptest.

         # In Sample.ps1

         “The value of `$Ptest is $Ptest.”
          “The value of `$Ptest is $global:Ptest.”

     Because the $ptest Variable is not visible in the script scope, the
     output is empty.

         “The value of $Ptest is .”
          “The value of $Ptest is .”

SEE ALSO
    about_Variables
    about_environment_variables
    about_functions
    about_script_blocks

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_scripts

TOPIC
    about_scripts

SHORT DESCRIPTION
    Describes how to write and run scripts in Windows PowerShell.

LONG DESCRIPTION
    A script is a plain text file that contains one or more Windows PowerShell
    commands. Windows PowerShell scripts have a .ps1 file name extension.

    Writing a script saves a command for later use and makes it easy to share
    with others. Most importantly, it lets you run the commands simply by typing
    the script path and the file name. Scripts can be as simple as a single
    command in a file or as extensive as a complex program.

    Scripts have additional features, such as the #Requires special comment,
    the use of parameters, support for data sections, and digital signing for
    security. You can also write Help topics for scripts and for any Functions
    in the script.

HOW TO WRITE A SCRIPT

    A script can contain any valid Windows PowerShell commands, including single
    commands, commands that use the pipeline, Functions, and control structures
    such as If statements and For loops.

    To write a script, start a text editor (such as Notepad) or a script editor
    (such as the Windows PowerShell Integrated Scripting Environment [ISE]). Type
    the commands and save them in a file with a valid file name and the .ps1 file
    name extension.

    The following example is a simple script that gets the services that are
    running on the current system and saves them to a log file. The log file name
    is created from the current date.

        $date = (Get-Date).dayofyear
        Get-Service | Out-File “$date.log”

    To create this script, open a text editor or a script editor, type these
    commands, and then save them in a file named ServiceLog.ps1.

HOW TO RUN A SCRIPT

    Before you can run a script, you need to change the default Windows
    PowerShell execution policy. The default execution policy, “Restricted”,
    prevents all scripts from running, including scripts that you write on the
    local computer. For more information, see about_execution_policies.

    To run a script, type the full name and the full path to the script file.

    For example, to run the ServicesLog script in the C:\Scripts directory, type:

        c:\scripts\ServicesLog.ps1

    To run a script in the current directory, type the path to the current
    directory, or use a dot to represent the current directory, followed by
    a path backslash (.\).

    For example, to run the ServicesLog.ps1 script in the local directory, type:

        .\ServicesLog.ps1

    As a security feature, Windows PowerShell does not run scripts when you
    double-click the script icon in Windows Explorer or when you type the
    script name without a full path, even when the script is in the current
    directory. For more information about running commands and scripts in
    Windows PowerShell, see about_command_precedence.

RUNNING SCRIPTS REMOTELY

    To run a script on a remote computer, use the FilePath parameter of the
    Invoke-Command cmdlet.

    Enter the path and file name of the script as the value of the FilePath
    parameter. The script must reside on the local computer or in a directory
    that the local computer can access.

    The following command runs the ServicesLog.ps1 script on the Server01 remote
    computer.

        Invoke-Command -computername Server01 -filepath C:\scripts\servicesLog.ps1

PARAMETERS IN SCRIPTS

    To define parameters in a script, use a Param statement. The Param statement
    must be the first statement in a script, except for comments and any
    #Requires statements.

    Script parameters work like Function parameters. The parameter values are
    available to all of the commands in the script. All of the features of
    Function parameters, including the Parameter attribute and its named
    arguments, are also valid in scripts.

    When running the script, script users type the parameters after the script
    name.

    The following example shows a Test-Remote.ps1 script that has a ComputerName
    parameter. Both of the script Functions can access the ComputerName
    parameter value.

        param ($ComputerName = $(throw “ComputerName parameter is required.”))

        Function CanPing {
         $error.clear()
         $tmp = Test-Connection $computername -ErrorAction SilentlyContinue

         if (!$?)
             {Write-Host “Ping failed: $ComputerName.”; return $false}
         else
             {Write-Host “Ping succeeded: $ComputerName”; return $true}
        }

        Function CanRemote {
            $s = New-PSSession $computername -ErrorAction SilentlyContinue

            if ($s -is [System.Management.Automation.Runspaces.PSSession])
                {Write-Host “Remote test succeeded: $ComputerName.”}
            else
                {Write-Host “Remote test failed: $ComputerName.”}
        }

        if (CanPing $computername) {CanRemote $computername}

    To run this script, type the parameter name after the script name.
    For example:

    C:\PS> .\test-remote.ps1 -computername Server01

    Ping succeeded: Server01
    Remote test failed: Server01

    For more information about the Param statement and the Function parameters,
    see about_functions and about_functions_advanced_parameters.

HELP FOR SCRIPTS

    The Get-Help cmdlet gets Help for scripts as well as for cmdlets,
    providers, and Functions. To get Help for a script, type Get-Help and the
    path and file name of the script. If the script path is in your Path
    Environment Variable, you can omit the path.

    For example, to get Help for the ServicesLog.ps1 script, type:

        Get-Help C:\admin\scripts\ServicesLog.ps1

    You can write Help for a script by using either of the two following methods:

    — Comment-Based Help for Scripts

        Create a Help topic by using special keywords in the comments. To create
        comment-based Help for a script, the comments must be placed at the
        beginning or end of the script file. For more information about
        comment-based Help, see about_Comment_Based_Help.

    — XML-Based Help for Scripts

        Create an XML-based Help topic, such as the type that is typically
        created for cmdlets. XML-based Help is required if you are translating
        Help topics into multiple languages.

        To associate the script with the XML-based Help topic, use the
        .ExternalHelp Help comment keyword. For more information about the
        ExternalHelp keyword, see about_Comment_Based_Help. For more information
        about XML-based help, see “How to Write Cmdlet Help” in the MSDN
        (Microsoft Developer Network) library at
        http://go.microsoft.com/fwlink/?LinkID=123415.

SCRIPT SCOPE AND DOT SOURCING

    Each script runs in its own scope. The Functions, Variables, Aliases, and
    drives that are created in the script exist only in the script scope. You
    cannot access these items or their values in the scope in which the
    script runs.

    To run a script in a different scope, you can specify a scope, such as
    Global or Local, or you can dot source the script.

    The dot sourcing feature lets you run a script in the current scope instead
    of in the script scope. When you run a script that is dot sourced, the
    commands in the script run as though you had typed them at the command
    prompt. The Functions, Variables, Aliases, and drives that the script
    creates are created in the scope in which you are working. After the script
    runs, you can use the created items and access their values in your session.

    To dot source a script, type a dot (.) and a space before the script path.

    For example:

        . C:\scripts\UtilityFunctions.ps1

    -or-

        . .\UtilityFunctions.ps1

    After the UtilityFunctions script runs, the Functions and Variables that the
    script creates are added to the current scope.

    For example, the UtilityFunctions.ps1 script creates the New-Profile
    Function and the $ProfileName Variable.

        #In UtilityFunctions.ps1

        Function New-Profile
        {
            Write-Host “Running New-Profile Function
            $profileName = Split-Path $profile -leaf

            if (Test-Path $profile)
             {Write-Error “There is already a $profileName profile on this computer.”}
            else
         {New-Item -type file -path $profile -force }
        }

    If you run the UtilityFunctions.ps1 script in its own script scope, the
    New-Profile Function and the $ProfileName Variable exist only while the
    script is running. When the script exits, the Function and Variable are
    removed, as shown in the following example.

        C:\PS> .\UtilityFunctions.ps1

        C:\PS> New-Profile
        The term ‘new-profile’ is not recognized as a cmdlet, Function, operable
        program, or script file. Verify the term and try again.
        At line:1 char:12
        + new-profile <<<<
         + CategoryInfo         : ObjectNotFound: (new-profile:String) [],
         + FullyQualifiedErrorId : CommandNotFoundException

        C:\PS> $profileName
        C:\PS>

    When you dot source the script and run it, the script creates the
    New-Profile Function and the $ProfileName Variable in your session in your
    scope. After the script runs, you can use the New-Profile Function in your
    session, as shown in the following example.

        C:\PS> . .\UtilityFunctions.ps1

        C:\PS> New-Profile

            Directory: C:\Users\juneb\Documents\WindowsPowerShell

            Mode    LastWriteTime     Length Name
            —-    ————-     —— —-
            -a— 1/14/2009 3:08 PM     0 Microsoft.PowerShellISE_profile.ps1

        C:\PS> $profileName
        Microsoft.PowerShellISE_profile.ps1

    For more information about scope, see about_scopes.

SCRIPTS IN MODULES

    A module is a set of related Windows PowerShell resources that can be
    distributed as a unit. You can use modules to organize your scripts,
    Functions, and other resources. You can also use modules to distribute your
    code to others, and to get code from trusted sources.

    You can include scripts in your modules, or you can create a script module,
    which is a module that consists entirely or primarily of a script and
    supporting resources. A script module is just a script with a .psm1 file
    name extension.

    For more information about modules, see about_modules.

OTHER SCRIPT FEATURES

    Windows PowerShell has many useful features that you can use in scripts.

    #Requires
        You can use a #Requires statement to prevent a script from running
        without specified modules or snap-ins and a specified version of
        Windows PowerShell. For more information, see about_requires.

    $MyInvocation
        The $MyInvocation automatic Variable contains information about the
        current command, including the current script. You can use this Variable
        and its properties to get information about the script while it is
        running. For example, the $MyInvocation.MyCommand.Path Variable contains
        the path and file name of the script.

    Data sections
        You can use the Data keyword to separate data from logic in scripts.
        Data sections can also make localization easier. For more information,
        see about_data_sections and about_Script_Localization.

    Script Signing
        You can add a digital signature to a script. Depending on the execution
        policy, you can use digital signatures to restrict the running of scripts
        that could include unsafe commands. For more information, see
        about_execution_policies and about_Signing.

SEE ALSO
    about_command_precedence
    about_Comment_Based_Help
    about_execution_policies
    about_functions
    about_modules
    about_profiles
    about_requires
    about_scopes
    about_script_blocks
    about_Signing
    Invoke-Command

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