Tag Archives: ArgumentList

Start-Job

NAME
    Start-Job

SYNOPSIS
    Starts a Windows PowerShell background job.

SYNTAX
    Start-Job [-ScriptBlock] <scriptblock> [[-InitializationScript] <scriptblock>] [-ArgumentList <Object[]>] [-Authentication {Default | Basic | Negotiate | NegotiateWithImplicitCredential | Credssp | Digest | Kerberos}] [-Credential <PSCredential>] [-InputObject <psobject>] [-Name <string>] [-RunAs32] [<CommonParameters>]

    Start-Job [[-FilePath] <string>] [[-InitializationScript] <scriptblock>] [-ArgumentList <Object[]>] [-Authentication {Default | Basic | Negotiate | NegotiateWithImplicitCredential | Credssp | Digest | Kerberos}] [-Credential <PSCredential>] [-InputObject <psobject>] [-Name <string>] [-RunAs32] [<CommonParameters>]

DESCRIPTION
    The Start-Job cmdlet starts a Windows PowerShell background job on the local computer.

    A Windows PowerShell background job runs a command “in the background” without interacting with the current session. When you start a background job, a job object is returned immediately, even if the job takes an extended time to complete. You can continue to work in the session without interruption while the job runs.

    The job object contains useful information about the job, but it does not contain the job results. When the job completes, use the Receive-Job cmdlet to get the results of the job. For more information about background jobs, see about_jobs.

    To run a background job on a remote computer, use the AsJob parameter that is available on many cmdlets, or use the Invoke-Command cmdlet to run a Start-Job command on the remote computer. For more information, see about_remote_Jobs.

PARAMETERS
    -ArgumentList <Object[]>
        Specifies the arguments (parameter values) for the script that is specified by the FilePath parameter.

        Because all of the values that follow the ArgumentList parameter name are interpreted as being values of ArgumentList, the ArgumentList parameter should be the last parameter in the command.

        Required?                    false
        Position?                    named
        Default value
        Accept pipeline input?     false
        Accept wildcard characters? false

    -Authentication <AuthenticationMechanism>
        Specifies the mechanism that is used to authenticate the user’s credentials. Valid values are Default, Basic, Credssp, Digest, Kerberos, Negotiate, and NegotiateWithImplicitCredential. The default value is Default.

        CredSSP authentication is available only in Windows Vista, Windows Server 2008, and later versions of Windows.

        For information about the values of this parameter, see the description of the System.Management.Automation.Runspaces.AuthenticationMechanism enumeration in MSDN.

        CAUTION: Credential Security Service Provider (CredSSP) authentication, in which the user’s credentials are passed to a remote computer to be authenticated, is designed for commands that require authentication on more than one resource, such as accessing a remote network share. This mechanism increases the security risk of the remote operation. If the remote computer is compromised, the credentials that are passed to it can be used to control the network session.

        Required?                    false
        Position?                    named
        Default value
        Accept pipeline input?     false
        Accept wildcard characters? false

    -Credential <PSCredential>
        Specifies a user account that has permission to perform this action. The default is the current user.

        Type a user name, such as “User01” or “Domain01\User01”, or enter a PSCredential object, such as one from the Get-Credential cmdlet.

        Required?                    false
        Position?                    named
        Default value                Current user
        Accept pipeline input?     false
        Accept wildcard characters? false

    -FilePath <string>
        Runs the specified local script as a background job. Enter the path and file name of the script or pipe a script path to Start-Job. The script must reside on the local computer or in a directory that the local computer can access.

        When you use this parameter, Windows PowerShell converts the contents of the specified script file to a script block and runs the script block as a background job.

        Required?                    false
        Position?                    1
        Default value
        Accept pipeline input?     false
        Accept wildcard characters? false

    -InitializationScript <scriptblock>
        Specifies commands that run before the job starts. Enclose the commands in braces ( { } ) to create a script block.

        Use this parameter to prepare the session in which the job runs. For example, you can use it to add Functions, snap-ins, and modules to the session.

        Required?                    false
        Position?                    2
        Default value                None
        Accept pipeline input?     false
        Accept wildcard characters? false

    -InputObject <psobject>
        Specifies input to the command. Enter a Variable that contains the objects, or type a command or expression that generates the objects.

        In the value of the ScriptBlock parameter, use the $input automatic Variable to represent the input objects.

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

    -Name <string>
        Specifies a friendly name for the new job. You can use the name to identify the job to other job cmdlets, such as Stop-Job.

        The default friendly name is Job#, where “#” is an ordinal number that is incremented for each job.

        Required?                    false
        Position?                    named
        Default value                Job<number>
        Accept pipeline input?     true (ByPropertyName)
        Accept wildcard characters? false

    -RunAs32 [<SwitchParameter>]
        Runs the job in a 32-bit process.

        Use this parameter to force the job to run in a 32-bit process on a 64-bit operating system.

        Required?                    false
        Position?                    named
        Default value                False
        Accept pipeline input?     false
        Accept wildcard characters? false

    -ScriptBlock <scriptblock>
        Specifies the commands to run in the background job. Enclose the commands in braces ( { } ) to create a script block. This parameter is required.

        Required?                    true
        Position?                    1
        Default value
        Accept pipeline input?     false
        Accept wildcard characters? false

    <CommonParameters>
        This cmdlet supports the common parameters: Verbose, Debug,
        ErrorAction, ErrorVariable, WarningAction, WarningVariable,
        OutBuffer and OutVariable. For more information, type,
        “Get-Help about_CommonParameters“.

INPUTS
    System.String
        You can pipe a file path to Start-Job.

OUTPUTS
    System.Management.Automation.RemotingJob
        Start-Job returns an object that represents the job that it started.

NOTES

        To run in the background, Start-Job runs in its own session within the current session. When you use the Invoke-Command cmdlet to run a Start-Job command in a session on a remote computer, Start-Job runs in a session within the remote session.

    ————————– EXAMPLE 1 ————————–

    C:\PS>Start-Job -ScriptBlock {Get-Process}

    C:\PS> Start-Job -command “Get-Process

    Id    Name State    HasMoreData Location Command
    — —- —–    ———– ——– ——-
    1     Job1 Running True         localhost Get-Process

    Description
    ———–
    This command starts a background job that runs a Get-Process command. The command returns a job object with information about the job. The command prompt returns immediately so that you can work in the session while the job runs in the background.

    ————————– EXAMPLE 2 ————————–

    C:\PS>$jobWRM = Invoke-Command -computerName (Get-Content servers.txt) -ScriptBlock {Get-Service winrm} -jobname WinRM -throttlelimit 16 -AsJob

    Description
    ———–
    This command uses the Invoke-Command cmdlet and its AsJob parameter to start a background job that runs a “Get-Service winrm” command on numerous computers. Because the command is running on a server with substantial network traffic, the command uses the ThrottleLimit parameter of Invoke-Command to limit the number of concurrent commands to 16.

    The command uses the ComputerName parameter to specify the computers on which the job runs. The value of the ComputerName parameter is a Get-Content command that gets the text in the Servers.txt file, a file of computer names in a domain.

    The command uses the ScriptBlock parameter to specify the command and the JobName parameter to specify a friendly name for the job.

    ————————– EXAMPLE 3 ————————–

    C:\PS>$j = Start-Job -ScriptBlock {Get-Eventlog -log system} -Credential domain01\user01

    C:\PS> $j | Format-List -property *

    HasMoreData : True
    StatusMessage :
    Location     : localhost
    Command     : Get-Eventlog -log system
    JobStateInfo : Running
    Finished     : System.Threading.ManualResetEvent
    InstanceId    : 2d9d775f-63e0-4d48-b4bc-c05d0e177f34
    Id            : 1
    Name         : Job1
    ChildJobs     : {Job2}
    Output        : {}
    Error         : {}
    Progress     : {}
    Verbose     : {}
    Debug         : {}
    Warning     : {}
    StateChanged :

    C:\PS> $j.JobStateInfo.state
    Completed

    C:\PS> $results = Receive-Job -job $j

    C:\PS> $results
    Index Time         Type        Source                EventID Message
    —– —-         —-        ——                ——- ——-
    84366 Feb 18 19:20 Information Service Control M…     7036 The description…
    84365 Feb 18 19:16 Information Service Control M…     7036 The description…
    84364 Feb 18 19:10 Information Service Control M…     7036 The description…
    …

    Description
    ———–
    These commands manage a background job that gets all of the events from the System log in Event Viewer. The job runs on the local computer.

    The first command uses the Start-Job cmdlet to start the job. It uses the Credential parameter to specify the user account of a user who has permission to run the job on the computer. Then it saves the job object that Start-Job returns in the $j Variable.

    At this point, you can resume your other work while the job completes.

    The second command uses a pipeline operator (|) to pass the job object in $j to the Format-List cmdlet. The Format-List command uses the Property parameter with a value of all (*) to display all of the properties of the job object in a list.

    The third command displays the value of the JobStateInfo property. This contains the status of the job.

    The fourth command uses the Receive-Job cmdlet to get the results of the job. It stores the results in the $results Variable.

    The final command displays the contents of the $results Variable.

    ————————– EXAMPLE 4 ————————–

    C:\PS>Start-Job -filepath c:\scripts\sample.ps1

    Description
    ———–
    This command runs the Sample.ps1 script as a background job.

    ————————– EXAMPLE 5 ————————–

    C:\PS>Start-Job -Name WinRm -ScriptBlock {Get-Process winrm}

    Description
    ———–
    This command runs a background job that gets the WinRM process on the local computer. The command uses the ScriptBlock parameter to specify the command that runs in the background job. It uses the Name parameter to specify a friendly name for the new job.

    ————————– EXAMPLE 6 ————————–

    C:\PS>Start-Job -Name GetMappingFiles -InitializationScript {Import-Module MapFunctions} -ScriptBlock {Get-Map -Name * | Set-Content D:\Maps.tif} -RunAs32

    Description
    ———–
    This command starts a job that collects a large amount of data and saves it in a .tif file. The command uses the InitializationScript parameter to run a script block that imports a required module. It also uses the RunAs32 parameter to run the job in a 32-bit process even if the computer has a 64-bit operating system.

RELATED LINKS
    Online version: http://go.microsoft.com/fwlink/?LinkID=113405
    about_jobs
    about_job_details
    about_remote_Jobs
    Get-Job
    Receive-Job
    Wait-Job
    Stop-Job
    Remove-Job
    Invoke-Command

Start-Process

NAME
    Start-Process

SYNOPSIS
    Starts one or more processes on the local computer.

SYNTAX
    Start-Process [-FilePath] <string> [[-ArgumentList] <string[]>] [-Credential <PSCredential>] [-LoadUserProfile] [-NoNewWindow] [-PassThru] [-RedirectStandardError <string>] [-RedirectStandardInput <string>] [-RedirectStandardOutput <string>] [-UseNewEnvironment] [-Wait] [-WorkingDirectory <string>] [<CommonParameters>]

    Start-Process [-FilePath] <string> [[-ArgumentList] <string[]>] [-PassThru] [-Verb <string>] [-Wait] [-WindowStyle {Normal | Hidden | Minimized | Maximized}] [-WorkingDirectory <string>] [<CommonParameters>]

DESCRIPTION
    Starts one or more processes on the local computer. To specify the program that runs in the process, enter an executable file or script file, or a file that can be opened by using a program on the computer. If you specify a non-executable file, Start-Process starts the program that is associated with the file, much like the Invoke-Item cmdlet.

    You can use the parameters of Start-Process to specify options, such as loading a user profile, starting the process in a new window, or using alternate credentials.

PARAMETERS
    -ArgumentList <string[]>
        Specifies parameters or parameter values to use when starting the process. The parameter name (“Arguments”) is optional.

        Required?                    false
        Position?                    2
        Default value                None
        Accept pipeline input?     false
        Accept wildcard characters? false

    -Credential <PSCredential>
        Specifies a user account that has permission to perform this action. Type a user-name, such as “User01” or “Domain01\User01”, or enter a PSCredential object, such as one from the Get-Credential cmdlet. By default, the cmdlet uses the credentials of the current user.

        Required?                    false
        Position?                    named
        Default value                Current user.
        Accept pipeline input?     false
        Accept wildcard characters? false

    -FilePath <string>
        Specifies the path (optional) and file name of the program that runs in the process. Enter the name of an executable file or of a document, such as a .txt or .doc file, that is associated with a program on the computer. This parameter is required.

        If you specify only a file name, use the WorkingDirectory parameter to specify the path.

        Required?                    true
        Position?                    1
        Default value
        Accept pipeline input?     false
        Accept wildcard characters? false

    -LoadUserProfile [<SwitchParameter>]
        Loads the Windows user profile stored in the HKEY_USERS Registry key for the current user. The default value is FALSE.

        This parameter does not affect the Windows PowerShell profiles. (See about_profiles.)

        Required?                    false
        Position?                    named
        Default value                False
        Accept pipeline input?     false
        Accept wildcard characters? false

    -NoNewWindow [<SwitchParameter>]
        Prevents the process from running in a new window. By default, the process runs in a new window.

        Required?                    false
        Position?                    named
        Default value                False
        Accept pipeline input?     false
        Accept wildcard characters? false

    -PassThru [<SwitchParameter>]
        Returns a process object for each process that the cmdlet started. By default, this cmdlet does not generate any output.

        Required?                    false
        Position?                    named
        Default value                False
        Accept pipeline input?     false
        Accept wildcard characters? false

    -RedirectStandardError <string>
        Sends any errors generated by the process to a file that you specify. Enter the path and file name. By default, the errors are displayed in the console.

        Required?                    false
        Position?                    named
        Default value                Errors are displayed in the console
        Accept pipeline input?     false
        Accept wildcard characters? false

    -RedirectStandardInput <string>
        Reads input from the specified file. Enter the path and file name of the input file. By default, the process gets its input from the keyboard.

        Required?                    false
        Position?                    named
        Default value                Keyboard
        Accept pipeline input?     false
        Accept wildcard characters? false

    -RedirectStandardOutput <string>
        Sends the output generated by the process to a file that you specify. Enter the path and file name. By default, the output is displayed in the console.

        Required?                    false
        Position?                    named
        Default value                FALSE
        Accept pipeline input?     false
        Accept wildcard characters? false

    -UseNewEnvironment [<SwitchParameter>]
        Use new Environment Variables specified for the process. By default, the started process runs with the Environment Variables specified for the computer and user.

        Required?                    false
        Position?                    named
        Default value                False
        Accept pipeline input?     false
        Accept wildcard characters? false

    -Verb <string>
        Specifies a verb to be used when starting the process, such as Edit, Open, or Print.

        Each file type has a set of verbs that you can use. To find the verbs that can be used with the process, use the Verbs property of the object.

        Required?                    false
        Position?                    named
        Default value
        Accept pipeline input?     false
        Accept wildcard characters? false

    -Wait [<SwitchParameter>]
        Waits for the specified process to complete before accepting more input. This parameter suppresses the command prompt or retains the window until the process completes.

        Required?                    false
        Position?                    named
        Default value                False
        Accept pipeline input?     false
        Accept wildcard characters? false

    -WindowStyle <ProcessWindowStyle>
        Specifies the state of the windows used for the process. Valid values are Normal, Hidden, Minimized, and Maximized. The default value is Normal.

        Required?                    false
        Position?                    named
        Default value                Normal
        Accept pipeline input?     false
        Accept wildcard characters? false

    -WorkingDirectory <string>
        Specifies the location of the executable file or document that runs in the process. The default is the current directory.

        Required?                    false
        Position?                    named
        Default value                Current directory
        Accept pipeline input?     false
        Accept wildcard characters? false

    <CommonParameters>
        This cmdlet supports the common parameters: Verbose, Debug,
        ErrorAction, ErrorVariable, WarningAction, WarningVariable,
        OutBuffer and OutVariable. For more information, type,
        “Get-Help about_CommonParameters“.

INPUTS
    None
        You cannot pipe input to Start-Process.

OUTPUTS
    None or System.Diagnostics.Process
        When you use the PassThru parameter, Start-Process generates a System.Diagnostics.Process. Otherwise, this cmdlet does not return any output.

NOTES

        This cmdlet is implemented by using the Start method of the System.Diagnostics,Process class. For more information about this method, see “Process.Start Method” in the MSDN (Microsoft Developer Network) library at http://go.microsoft.com/fwlink/?LinkId=143602.

    ————————– EXAMPLE 1 ————————–

    C:\PS>Start-Process sort.exe

    Description
    ———–
    This command starts a process that uses the Sort.exe file in the current directory. The command uses all of the default values, including the default window style, working directory, and credentials.

    ————————– EXAMPLE 2 ————————–

    C:\PS>Start-Process myfile.txt -WorkingDirectory “C:\PS-Test” -verb Print

    Description
    ———–
    This command starts a process that prints the C:\PS-Test\MyFile.txt file.

    ————————– EXAMPLE 3 ————————–

    C:\PS>Start-Process Sort.exe -RedirectStandardInput Testsort.txt -RedirectStandardOutput Sorted.txt -RedirectStandardError SortError.txt -UseNewEnvironment

    Description
    ———–
    This command starts a process that sorts items in the Testsort.txt file and returns the sorted items in the Sorted.txt files. Any errors are written to the SortError.txt file.

    The UseNewEnvironment parameter specifies that the process runs with its own Environment Variables.

    ————————– EXAMPLE 4 ————————–

    C:\PS>Start-Process notepad -Wait -windowstyle Maximized

    Description
    ———–
    This command starts the Notepad process. It maximizes the window and retains the window until the process completes.

RELATED LINKS
    Online version: http://go.microsoft.com/fwlink/?LinkID=135261
    Start-Service
    Get-Process
    Stop-Process
    Wait-Process
    Debug-Process

New-Object

NAME
    New-Object

SYNOPSIS
    Creates an instance of a Microsoft .NET Framework or COM object.

SYNTAX
    New-Object -ComObject <string> [-Strict] [-Property <hashtable>] [<CommonParameters>]

    New-Object [-TypeName] <string> [[-ArgumentList] <Object[]>] [-Property <hashtable>] [<CommonParameters>]

DESCRIPTION
    The New-Object cmdlet creates an instance of a .NET Framework or COM object.

    You can specify either the type of a .NET Framework class or a ProgID of a COM object. By default, you type the fully qualified name of a .NET Framework class and the cmdlet returns a reference to an instance of that class. To create an instance of a COM object, use the ComObject parameter and specify the ProgID of the object as its value.

PARAMETERS
    -ArgumentList <Object[]>
        Specifies a list of arguments to pass to the constructor of the .NET Framework class. Separate elements in the list by using commas (,). The Alias for ArgumentList is Args.

        Required?                    false
        Position?                    2
        Default value
        Accept pipeline input?     false
        Accept wildcard characters? false

    -ComObject <string>
        Specifies the programmatic identifier (ProgID) of the COM object.

        Required?                    true
        Position?                    named
        Default value                None
        Accept pipeline input?     false
        Accept wildcard characters? false

    -Property <hashtable>
        Sets property values and invokes methods of the new object.

        Enter a hash table in which the keys are the names of properties or methods and the values are property values or method arguments. New-Object creates the object and sets each property value and invokes each method in the order that they appear in the hash table.

        If the new object is derived from the PSObject class, and you specify a property that does not exist on the object, New-Object adds the specified property to the object as a NoteProperty. If the object is not a PSObject, the command generates a non-terminating error.

        Required?                    false
        Position?                    named
        Default value
        Accept pipeline input?     false
        Accept wildcard characters? false

    -Strict [<SwitchParameter>]
        Specifies that an error should be raised if the COM object that you attempt to create uses an interop assembly. This enables you to distinguish actual COM objects from .NET Framework objects with COM-callable wrappers.

        Required?                    false
        Position?                    named
        Default value
        Accept pipeline input?     false
        Accept wildcard characters? false

    -TypeName <string>
        Specifies the fully qualified name of the .NET Framework class. You cannot specify both the TypeName parameter and the ComObject parameter.

        Required?                    true
        Position?                    1
        Default value
        Accept pipeline input?     false
        Accept wildcard characters? false

    <CommonParameters>
        This cmdlet supports the common parameters: Verbose, Debug,
        ErrorAction, ErrorVariable, WarningAction, WarningVariable,
        OutBuffer and OutVariable. For more information, type,
        “Get-Help about_CommonParameters“.

INPUTS
    None
        You cannot pipe input to this cmdlet.

OUTPUTS
    Object
        New-Object returns the object that is created.

NOTES

        New-Object provides the most commonly-used Functionality of the VBScript CreateObject Function. A statement like Set objShell = CreateObject(“Shell.Application”) in VBScript can be translated to $objShell = New-Object -comobject “Shell.Application” in Windows PowerShell.

        New-Object expands upon the Functionality available in the Windows Script Host Environment by making it easy to work with .NET Framework objects from the command line and within scripts.

    ————————– EXAMPLE 1 ————————–

    C:\PS>New-Object -TypeName System.Version -ArgumentList “1.2.3.4”

    Major Minor Build Revision
    —– —– —– ——–
    1     2     3     4

    Description
    ———–
    This command creates a System.Version object using the string “1.2.3.4” as the constructor.

    ————————– EXAMPLE 2 ————————–

    C:\PS>$ie = New-Object -comobject InternetExplorer.Application -Property @{navigate2=”www.microsoft.com”; visible = $true}

    Description
    ———–
    This command creates an instance of the COM object that represents the Internet Explorer application. It uses the Property parameter to call the Navigate2 method and to set the Visible property of the object to $true to make the application visible.

    This command is the equivalent of the following:

    $ie = New-Object -comobject InternetExplorer.Application
    $ie.navigate2(“www.microsoft.com”)
    $ie.visible = $true

    ————————– EXAMPLE 3 ————————–

    C:\PS>$a=New-Object -comobject Word.Application -strict -Property @{visible=$true}

    New-Object : The object written to the pipeline is an instance of the type
    “Microsoft.Office.Interop.Word.ApplicationClass” from the component’s prima
    ry interop assembly. If this type exposes different members than the IDispa
    tch members, scripts written to work with this object might not work if the
     primary interop assembly is not installed.
    At line:1 char:14
    + $a=New-Object <<<< -COM Word.Application -Strict; $a.visible=$true

    Description
    ———–
    This command demonstrates that specifying the Strict parameter causes the New-Object cmdlet to generate a non-terminating error when the COM object that is created uses an interop assembly.

    ————————– EXAMPLE 4 ————————–

    C:\PS>$objshell = New-Object -comobject “Shell.Application”

    C:\PS> $objshell | Get-Member

    C:\PS> $objshell.ToggleDesktop()

    Description
    ———–
    The command uses the ComObject parameter to create a COM object with the “Shell.Application” ProgID. It stores the resulting object in the $objShell Variable.

    The second command pipes the $objShell Variable to the Get-Member cmdlet, which displays the properties and methods of the COM object.

    The third command calls the ToggleDesktop method of the object to minimize the open windows on your desktop.

RELATED LINKS
    Online version: http://go.microsoft.com/fwlink/?LinkID=113355
    Compare-Object
    Select-Object
    Sort-Object
    ForEach-Object
    Group-Object
    Measure-Object
    Tee-Object
    Where-Object

Invoke-WmiMethod

NAME
    Invoke-WmiMethod

SYNOPSIS
    Calls Windows Management Instrumentation (WMI) methods.

SYNTAX
    Invoke-WmiMethod [-Class] <string> [[-ArgumentList] <Object[]>] [-Authentication {Default | None | Connect | Call | Packet | PacketIntegrity | PacketPrivacy | Unchanged}] [-Authority <string>] [-ComputerName <string[]>] [-Credential <PSCredential>] [-EnableAllPrivileges] [-Impersonation {Default | Anonymous | Identify | Impersonate | Delegate}] [-Locale <string>] [-Namespace <string>] [-Name] <string> [-AsJob] [-ThrottleLimit <int>] [-Confirm] [-WhatIf] [<CommonParameters>]

    Invoke-WmiMethod [-Authentication {Default | None | Connect | Call | Packet | PacketIntegrity | PacketPrivacy | Unchanged}] [-Authority <string>] [-ComputerName <string[]>] [-Credential <PSCredential>] [-EnableAllPrivileges] [-Impersonation {Default | Anonymous | Identify | Impersonate | Delegate}] [-Locale <string>] [-Namespace <string>] [-Name] <string> [-AsJob] [-ThrottleLimit <int>] [-Confirm] [-WhatIf] [<CommonParameters>]

    Invoke-WmiMethod -InputObject <ManagementObject> [-ArgumentList <Object[]>] [-Name] <string> [-AsJob] [-ThrottleLimit <int>] [-Confirm] [-WhatIf] [<CommonParameters>]

    Invoke-WmiMethod -Path <string> [-ArgumentList <Object[]>] [-Authentication {Default | None | Connect | Call | Packet | PacketIntegrity | PacketPrivacy | Unchanged}] [-Authority <string>] [-ComputerName <string[]>] [-Credential <PSCredential>] [-EnableAllPrivileges] [-Impersonation {Default | Anonymous | Identify | Impersonate | Delegate}] [-Locale <string>] [-Namespace <string>] [-Name] <string> [-AsJob] [-ThrottleLimit <int>] [-Confirm] [-WhatIf] [<CommonParameters>]

    Invoke-WmiMethod [-Authentication {Default | None | Connect | Call | Packet | PacketIntegrity | PacketPrivacy | Unchanged}] [-Authority <string>] [-ComputerName <string[]>] [-Credential <PSCredential>] [-EnableAllPrivileges] [-Impersonation {Default | Anonymous | Identify | Impersonate | Delegate}] [-Locale <string>] [-Namespace <string>] [-Name] <string> [-AsJob] [-ThrottleLimit <int>] [-Confirm] [-WhatIf] [<CommonParameters>]

    Invoke-WmiMethod [-Authentication {Default | None | Connect | Call | Packet | PacketIntegrity | PacketPrivacy | Unchanged}] [-Authority <string>] [-ComputerName <string[]>] [-Credential <PSCredential>] [-EnableAllPrivileges] [-Impersonation {Default | Anonymous | Identify | Impersonate | Delegate}] [-Locale <string>] [-Namespace <string>] [-Name] <string> [-AsJob] [-ThrottleLimit <int>] [-Confirm] [-WhatIf] [<CommonParameters>]

DESCRIPTION
    The Invoke-WmiMethod cmdlet calls WMI methods.

PARAMETERS
    -ArgumentList <Object[]>
        Specifies the parameters to pass to the called method. The value of this parameter must be an array of objects and they must appear in the order required by the called method.

        Important: A second value of $null is required, otherwise the command will generate an error, such as “Unable to cast object of type ‘System.Byte’ to type ‘System.Array’.”.

        An example using an array of objects ($binSD) followed by a null value ($null) follows:

        PS C:\> $acl = Get-Acl test.txt
        PS C:\> $binSD = $acl.GetSecurityDescriptorBinaryForm()
        PS C:\> Invoke-WmiMethod -Class Win32_SecurityDescriptorHelper -Name BinarySDToSDDL -ArgumentList $binSD, $null

        Required?                    false
        Position?                    named
        Default value
        Accept pipeline input?     false
        Accept wildcard characters? false

    -AsJob [<SwitchParameter>]
        Runs the command as a background job. Use this parameter to run commands that take a long time to finish.

        When you use the AsJob parameter, the command returns an object that represents the background job and then displays the command prompt. You can continue to work in the session while the job finishes. If Invoke-WmiMethod is used against a remote computer, the job is created on the local computer, and the results from remote computers are automatically returned to the local computer. To manage the job, use the cmdlets that contain the Job noun (the Job cmdlets). To get the job results, use the Receive-Job cmdlet.

        Note: To use this parameter with remote computers, the local and remote computers must be configured for remoting. Additionally, you must start Windows PowerShell by using the “Run as administrator” option in Windows Vista and later versions of Windows. For more information, see about_remote_requirements.

        For more information about Windows PowerShell background jobs, see about_jobs and about_remote_Jobs.

        Required?                    false
        Position?                    named
        Default value
        Accept pipeline input?     false
        Accept wildcard characters? false

    -Authentication <AuthenticationLevel>
        Specifies the authentication level to be used with the WMI connection. Valid values are:

        -1: Unchanged
        0: Default
        1: None (No authentication in performed.)
        2: Connect (Authentication is performed only when the client establishes a relationship with the application.)
        3: Call (Authentication is performed only at the beginning of each call when the application receives the request.)
        4: Packet (Authentication is performed on all the data that is received from the client.)
        5: PacketIntegrity (All the data that is transferred between the client and the application is authenticated and verified.)
        6: PacketPrivacy (The properties of the other authentication levels are used, and all the data is encrypted.)

        Required?                    false
        Position?                    named
        Default value
        Accept pipeline input?     false
        Accept wildcard characters? false

    -Authority <string>
        Specifies the authority to use to authenticate the WMI connection. You can specify standard NTLM or Kerberos authentication. To use NTLM, set the authority setting to ntlmdomain:<DomainName>, where <DomainName> identifies a valid NTLM domain name. To use Kerberos, specify kerberos:<DomainName\ServerName>. You cannot include the authority setting when you connect to the local computer.

        Required?                    false
        Position?                    named
        Default value
        Accept pipeline input?     false
        Accept wildcard characters? false

    -Class <string>
        Specifies the WMI class that contains a static method to call.

        Required?                    true
        Position?                    1
        Default value
        Accept pipeline input?     false
        Accept wildcard characters? false

    -ComputerName <string[]>
        Specifies the computer against which you want to run the management operation. The value can be a fully qualified domain name, a NetBIOS name, or an Internet Protocol (IP) address. Use the local computer name, use localhost, or use a dot (.) to specify the local computer. The local computer is the default. When the remote computer is in a different domain from the user, a fully qualified domain name is required. You can also set the value of this parameter by piping the value to the parameter.

        Required?                    false
        Position?                    named
        Default value
        Accept pipeline input?     false
        Accept wildcard characters? false

    -Credential <PSCredential>
        Specifies a user account that has permission to perform this action. The default is the current user. Type a user name, such as “User01”, “Domain01\User01”, or User@Contoso.com. Or, enter a PSCredential object, such as an object that is returned by the Get-Credential cmdlet. When you type a user name, you will be prompted for a password.

        Required?                    false
        Position?                    named
        Default value
        Accept pipeline input?     false
        Accept wildcard characters? false

    -EnableAllPrivileges [<SwitchParameter>]
        Enables all the privileges of the current user before the command makes the WMI call.

        Required?                    false
        Position?                    named
        Default value
        Accept pipeline input?     false
        Accept wildcard characters? false

    -Impersonation <ImpersonationLevel>
        Specifies the impersonation level to use. Valid values are:

        0: Default (Reads the local Registry for the default impersonation level, which is usually set to “3: Impersonate”.)
        1: Anonymous (Hides the credentials of the caller.)
        2: Identify (Allows objects to query the credentials of the caller.)
        3: Impersonate (Allows objects to use the credentials of the caller.)
        4: Delegate (Allows objects to permit other objects to use the credentials of the caller.)

        Required?                    false
        Position?                    named
        Default value
        Accept pipeline input?     false
        Accept wildcard characters? false

    -InputObject <ManagementObject>
        Specifies a ManagementObject object to use as input. When this parameter is used, all other parameters except the Flag and Argument parameters are ignored.

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

    -Locale <string>
        Specifies the preferred locale for WMI objects. Specify the value of the Locale parameter as an array in the MS_<LCID> format in the preferred order.

        Required?                    false
        Position?                    named
        Default value
        Accept pipeline input?     false
        Accept wildcard characters? false

    -Name <string>
        Specifies the name of the method to be invoked. This parameter is mandatory and cannot be null or empty.

        Required?                    true
        Position?                    2
        Default value
        Accept pipeline input?     false
        Accept wildcard characters? false

    -Namespace <string>
        When used with the Class parameter, this parameter specifies the WMI repository namespace where the referenced WMI class or object is located.

        Required?                    false
        Position?                    named
        Default value
        Accept pipeline input?     false
        Accept wildcard characters? false

    -Path <string>
        Specifies the WMI object path of a WMI class, or specifies the WMI object path of an instance of a WMI class. The class or the instance that you specify must contain the method that is specified in the Name parameter.

        Required?                    true
        Position?                    named
        Default value
        Accept pipeline input?     false
        Accept wildcard characters? false

    -ThrottleLimit <int>
        Allows the user to specify a throttling value for the number of WMI operations that can be executed simultaneously. This parameter is used together with the AsJob parameter. The throttle limit applies only to the current command, not to the session or to the computer.

        Required?                    false
        Position?                    named
        Default value
        Accept pipeline input?     false
        Accept wildcard characters? false

    -Confirm [<SwitchParameter>]
        Prompts you for confirmation before executing the command.

        Required?                    false
        Position?                    named
        Default value
        Accept pipeline input?     false
        Accept wildcard characters? false

    -WhatIf [<SwitchParameter>]
        Describes what would happen if you executed the command without actually executing the command.

        Required?                    false
        Position?                    named
        Default value
        Accept pipeline input?     false
        Accept wildcard characters? false

    <CommonParameters>
        This cmdlet supports the common parameters: Verbose, Debug,
        ErrorAction, ErrorVariable, WarningAction, WarningVariable,
        OutBuffer and OutVariable. For more information, type,
        “Get-Help about_CommonParameters“.

INPUTS
    None
        This cmdlet does not accept any input.

OUTPUTS
    None
        This cmdlet does not generate any output.

NOTES

    ————————– EXAMPLE 1 ————————–

    C:\PS>Invoke-WmiMethod -path win32_process -Name create -ArgumentList notepad.exe

    __GENUS         : 2
    __CLASS         : __PARAMETERS
    __SUPERCLASS     :
    __DYNASTY        : __PARAMETERS
    __RELPATH        :
    __PROPERTY_COUNT : 2
    __DERIVATION     : {}
    __SERVER         :
    __NAMESPACE     :
    __PATH         :
    ProcessId        : 4844
    ReturnValue     : 0

    Description
    ———–
    This command starts an instance of Notepad by calling the Create method of the Win32_Process class.

    Note: The ReturnValue property is populated with a 0, and the ProcessId property is populated with an integer (the next process ID number) if the command is completed.

    ————————– EXAMPLE 2 ————————–

    C:\PS>Invoke-WmiMethod -path “CIM_DataFile.Name=’C:\scripts\test.txt'” -Name Rename -ArgumentList “C:\scripts\test_bu.txt”

    __GENUS         : 2
    __CLASS         : __PARAMETERS
    __SUPERCLASS     :
    __DYNASTY        : __PARAMETERS
    __RELPATH        :
    __PROPERTY_COUNT : 1
    __DERIVATION     : {}
    __SERVER         :
    __NAMESPACE     :
    __PATH         :
    ReturnValue     : 0

    Description
    ———–
    This command renames a file. It uses the Path parameter to reference an instance of the CIM_DataFile class. Then, it applies the Rename method to that particular instance.

    Note: The ReturnValue property is populated with a 0 if the command is completed.

RELATED LINKS
    Online version: http://go.microsoft.com/fwlink/?LinkID=113346
    Get-WmiObject
    Remove-WmiObject
    Set-WmiInstance
    Get-WSManInstance
    Invoke-WSManAction
    New-WSManInstance
    Remove-WSManInstance

New-Module

NAME
    New-Module

SYNOPSIS
    Creates a new dynamic module that exists only in memory.

SYNTAX
    New-Module [-Name] <string> [-ScriptBlock] <scriptblock> [-ArgumentList <Object[]>] [-AsCustomObject] [-Cmdlet <string[]>] [-Function <string[]>] [-ReturnResult] [<CommonParameters>]

    New-Module [-ScriptBlock] <scriptblock> [-ArgumentList <Object[]>] [-AsCustomObject] [-Cmdlet <string[]>] [-Function <string[]>] [-ReturnResult] [<CommonParameters>]

DESCRIPTION
    The New-Module cmdlet creates a dynamic module from a script block. The members of the dynamic module, such as Functions and Variables, are immediately available in the session and remain available until you close the session.

    Like static modules, by default, the cmdlets and Functions in a dynamic module are exported and the Variables and Aliases are not. However, you can use the Export-ModuleMember cmdlet and the parameters of New-Module to override the defaults.

    Dynamic modules exist only in memory, not on disk. Like all modules, the members of dynamic modules run in a private module scope that is a child of the global scope. Get-Module cannot get a dynamic module, but Get-Command can get the exported members.

    To make a dynamic module available to Get-Module, pipe a New-Module command to Import-Module, or pipe the module object that New-Module returns to Import-Module. This action adds the dynamic module to the Get-Module list, but it does not save the module to disk or make it persistent.

PARAMETERS
    -ArgumentList <Object[]>
        Specifies arguments (parameter values) that are passed to the script block.

        Required?                    false
        Position?                    named
        Default value                None
        Accept pipeline input?     false
        Accept wildcard characters? false

    -AsCustomObject [<SwitchParameter>]
        Returns a custom object with members that represent the module members.

        When you use the AsCustomObject parameter, New-Module creates the dynamic module, imports the module members into the current session, and then returns a PSCustomObject object instead of a PSModuleInfo object. You can save the custom object in a Variable and use dot notation to invoke the members.

        If the module has multiple members with the same name, such as a Function and a Variable that are both named “A,” only one member with each name is accessible from the custom object.

        Required?                    false
        Position?                    named
        Default value                None
        Accept pipeline input?     false
        Accept wildcard characters? false

    -Cmdlet <string[]>
        Exports only the specified cmdlets from the module into the current session. Enter a comma-separated list of cmdlets. Wildcard characters are permitted. By default, all cmdlets in the module are exported.

        You cannot define cmdlets in a script block, but a dynamic module can include cmdlets if it imports the cmdlets from a binary module.

        Required?                    false
        Position?                    named
        Default value                None
        Accept pipeline input?     false
        Accept wildcard characters? true

    -Function <string[]>
        Exports only the specified Functions from the module into the current session. Enter a comma-separated list of Functions. Wildcard characters are permitted. By default, all Functions defined in a module are exported.

        Required?                    false
        Position?                    named
        Default value                None
        Accept pipeline input?     false
        Accept wildcard characters? true

    -Name <string>
        Specifies a name for the new module. You can also pipe a module name to New-Module.

        The default value is an autogenerated name that begins with “__DynamicModule_” and is followed by a GUID that specifies the path to the dynamic module.

        Required?                    true
        Position?                    1
        Default value                “__DynamicModule_” + GUID
        Accept pipeline input?     true (ByValue)
        Accept wildcard characters? false

    -ReturnResult [<SwitchParameter>]
        Runs the script block and returns the script block results instead of returning a module object.

        Required?                    false
        Position?                    named
        Default value                False
        Accept pipeline input?     false
        Accept wildcard characters? false

    -ScriptBlock <scriptblock>
        Specifies the contents of the dynamic module. Enclose the contents in braces ( { } ) to create a script block. This parameter is required.

        Required?                    true
        Position?                    1
        Default value                None
        Accept pipeline input?     false
        Accept wildcard characters? false

    <CommonParameters>
        This cmdlet supports the common parameters: Verbose, Debug,
        ErrorAction, ErrorVariable, WarningAction, WarningVariable,
        OutBuffer and OutVariable. For more information, type,
        “Get-Help about_CommonParameters“.

INPUTS
    System.String
        You can pipe a module name string to New-Module.

OUTPUTS
    System.Management.Automation.PSModuleInfo, System.Management.Automation.PSCustomObject, or None
        By default, New-Module generates a PSModuleInfo object. If you use the AsCustomObject parameter, it generates a PSCustomObject object. If you use the ReturnResult parameter, it returns the result of evaluating the script block in the dynamic module.

NOTES

        You can also refer to New-Module by its Alias, “nmo”. For more information, see about_aliases.

    ————————– EXAMPLE 1 ————————–

    C:\PS>New-Module -ScriptBlock {function Hello {“Hello!”}}

    Name             : __DynamicModule_2ceb1d0a-990f-45e4-9fe4-89f0f6ead0e5
    Path             : 2ceb1d0a-990f-45e4-9fe4-89f0f6ead0e5
    Description     :
    Guid             : 00000000-0000-0000-0000-000000000000
    Version         : 0.0
    ModuleBase        :
    ModuleType        : Script
    PrivateData     :
    AccessMode        : ReadWrite
    ExportedAliases : {}
    ExportedCmdlets : {}
    ExportedFunctions : {[Hello, Hello]}
    ExportedVariables : {}
    NestedModules     : {}

    Description
    ———–
    This command creates a new dynamic module with a Function called “Hello”. The command returns a module object that represents the new dynamic module.

    ————————– EXAMPLE 2 ————————–

    C:\PS>New-Module -ScriptBlock {function Hello {“Hello!”}}

    Name             : __DynamicModule_2ceb1d0a-990f-45e4-9fe4-89f0f6ead0e5
    Path             : 2ceb1d0a-990f-45e4-9fe4-89f0f6ead0e5
    Description     :
    Guid             : 00000000-0000-0000-0000-000000000000
    Version         : 0.0
    ModuleBase        :
    ModuleType        : Script
    PrivateData     :
    AccessMode        : ReadWrite
    ExportedAliases : {}
    ExportedCmdlets : {}
    ExportedFunctions : {[Hello, Hello]}
    ExportedVariables : {}
    NestedModules     : {}

    C:\PS> Get-Module
    C:\PS>

    C:\PS> Get-Command Hello

    CommandType     Name Definition
    ———–     —- ———-
    Function        Hello “Hello!”

    Description
    ———–
    This example demonstrates that dynamic modules are not returned by the Get-Module cmdlet, but the members that they export are returned by the Get-Command cmdlet.

    ————————– EXAMPLE 3 ————————–

    C:\PS>New-Module -ScriptBlock {$SayHelloHelp=”Type ‘SayHello’, a space, and a name.”; Function SayHello ($name) { “Hello, $name” }; Export-ModuleMember -Function SayHello -Variable SayHelloHelp}

    C:\PS> $SayHelloHelp
    Type ‘SayHello’, a space, and a name.

    C:\PS> SayHello Jeffrey
    Hello, Jeffrey

    Description
    ———–
    This command uses the Export-ModuleMember cmdlet to export a Variable into the current session. Without the Export-ModuleMember command, only the Function is exported.

    The output shows that both the Variable and the Function were exported into the session.

    ————————– EXAMPLE 4 ————————–

    C:\PS>New-Module -ScriptBlock {function Hello {“Hello!”}} -name GreetingModule | Import-Module

    C:\PS> Get-Module

    Name             : GreetingModule
    Path             : d54dfdac-4531-4db2-9dec-0b4b9c57a1e5
    Description     :
    Guid             : 00000000-0000-0000-0000-000000000000
    Version         : 0.0
    ModuleBase        :
    ModuleType        : Script
    PrivateData     :
    AccessMode        : ReadWrite
    ExportedAliases : {}
    ExportedCmdlets : {}
    ExportedFunctions : {[Hello, Hello]}
    ExportedVariables : {}
    NestedModules     : {}

    C:\PS> Get-Command hello

    CommandType     Name                                                             Definition
    ———–     —-                                                             ———-
    Function        Hello                                                             “Hello!”

    Description
    ———–
    This command demonstrates that you can make a dynamic module available to the Get-Module cmdlet by piping the dynamic module to the Import-Module cmdlet.

    The first command uses a pipeline operator (|) to send the module object that New-Module generates to the Import-Module cmdlet. The command uses the Name parameter of New-Module to assign a friendly name to the module. Because Import-Module does not return any objects by default, there is no output from this command.

    The second command uses the Get-Module cmdlet to get the modules in the session. The result shows that Get-Module can get the new dynamic module.

    The third command uses the Get-Command cmdlet to get the Hello Function that the dynamic module exports.

    ————————– EXAMPLE 5 ————————–

    C:\PS>$m = New-Module -ScriptBlock {function Hello ($name) {“Hello, $name”}; Function Goodbye ($name) {“Goodbye, $name”}} -AsCustomObject

    C:\PS> $m

    C:\PS> $m | Get-Member

     TypeName: System.Management.Automation.PSCustomObject

    Name        MemberType Definition
    —-        ———- ———-
    Equals     Method     bool Equals(System.Object obj)
    GetHashCode Method     int GetHashCode()
    GetType     Method     type GetType()
    ToString    Method     string ToString()
    Goodbye     ScriptMethod System.Object Goodbye();
    Hello     ScriptMethod System.Object Hello();

    PS C:\ps-test> $m.goodbye(“Jane”)
    Goodbye, Jane

    PS C:\ps-test> $m.hello(“Manoj”)
    Hello, Manoj

    PS C:\ps-test> goodbye Jane
    Goodbye, Jane

    PS C:\ps-test> hello Manoj
    Hello, Manoj

    Description
    ———–
    This example shows how to use the AsCustomObject parameter of New-Module to generate a custom object with script methods that represent the exported Functions.

    The first command uses the New-Module cmdlet to generate a dynamic module with two Functions, Hello and Goodbye. The command uses the AsCustomObject parameter to generate a custom object instead of the PSModuleInfo object that New-Module generates by default. The command saves the custom object in the $m Variable.

    The second command attempts to display the value of the $m Variable. No content appears.

    The third command uses a pipeline operator (|) to send the custom object to the Get-Member cmdlet, which displays the properties and methods of the custom object. The output shows that the object has script methods that represent the Hello and Goodbye Functions.

    The fourth and fifth commands use the script method format to call the Hello and Goodbye Functions.

    The sixth and seventh commands call the Functions by specifying the Function name and parameter value.

    ————————– EXAMPLE 6 ————————–

    C:\PS>New-Module -ScriptBlock {function SayHello {“Hello, World!”}; SayHello} -ReturnResult

    Hello, World!

    Description
    ———–
    This command uses the ReturnResult parameter to request the results of running the script block instead of requesting a module object.

    The script block in the new module defines the SayHello Function and then calls the Function.

RELATED LINKS
    Online version: http://go.microsoft.com/fwlink/?LinkID=141554
    Get-Module
    Import-Module
    Remove-Module
    Export-ModuleMember
    about_modules

Import-Module

NAME
    Import-Module

SYNOPSIS
    Adds modules to the current session.

SYNTAX
    Import-Module [-Name] <string[]> [-Alias <string[]>] [-ArgumentList <Object[]>] [-AsCustomObject] [-Cmdlet <string[]>] [-Force] [-Function <string[]>] [-Global] [-PassThru] [-Prefix <string>] [-Variable <string[]>] [-Version <Version>] [<CommonParameters>]

    Import-Module [-Assembly] <Assembly[]> [-Alias <string[]>] [-ArgumentList <Object[]>] [-AsCustomObject] [-Cmdlet <string[]>] [-Force] [-Function <string[]>] [-Global] [-PassThru] [-Prefix <string>] [-Variable <string[]>] [-Version <Version>] [<CommonParameters>]

    Import-Module [-ModuleInfo] <PSModuleInfo[]> [-Alias <string[]>] [-ArgumentList <Object[]>] [-AsCustomObject] [-Cmdlet <string[]>] [-Force] [-Function <string[]>] [-Global] [-PassThru] [-Prefix <string>] [-Variable <string[]>] [-Version <Version>] [<CommonParameters>]

DESCRIPTION
    The Import-Module cmdlet adds one or more modules to the current session.

    A module is a package that contains members (such as cmdlets, providers, scripts, Functions, Variables, and other tools and files) that can be used in Windows PowerShell. After a module is imported, you can use the module members in your session.

    To import a module, use the Name, Assembly, or ModuleInfo parameter to identify the module to import. By default, Import-Module imports all members that the module exports, but you can use the Alias, Function, Cmdlet, and Variable parameters to restrict the members that are imported.

    Import-Module imports a module only into the current session. To import the module into all sessions, add an Import-Module command to your Windows PowerShell profile. For more information about profiles, see about_profiles.

    For more information about modules, see about_modules.

PARAMETERS
    -Alias <string[]>
        Imports only the specified Aliases from the module into the current session. Enter a comma-separated list of Aliases. Wildcard characters are permitted.

        Some modules automatically export selected Aliases into your session when you import the module. This parameter lets you select from among the exported Aliases.

        Required?                    false
        Position?                    named
        Default value
        Accept pipeline input?     false
        Accept wildcard characters? true

    -ArgumentList <Object[]>
        Specifies arguments (parameter values) that are passed to a script module during the Import-Module command. This parameter is valid only when you are importing a script module.

        You can also refer to ArgumentList by its Alias, “args”. For more information, see about_aliases.

        Required?                    false
        Position?                    named
        Default value
        Accept pipeline input?     false
        Accept wildcard characters? false

    -AsCustomObject [<SwitchParameter>]
        Returns a custom object with members that represent the imported module members. This parameter is valid only for script modules.

        When you use the AsCustomObject parameter, Import-Module imports the module members into the session and then returns a PSCustomObject object instead of a PSModuleInfo object. You can save the custom object in a Variable and use dot notation to invoke the members.

        Required?                    false
        Position?                    named
        Default value
        Accept pipeline input?     false
        Accept wildcard characters? false

    -Assembly <Assembly[]>
        Imports the cmdlets and providers implemented in the specified assembly objects. Enter a Variable that contains assembly objects or a command that creates assembly objects. You can also pipe an assembly object to Import-Module.

        When you use this parameter, only the cmdlets and providers implemented by the specified assemblies are imported. If the module contains other files, they are not imported, and you might be missing important members of the module. Use this parameter for debugging and testing the module, or when you are instructed to use it by the module author.

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

    -Cmdlet <string[]>
        Imports only the specified cmdlets from the module into the current session. Enter a list of cmdlets. Wildcard characters are permitted.

        Some modules automatically export selected cmdlets into your session when you import the module. This parameter lets you select from among the exported cmdlets.

        Required?                    false
        Position?                    named
        Default value
        Accept pipeline input?     false
        Accept wildcard characters? true

    -Force [<SwitchParameter>]
        Re-imports a module and its members, even if the module or its members have an access mode of read-only.

        Required?                    false
        Position?                    named
        Default value                False
        Accept pipeline input?     false
        Accept wildcard characters? false

    -Function <string[]>
        Imports only the specified Functions from the module into the current session. Enter a list of Functions. Wildcard characters are permitted.

        Some modules automatically export selected Functions into your session when you import the module. This parameter lets you select from among the exported Functions.

        Required?                    false
        Position?                    named
        Default value
        Accept pipeline input?     false
        Accept wildcard characters? true

    -Global [<SwitchParameter>]
        When used in a script module (.psm1), this parameter imports modules into the global session state.

        This parameter is effective only when it appears in a script module. Otherwise, it is ignored.

        By default, the commands in a script module, including commands from nested modules, are imported into the caller’s session state. To restrict the commands that a module exports, use an Export-ModuleMember command in the script module.

        Required?                    false
        Position?                    named
        Default value
        Accept pipeline input?     false
        Accept wildcard characters? false

    -ModuleInfo <PSModuleInfo[]>
        Specifies module objects to import. Enter a Variable that contains the module objects, or a command that gets the module objects, such as a “Get-Module -listavailable” command. You can also pipe module objects to Import-Module.

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

    -Name <string[]>
        Specifies the names of the modules to import. Enter the name of the module or the name of a file in the module, such as a .psd1, .psm1, .dll, or ps1 file. File paths are optional. Wildcards are not permitted. You can also pipe module names and file names to Import-Module.

        If you omit a path, Import-Module looks for the module in the paths saved in the PSModulePath Environment Variable ($env:PSModulePath).

        Specify only the module name whenever possible. When you specify a file name, only the members that are implemented in that file are imported. If the module contains other files, they are not imported, and you might be missing important members of the module.

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

    -PassThru [<SwitchParameter>]
        Returns objects that represent the modules that were imported. By default, this cmdlet does not generate any output.

        Notes
        — When you pipe the output of a “Get-Module -listavailable” command to an Import-Module command with the PassThru parameter, Import-Module returns the object that Get-Module passed to it without updating the object. As a result, the Exported and NestedModules properties are not yet populated.

        — When you use the Prefix parameter to specify a prefix for the member, the prefix does not appear in the member names in the properties of the module object. The object records what was exported before the prefix was applied.

        Required?                    false
        Position?                    named
        Default value
        Accept pipeline input?     false
        Accept wildcard characters? false

    -Prefix <string>
        Adds the specified prefix to the nouns in the names of imported module members.

        Use this parameter to avoid name conflicts that might occur when different members in the session have the same name. This parameter does not change the module, and it does not affect files that the module imports for its own use (known as “nested modules”). It affects only the names of members in the current session.

        For example, if you specify the prefix “UTC” and then import a Get-Date cmdlet, the cmdlet is known in the session as Get-UTCDate, and it is not confused with the original Get-Date cmdlet.

        Required?                    false
        Position?                    named
        Default value
        Accept pipeline input?     false
        Accept wildcard characters? false

    -Variable <string[]>
        Imports only the specified Variables from the module into the current session. Enter a list of Variables. Wildcard characters are permitted.

        Some modules automatically export selected Variables into your session when you import the module. This parameter lets you select from among the exported Variables.

        Required?                    false
        Position?                    named
        Default value
        Accept pipeline input?     false
        Accept wildcard characters? true

    -Version <Version>
        Specifies the version of the module to import. Use this parameter when you have different versions of the same module on your system.

        Required?                    false
        Position?                    named
        Default value
        Accept pipeline input?     false
        Accept wildcard characters? false

    <CommonParameters>
        This cmdlet supports the common parameters: Verbose, Debug,
        ErrorAction, ErrorVariable, WarningAction, WarningVariable,
        OutBuffer and OutVariable. For more information, type,
        “Get-Help about_CommonParameters“.

INPUTS
    System.String, System.Management.Automation.PSModuleInfo, System.Reflection.Assembly
        You can pipe a module name, module object, or assembly object to Import-Module.

OUTPUTS
    None, System.Management.Automation.PSModuleInfo, or System.Management.Automation.PSCustomObject
        By default, Import-Module does not generate any output. If you use the PassThru parameter, it generates a System.Management.Automation.PSModuleInfo object that represents the module. If you use the AsCustomObject parameter, it generates a PSCustomObject object.

NOTES

        You can also refer to Import-Module by its Alias, “ipmo”. For more information, see about_aliases.

        Before you can import a module, the module directory must be copied to a directory that is accessible to your local computer. For more information, see about_modules.

        Module members run in their own private module session state, so the commands that they use for internal processing do not affect your session state.

        If you import members with the same name and the same type into your session, Windows PowerShell uses the member imported last by default. Variables and Aliases are replaced, and the originals are not accessible. Functions, cmdlets and providers are merely “shadowed” by the new members, and they can be accessed by qualifying the command name with the name of its snap-in, module, or Function path.

        To update the formatting data for commands that have been imported from a module, use the Update-FormatData cmdlet. Update-FormatData also updates the formatting data for commands in the session that were imported from modules. If the formatting file for a module changes, you can run an Update-FormatData command to update the formatting data for imported commands. You do not need to import the module again.

        To import a module that is created by Import-PSSession or Export-PSSession, the execution policy in the current session cannot be Restricted or AllSigned, because the modules that Import-PSSession and Export-PSSession create contains unsigned script files that are prohibited by these policies. To use Import-Module without changing the execution policy for the local computer, use the Scope parameter of Set-ExecutionPolicy to set a less restrictive execution policy for a single process.

    ————————– EXAMPLE 1 ————————–

    C:\PS>Import-Module -Name BitsTransfer

    Description
    ———–
    This command imports the members of the BitsTransfer module into the current session.

    The Name parameter name (-Name) is optional and can be omitted.

    By default, Import-Module does not generate any output when it imports a module. To request output, use the PassThru or AsCustomObject parameter, or the Verbose common parameter.

    ————————– EXAMPLE 2 ————————–

    C:\PS>Get-Module -listAvailable | Import-Module

    Description
    ———–
    This command imports all available modules in the path specified by the PSModulePath Environment Variable ($env:psmodulepath) into the current session.

    ————————– EXAMPLE 3 ————————–

    C:\PS>$m = Get-Module -ListAvailable BitsTransfer, ServerBackup

    C:\PS> Import-Module -moduleInfo $m

    Description
    ———–
    These commands import the members of the BitsTransfer and ServerBackup modules into the current session.

    The first command uses the Get-Module cmdlet to get PSModuleInfo objects that represent the BitsTransfer and ServerBackup modules. It saves the objects in the $m Variable. The ListAvailable parameter is required when you are getting modules that are not yet imported into the session.

    The second command uses the ModuleInfo parameter of Import-Module to import the modules into the current session.

    These commands are equivalent to using a pipeline operator (|) to send the output of a Get-Module command to Import-Module.

    ————————– EXAMPLE 4 ————————–

    C:\PS>Import-Module -Name c:\ps-test\modules\test -Verbose

    VERBOSE: Loading module from path ‘C:\ps-test\modules\Test\Test.psm1’.
    VERBOSE: Exporting Function ‘my-parm’.
    VERBOSE: Exporting Function ‘get-parm’.
    VERBOSE: Exporting Function ‘get-spec’.
    VERBOSE: Exporting Function ‘get-specDetails’.

    Description
    ———–
    This command uses an explicit path to identify the module to import.

    It also uses the Verbose common parameter to get a list of the items imported from the module. Without the Verbose, PassThru, or AsCustomObject parameter, Import-Module does not generate any output when it imports a module.

    ————————– EXAMPLE 5 ————————–

    C:\PS>Import-Module BitsTransfer -Cmdlet Add-BitsTransferFile, Get-BitsTransfer

    C:\PS> Get-Module BitsTransfer

    Name             : BitsTransfer
    Path             : C:\Windows\system32\WindowsPowerShell\v1.0\Modules\BitsTransfer\BitsTransfer.psd1
    Description     :
    Guid             : 8fa5064b-8479-4c5c-86ea-0d311fe48875
    Version         : 1.0.0.0
    ModuleBase        : C:\Windows\system32\WindowsPowerShell\v1.0\Modules\BitsTransfer
    ModuleType        : Manifest
    PrivateData     :
    AccessMode        : ReadWrite
    ExportedAliases : {}
    ExportedCmdlets : {[Add-BitsTransfer, Add-BitsTransfer], [Complete-BitsTransfer, Complete-BitsTransfer], [Get-BitsTransfer, Get-BitsTransfer], [Rem
                        ove-BitsTransfer, Remove-BitsTransfer]…}
    ExportedFunctions : {}
    ExportedVariables : {}
    NestedModules     : {Microsoft.BackgroundIntelligentTransfer.Management}

    C:\PS> Get-Command -module BitsTransfer

    CommandType Name                Definition
    ———– —-                ———-
    Cmdlet     Add-BitsTransfer    Add-BitsTransfer [-BitsJob] <BitsJob[]> [-Source] <String[]> [[-Destination] <String[]>] [-Verbose] [-Debug] [-ErrorA…
    Cmdlet     Get-BitsTransfer    Get-BitsTransfer [[-Name] <String[]>] [-AllUsers] [-Verbose] [-Debug] [-ErrorAction <ActionPreference>] [-WarningActi…

    Description
    ———–
    This example shows how to restrict the module members that are imported into the session and the effect of this command on the session.

    The first command imports only the Add-BitsTransfer and Get-BitsTransfer cmdlets from the BitsTransfer module. The command uses the Cmdlet parameter to restrict the cmdlets that the module imports. You can also use the Alias, Variable, and Function parameters to restrict other members that a module imports.

    The second command uses the Get-Module cmdlet to get the object that represents the BitsTransfer module. The ExportedCmdlets property lists all of the cmdlets that the module exports, even when they were not all imported.

    The third command uses the Module parameter of the Get-Command cmdlet to get the commands that were imported from the BitsTransfer module. The results confirm that only the Add-BitsTransfer and Get-BitsTransfer cmdlets were imported.

    ————————– EXAMPLE 6 ————————–

    C:\PS>Import-Module BitsTransfer -Prefix PS -PassThru

    Name             : bitstransfer
    Path             : C:\Windows\system32\WindowsPowerShell\v1.0\Modules\bitstransfer\bitstransfer.psd1
    Description     :
    Guid             : 8fa5064b-8479-4c5c-86ea-0d311fe48875
    Version         : 1.0.0.0
    ModuleBase        : C:\Windows\system32\WindowsPowerShell\v1.0\Modules\bitstransfer
    ModuleType        : Manifest
    PrivateData     :
    AccessMode        : ReadWrite
    ExportedAliases : {}
    ExportedCmdlets : {[Add-BitsTransfer, Add-BitsTransfer], [Remove-BitsTransfer, Remove-BitsTransfer], [Complete-BitsTransfer, Complete-BitsTransfer]
                        , [Get-BitsTransfer, Get-BitsTransfer]…}
    ExportedFunctions : {}
    ExportedVariables : {}
    NestedModules     : {Microsoft.BackgroundIntelligentTransfer.Management}

    C:\PS> Get-Command -module bitstransfer

    CommandType     Name                        Definition
    ———–     —-                        ———-
    Cmdlet         Add-PSBitsTransfer         Add-PSBitsTransfer [-BitsJob] <BitsJob[]> [-Source] <String[]> …
    Cmdlet         Complete-PSBitsTransfer     Complete-PSBitsTransfer [-BitsJob] <BitsJob[]> [-Verbose] [-Deb…
    Cmdlet         Get-PSBitsTransfer         Get-PSBitsTransfer [[-Name] <String[]>] [-AllUsers] [-Verbose] …
    Cmdlet         Remove-PSBitsTransfer     Remove-PSBitsTransfer [-BitsJob] <BitsJob[]> [-Verbose] [-Debug
    Cmdlet         Resume-PSBitsTransfer     Resume-PSBitsTransfer [-BitsJob] <BitsJob[]> [-Asynchronous] [-…
    Cmdlet         Set-PSBitsTransfer         Set-PSBitsTransfer [-BitsJob] <BitsJob[]> [-DisplayName <String…
    Cmdlet         Start-PSBitsTransfer        Start-PSBitsTransfer [[-Source] <String[]>] [[-Destination] <St…
    Cmdlet         Suspend-PSBitsTransfer     Suspend-PSBitsTransfer [-BitsJob] <BitsJob[]> [-Verbose] [-Debu…

    Description
    ———–
    These commands import the BitsTransfer module into the current session, add a prefix to the member names, and then display the prefixed member names.

    The first command uses the Import-Module cmdlet to import the BitsTransfer module. It uses the Prefix parameter to add the PS prefix to all members that are imported from the module and the PassThru parameter to return a module object that represents the imported module.

    The module object that the command returns has an ExportedCmdlets property that lists the exported members. The prefix does not appear in the cmdlet names, because it is applied after the members are exported (but before they are imported).

    The second command uses the Get-Command cmdlet to get the members that have been imported from the module. It uses the Module parameter to specify the module. The output shows that the module members were correctly prefixed.

    The prefix that you use applies only to the members in the current session. It does not change the module.

    ————————– EXAMPLE 7 ————————–

    C:\PS>Get-Module -list | Format-Table -property name, moduletype -auto

    Name         ModuleType
    —-         ———-
    Show-Calendar     Script
    BitsTransfer    Manifest
    PSDiagnostics Manifest
    TestCmdlets     Script

    C:\PS> $a = Import-Module -Name Show-Calendar -AsCustomObject

    C:\PS> $a | Get-Member

     TypeName: System.Management.Automation.PSCustomObject

    Name         MemberType Definition
    —-         ———- ———-
    Equals        Method     bool Equals(System.Object obj)
    GetHashCode Method     int GetHashCode()
    GetType     Method     type GetType()
    ToString     Method     string ToString()
    Show-Calendar ScriptMethod System.Object Show-Calendar();

    C:\PS> $a.”show-calendar”()

    Description
    ———–
    These commands demonstrate how to get and use the custom object that Import-Module returns.

    Custom objects include synthetic members that represent each of the imported module members. For example, the cmdlets and Functions in a module are converted to script methods of the custom object.

    Custom objects are very useful in scripting. They are also useful when several imported objects have the same names. Using the script method of an object is equivalent to specifying the fully qualified name of an imported member, including its module name.

    The AsCustomObject parameter can be used only with a script module, so the first task is to determine which of the available modules is a script module.

    The first command uses the Get-Module cmdlet to get the available modules. The command uses a pipeline operator (|) to pass the module objects to the Format-Table cmdlet, which lists the Name and ModuleType of each module in a table.

    The second command uses the Import-Module cmdlet to import the Show-Calendar script module. The command uses the AsCustomObject parameter to request a custom object. The command saves the resulting custom object in the $a Variable.

    The third command uses a pipeline operator to send the $a Variable to the Get-Member cmdlet, which gets the properties and methods of the PSCustomObject in $a. The output shows a Show-Calendar script method.

    The last command uses the Show-Calendar script method. The method name must be enclosed in quotation marks, because it includes a hyphen.

    ————————– EXAMPLE 8 ————————–

    C:\PS>Import-Module BitsTransfer

    C:\PS> Import-Module BitsTransfer -Force -Prefix PS

    Description
    ———–
    This example shows how to use the Force parameter of Import-Module when you are re-importing a module into the same session.

    The first command imports the BitsTransfer module. The second command imports the module again, this time using the Prefix parameter.

    The second command also includes the Force parameter, which removes the module and then imports it again. Without this parameter, the session would include two copies of each BitsTransfer cmdlet, one with the standard name and one with the prefixed name.

    ————————– EXAMPLE 9 ————————–

    C:\PS>Get-Date

    Saturday, September 12, 2009 6:47:04 PM

    C:\PS> Import-Module TestModule

    C:\PS> Get-Date
    09255

    C:\PS> Get-Command Get-Date | Format-Table -property commandtype, name, pssnapin, module -auto

    CommandType Name     pssnapin                     Module
    ———– —-     ——–                     ——
     Function Get-Date                                 TestModule
         Cmdlet Get-Date Microsoft.PowerShell.Utility

    C:\PS> Microsoft.PowerShell.Utility\Get-Date

    Saturday, September 12, 2009 6:33:23 PM

    Description
    ———–
    This example shows how to run commands that have been hidden by imported commands.

    The first command run the Get-Date cmdlet that comes with Windows PowerShell. It returns a DateTime object with the current date.

    The second command imports the TestModule module. This module includes a Function named Get-Date that returns the Julian date.

    The third command runs the Get-Date command again. Because Functions take precedence over cmdlets, the Get-Date Function from the TestModule module ran, instead of the Get-Date cmdlet.

    The fourth command shows that there are two Get-Date commands in the session, a Function from the TestModule module and a cmdlet from the Microsoft.PowerShell.Utility snap-in.

    The fifth command runs the hidden cmdlet by qualifying the command name with the snap-in name.

    For more information about command precedence in Windows PowerShell, see about_command_precedence.

RELATED LINKS
    Online version: http://go.microsoft.com/fwlink/?LinkID=141553
    Get-Module
    New-Module
    Remove-Module
    Export-ModuleMember
    about_modules

Import-PSSession

NAME
    Import-PSSession

SYNOPSIS
    Imports commands from another session into the current session.

SYNTAX
    Import-PSSession [-Session] <PSSession> [[-CommandName] <string[]>] [[-FormatTypeName] <string[]>] [-AllowClobber] [-ArgumentList <Object[]>] [-CommandType {Alias | Function | Filter | Cmdlet | ExternalScript | Application | Script | All}] [-Module <string[]>] [-Prefix <string>] [<CommonParameters>]

DESCRIPTION
    The Import-PSSession cmdlet imports commands (such as cmdlets, Functions, and Aliases) from a PSSession on a local or remote computer into the current session. You can import any command that Get-Command can find in the PSSession.

    Use an Import-PSSession command to import commands from a customized shell, such as a Microsoft Exchange Server shell, or from a session that includes Windows PowerShell modules and snap-ins or other elements that are not in the current session.

    To import commands, first use the New-PSSession cmdlet to create a PSSession. Then, use the Import-PSSession cmdlet to import the commands. By default, Import-PSSession imports all commands except for commands that have the same names as commands in the current session. To import all the commands, use the AllowClobber parameter.

    You can use imported commands just as you would use any command in the session. When you use an imported command, the imported part of the command runs implicitly in the session from which it was imported. However, the remote operations are handled entirely by Windows PowerShell. You need not even be aware of them, except that you must keep the connection to the other session (PSSession) open. If you close it, the imported commands are no longer available.

    Because imported commands might take longer to run than local commands, Import-PSSession adds an AsJob parameter to every imported command. This parameter allows you to run the command as a Windows PowerShell background job. For more information, see about_jobs.

    When you use Import-PSSession, Windows PowerShell adds the imported commands to a temporary module that exists only in your session and returns an object that represents the module. To create a persistent module that you can use in future sessions, use the Export-PSSession cmdlet.

    The Import-PSSession cmdlet uses the implicit remoting feature of Windows PowerShell. When you import commands into the current session, they run implicitly in the original session or in a similar session on the originating computer.

PARAMETERS
    -AllowClobber [<SwitchParameter>]
        Imports the specified commands, even if they have the same names as commands in the current session.

        If you import a command with the same name as a command in the current session, the imported command hides or replaces the original commands. For more information, see about_command_precedence.

        By default, Import-PSSession does not import commands that have the same name as commands in the current session.

        Required?                    false
        Position?                    named
        Default value                False
        Accept pipeline input?     false
        Accept wildcard characters? false

    -ArgumentList <Object[]>
        Imports the variant of the command that results from using the specified arguments (parameter values).

        For example, to import the variant of the Get-Item command in the Certificate (Cert:) drive in the PSSession in $s, type “Import-PSSession -Session $s -command Get-Item -ArgumentList cert:”.

        Required?                    false
        Position?                    named
        Default value                All command in the PSSession, except for commands with the same names as commands in the current session.
        Accept pipeline input?     false
        Accept wildcard characters? false

    -CommandName <string[]>
        Imports only the commands with the specified names or name patterns. Wildcards are permitted. Use “CommandName” or its Alias, “Name”.

        By default, Import-PSSession imports all commands from the session, except for commands that have the same names as commands in the current session. This prevents imported commands from hiding or replacing commands in the session. To import all commands, even those that hide or replace other commands, use the AllowClobber parameter.

        If you use the CommandName parameter, the formatting files for the commands are not imported unless you use the FormatTypeName parameter. Similarly, if you use the FormatTypeName parameter, no commands are imported unless you use the CommandName parameter.

        Required?                    false
        Position?                    3
        Default value                All commands in the PSSession, except for commands with the same names as commands in the current session.
        Accept pipeline input?     false
        Accept wildcard characters? true

    -CommandType <CommandTypes>
        Imports only the specified types of command objects. The default value is Cmdlet. Use “CommandType” or its Alias, “Type”.

        Valid values are:
        — Alias: The Windows PowerShell Aliases in the remote session.
        — All: The cmdlets and Functions in the remote session.
        — Application: All the files other than Windows-PowerShell files in the paths that are listed in the Path Environment Variable ($env:path) in the remote session, including .txt, .exe, and .dll files.
        — Cmdlet: The cmdlets in the remote session. “Cmdlet” is the default.
        — ExternalScript: The .ps1 files in the paths listed in the Path Environment Variable ($env:path) in the remote session.
        — Filter and Function: The Windows PowerShell Functions in the remote session.
        — Script: The script blocks in the remote session.

        Required?                    false
        Position?                    named
        Default value                All command in the PSSession, except for commands with the same names as commands in the current session.
        Accept pipeline input?     false
        Accept wildcard characters? false

    -FormatTypeName <string[]>
        Imports formatting instructions for the specified Microsoft .NET Framework types. Enter the type names. Wildcards are permitted.

        The value of this parameter must be the name of a type that is returned by a Get-FormatData command in the session from which the commands are being imported. To get all of the formatting data in the remote session, type *.

        If the command does not include either the CommandName or FormatTypeName parameters, Import-PSSession
        imports formatting instructions for all .NET Framework types returned by a Get-FormatData command in the remote session.

        If you use the FormatTypeName parameter, no commands are imported unless you use the CommandName parameter.
        Similarly, if you use the CommandName parameter, the formatting files for the commands are not imported unless you use the FormatTypeName parameter.

        Required?                    false
        Position?                    4
        Default value                Types in the System.Management.Automation namespace
        Accept pipeline input?     false
        Accept wildcard characters? true

    -Module <string[]>
        Imports only the commands in the specified Windows PowerShell snap-ins and modules. Enter the snap-in and module names. Wildcards are not permitted.

        For more information, see about_PSSnapins and Import-Module.

        Required?                    false
        Position?                    named
        Default value                All command in the PSSession, except for commands with the same names as commands in the current session.
        Accept pipeline input?     false
        Accept wildcard characters? false

    -Prefix <string>
        Adds the specified prefix to the nouns in the names of imported commands.

        Use this parameter to avoid name conflicts that might occur when different commands in the session have the same name.
        For example, if you specify the prefix “Remote” and then import a Get-Date cmdlet, the cmdlet is known in the session as Get-RemoteDate and it is not confused with the original Get-Date cmdlet.

        Required?                    false
        Position?                    named
        Default value
        Accept pipeline input?     false
        Accept wildcard characters? false

    -Session <PSSession>
        Specifies the PSSession from which the cmdlets are imported. Enter a Variable that contains a session object or a command that gets a session object, such as a New-PSSession or Get-PSSession command. You can specify only one session. This parameter is required.

        Required?                    true
        Position?                    1
        Default value                None
        Accept pipeline input?     false
        Accept wildcard characters? false

    <CommonParameters>
        This cmdlet supports the common parameters: Verbose, Debug,
        ErrorAction, ErrorVariable, WarningAction, WarningVariable,
        OutBuffer and OutVariable. For more information, type,
        “Get-Help about_CommonParameters“.

INPUTS
    None
        You cannot pipe objects to this cmdlet.

OUTPUTS
    System.Management.Automation.PSModuleInfo
        Import-PSSession returns the same module object that New-Module and Get-Module return. However, the imported module is temporary and exists only in the current session. To create a permanent module on disk, use the Export-PSSession cmdlet.

NOTES

        Import-PSSession relies on the Windows PowerShell remoting infrastructure. To use this cmdlet, the computer must be configured for WS-Management remoting. For more information, see about_remote and about_remote_requirements.

        You cannot use Import-PSSession to import Variables or Windows PowerShell providers.

        When you import commands that have the same names as commands in the current session, the imported commands can hide Aliases, Functions, and cmdlets in the session and they can replace Functions and Variables in the session. For more information, see about_command_precedence.

        Import-PSSession converts all commands into Functions before it imports them. As a result, imported commands behave a bit differently than they would if they retained their original command type. For example, if you import a cmdlet from a PSSession and then import a cmdlet with the same name from a module or snap-in, the cmdlet that is imported from the PSSession always runs by default because Functions take precedence over cmdlets. Conversely, if you import an Alias into a session that has an Alias with the same name, the original Alias is always used, because Aliases take precedence over Functions. For more information, see about_command_precedence.

        Import-PSSession uses the Write-Progress cmdlet to display the progress of the command. You might see the progress bar while the command is running.

        To find the commands to import, Import-PSSession uses the Invoke-Command cmdlet to run a Get-Command command in the PSSession. To get formatting data for the commands, it uses the Get-FormatData cmdlet. You might see error messages from Invoke-Command, Get-Command, and Get-FormatData when you run an Import-PSSession command. Also, Import-PSSession cannot import commands from a PSSession that does not include the Get-Command, Get-FormatData, Select-Object, and Get-Help cmdlets.

        Imported commands have the same limitations as other remote commands, including the inability to start a program with a user interface, such as Notepad.

        Because Windows PowerShell profiles are not run in PSSessions, the commands that a profile adds to a session are not available to Import-PSSession. To import commands from a profile, use an Invoke-Command command to run the profile in the PSSession manually before importing commands.

        The temporary module that Import-PSSession creates might include a formatting file, even if the command does not import formatting data. If the command does not import formatting data, any formatting files that are created will not contain formatting data.

        To use Import-PSSession, the execution policy in the current session cannot be Restricted or AllSigned, because the module that Import-PSSession creates contains unsigned script files that are prohibited by these policies. To use Import-PSSession without changing the execution policy for the local computer, use the Scope parameter of Set-ExecutionPolicy to set a less restrictive execution policy for a single process.

    ————————– EXAMPLE 1 ————————–

    C:\PS>$s = New-PSSession -computername Server01

    C:\PS> Import-PSSession -Session $s

    Description
    ———–
    This command imports all commands from a PSSession on the Server01 computer into the current session, except for commands that have the same names as commands in the current session.

    Because this command does not use the CommandName parameter, it also imports all of the formatting data required for the imported commands.

    ————————– EXAMPLE 2 ————————–

    C:\PS>$s = New-PSSession https://ps.testlabs.com/powershell

    C:\PS> Import-PSSession -Session $s -CommandName *-test -FormatTypeName *

    C:\PS> new-test -name test1

    C:\PS> get-test test1 | run-test

    Description
    ———–
    These commands import the commands with names that end in “-test” from a PSSession into the local session, and then they show how to use an imported cmdlet.

    The first command uses the New-PSSession cmdlet to create a PSSession. It saves the PSSession in the $s Variable.

    The second command uses the Import-PSSession cmdlet to import commands from the PSSession in $s into the current session. It uses the CommandName parameter to specify commands with the Test noun and the FormatTypeName parameter to import the formatting data for the Test commands.

    The third and fourth commands use the imported commands in the current session. Because imported commands are actually added to the current session, you use the local syntax to run them. You do not need to use the Invoke-Command cmdlet to run an imported command.

    ————————– EXAMPLE 3 ————————–

    C:\PS>$s1 = New-PSSession -computername s1

    C:\PS> $s2 = New-PSSession -computername s2

    C:\PS> Import-PSSession -Session s1 -type cmdlet -name New-Test, Get-Test -FormatTypeName *

    C:\PS> Import-PSSession -Session s2 -type cmdlet -name Set-Test -FormatTypeName *

    C:\PS> new-test Test1 | set-test -runtype full

    Description
    ———–
    This example shows that you can use imported cmdlets just as you would use local cmdlets.

    These commands import the New-Test and Get-Test cmdlets from a PSSession on the Server01 computer and the Set-Test cmdlet from a PSSession on the Server02 computer.

    Even though the cmdlets were imported from different PSSessions, you can pipe an object from one cmdlet to another without error.

    ————————– EXAMPLE 4 ————————–

    C:\PS>$s = New-PSSession -computername Server01

    C:\PS> Import-PSSession -Session $s -CommandName *-test* -FormatTypeName *

    C:\PS> $batch = new-test -name Batch -asjob

    C:\PS> Receive-Job $batch

    Description
    ———–
    This example shows how to run an imported command as a background job.

    Because imported commands might take longer to run than local commands, Import-PSSession adds an AsJob parameter to every imported command. The AsJob parameter lets you run the command as a background job.

    The first command creates a PSSession on the Server01 computer and saves the PSSession object in the $s Variable.

    The second command uses Import-PSSession to import the Test cmdlets from the PSSession in $s into the current session.

    The third command uses the AsJob parameter of the imported New-Test cmdlet to run a New-Test command as a background job. The command saves the job object that New-Test returns in the $batch Variable.

    The fourth command uses the Receive-Job cmdlet to get the results of the job in the $batch Variable.

    ————————– EXAMPLE 5 ————————–

    C:\PS>$s = New-PSSession -comp Server01

    C:\PS> Invoke-Command -Session $s {Import-Module TestManagement}

    C:\PS> Import-PSSession -Session $s -Module TestManagement

    Description
    ———–
    This example shows how to import the cmdlets and Functions from a Windows PowerShell module on a remote computer into the current session.

    The first command creates a PSSession on the Server01 computer and saves it in the $s Variable.

    The second command uses the Invoke-Command cmdlet to run an Import-Module command in the PSSession in $s.

    Typically, the module would be added to all sessions by an Import-Module command in a Windows PowerShell profile, but profiles are not run in PSSessions.

    The third command uses the Module parameter of Import-PSSession to import the cmdlets and Functions in the module into the current session.

    ————————– EXAMPLE 6 ————————–

    C:\PS>Import-PSSession $s -CommandName Get-Date, SearchHelp -FormatTypeName * -AllowClobber

    Name             : tmp_79468106-4e1d-4d90-af97-1154f9317239_tcw1zunz.ttf
    Path             : C:\Users\User01\AppData\Local\Temp\tmp_79468106-4e1d-4d90-af97-1154f9317239_tcw1zunz.ttf\tmp_79468106-4e1d-4d90-af97-1154f9317239_
                        tcw1zunz.ttf.psm1
    Description     : Implicit remoting for http://server01.corp.fabrikam.com/wsman
    Guid             : 79468106-4e1d-4d90-af97-1154f9317239
    Version         : 1.0
    ModuleBase        : C:\Users\User01\AppData\Local\Temp\tmp_79468106-4e1d-4d90-af97-1154f9317239_tcw1zunz.ttf
    ModuleType        : Script
    PrivateData     : {ImplicitRemoting}
    AccessMode        : ReadWrite
    ExportedAliases : {}
    ExportedCmdlets : {}
    ExportedFunctions : {[Get-Date, Get-Date], [SearchHelp, SearchHelp]}
    ExportedVariables : {}
    NestedModules     : {}

    Description
    ———–
    This example shows that Import-PSSession creates a module in a temporary file on disk. It also shows that all commands are converted into Functions before they are imported into the current session.

    The command uses the Import-PSSession cmdlet to import a Get-Date cmdlet and a SearchHelp Function into the current session.

    The Import-PSSession cmdlet returns a PSModuleInfo object that represents the temporary module. The value of the Path property shows that Import-PSSession created a script module (.psm1) file in a temporary location. The ExportedFunctions property shows that the Get-Date cmdlet and the SearchHelp Function were both imported as Functions.

    ————————– EXAMPLE 7 ————————–

    C:\PS>Import-PSSession $s -CommandName Get-Date -FormatTypeName * -AllowClobber

    C:\PS> Get-Command Get-Date

    CommandType Name     Definition
    ———– —-     ———-
    Function     Get-Date
    Cmdlet        Get-Date Get-Date [[-Date] <DateTime>] [-Year <Int32>] [-Month <Int32>]

    C:\PS> Get-Date
    09074

    C:\PS> (Get-Command -type cmdlet -name Get-Date).pssnapin.name
    Microsoft.PowerShell.Utility

    C:\PS> Microsoft.PowerShell.Utility\Get-Date

    Sunday, March 15, 2009 2:08:26 PM

    Description
    ———–
    This example shows how to run a command that is hidden by an imported command.

    The first command imports a Get-Date cmdlet from the PSSession in the $s Variable. Because the current session includes a Get-Date cmdlet, the AllowClobber parameter is required in the command.

    The second command uses the Get-Command cmdlet to get the Get-Date commands in the current session. The output shows that the session includes the original Get-Date cmdlet and a Get-Date Function. The Get-Date Function runs the imported Get-Date cmdlet in the PSSession in $s.

    The third command runs a Get-Date command. Because Functions take precedence over cmdlets, Windows PowerShell runs the imported Get-Date Function, which returns a Julian date.

    The fourth and fifth commands show how to use a qualified name to run a command that is hidden by an imported command.

    The fourth command gets the name of the Windows PowerShell snap-in that added the original Get-Date cmdlet to the current session.

    The fifth command uses the snap-in-qualified name of the Get-Date cmdlet to run a Get-Date command.

    For more information about command precedence and hidden commands, see about_command_precedence.

    ————————– EXAMPLE 8 ————————–

    C:\PS>Import-PSSession -Session $s -CommandName *Item* -AllowClobber

    Description
    ———–
    This command imports commands whose names include “Item” from the PSSession in $s. Because the command includes the CommandName parameter but not the FormatTypeData parameter, only the command is imported.

    Use this command when you are using Import-PSSession to run a command on a remote computer and you already have the formatting data for the command in the current session.

    ————————– EXAMPLE 9 ————————–

    C:\PS>$m = Import-PSSession -Session $s -CommandName *bits* -FormatTypeName *bits*

    C:\PS> Get-Command -Module $m

    CommandType     Name
    ———–     —-
    Function        Add-BitsFile
    Function        Complete-BitsTransfer
    Function        Get-BitsTransfer
    Function        Remove-BitsTransfer
    Function        Resume-BitsTransfer
    Function        Set-BitsTransfer
    Function        Start-BitsTransfer
    Function        Suspend-BitsTransfer

    Description
    ———–
    This command shows how to use the Module parameter of Get-Command to find out which commands were imported into the session by an Import-PSSession command.

    The first command uses the Import-PSSession cmdlet to import commands whose names include “bits” from the PSSession in the $s Variable. The Import-PSSession command returns a temporary module, and the command saves the module in the $m Variable.

    The second command uses the Get-Command cmdlet to get the commands that are exported by the module in the $m Variable.

    The Module parameter takes a string value, which is designed for the module name. However, when you submit a module object, Windows PowerShell uses the ToString method on the module object, which returns the module name.

    The Get-Command command is the equivalent of “Get-Command $m.name”.

RELATED LINKS
    Online version: http://go.microsoft.com/fwlink/?LinkID=135221
    about_command_precedence
    New-PSSession
    Export-PSSession
    about_jobs
    about_pssessions

Invoke-Command

NAME
    Invoke-Command

SYNOPSIS
    Runs commands on local and remote computers.

SYNTAX
    Invoke-Command [-ScriptBlock] <scriptblock> [[-ComputerName] <string[]>] [-ApplicationName <string>] [-AsJob] [-Authentication {Default | Basic | Negotiate | NegotiateWithImplicitCredential | Credssp | Digest | Kerberos}] [-CertificateThumbprint <string>] [-ConfigurationName <string>] [-Credential <PSCredential>] [-HideComputerName] [-JobName <string>] [-Port <int>] [-SessionOption <PSSessionOption>] [-ThrottleLimit <int>] [-UseSSL] [-ArgumentList <Object[]>] [-InputObject <psobject>] [<CommonParameters>]

    Invoke-Command [-FilePath] <string> [[-ComputerName] <string[]>] [-ApplicationName <string>] [-AsJob] [-Authentication {Default | Basic | Negotiate | NegotiateWithImplicitCredential | Credssp | Digest | Kerberos}] [-ConfigurationName <string>] [-Credential <PSCredential>] [-HideComputerName] [-JobName <string>] [-Port <int>] [-SessionOption <PSSessionOption>] [-ThrottleLimit <int>] [-UseSSL] [-ArgumentList <Object[]>] [-InputObject <psobject>] [<CommonParameters>]

    Invoke-Command [-FilePath] <string> [[-Session] <PSSession[]>] [-AsJob] [-HideComputerName] [-JobName <string>] [-ThrottleLimit <int>] [-ArgumentList <Object[]>] [-InputObject <psobject>] [<CommonParameters>]

    Invoke-Command [-FilePath] <string> [[-ConnectionURI] <Uri[]>] [-AllowRedirection] [-AsJob] [-Authentication {Default | Basic | Negotiate | NegotiateWithImplicitCredential | Credssp | Digest | Kerberos}] [-ConfigurationName <string>] [-Credential <PSCredential>] [-HideComputerName] [-JobName <string>] [-SessionOption <PSSessionOption>] [-ThrottleLimit <int>] [-ArgumentList <Object[]>] [-InputObject <psobject>] [<CommonParameters>]

    Invoke-Command [-ScriptBlock] <scriptblock> [-ArgumentList <Object[]>] [-InputObject <psobject>] [<CommonParameters>]

    Invoke-Command [-ScriptBlock] <scriptblock> [[-Session] <PSSession[]>] [-AsJob] [-HideComputerName] [-JobName <string>] [-ThrottleLimit <int>] [-ArgumentList <Object[]>] [-InputObject <psobject>] [<CommonParameters>]

    Invoke-Command [-ScriptBlock] <scriptblock> [[-ConnectionURI] <Uri[]>] [-AllowRedirection] [-AsJob] [-Authentication {Default | Basic | Negotiate | NegotiateWithImplicitCredential | Credssp | Digest | Kerberos}] [-CertificateThumbprint <string>] [-ConfigurationName <string>] [-Credential <PSCredential>] [-HideComputerName] [-JobName <string>] [-SessionOption <PSSessionOption>] [-ThrottleLimit <int>] [-ArgumentList <Object[]>] [-InputObject <psobject>] [<CommonParameters>]

DESCRIPTION
    The Invoke-Command cmdlet runs commands on a local or remote computer and returns all output from the commands, including errors. With a single Invoke-Command command, you can run commands on multiple computers.

    To run a single command on a remote computer, use the ComputerName parameter. To run a series of related commands that share data, create a PSSession (a persistent connection) on the remote computer, and then use the Session parameter of Invoke-Command to run the command in the PSSession.

    You can also use Invoke-Command on a local computer to evaluate or run a string in a script block as a command. Windows PowerShell converts the script block to a command and runs the command immediately in the current scope, instead of just echoing the string at the command line.

    Before using Invoke-Command to run commands on a remote computer, read about_remote.

PARAMETERS
    -AllowRedirection [<SwitchParameter>]
        Allows redirection of this connection to an alternate URI.

        When you use the ConnectionURI parameter, the remote destination can return an instruction to redirect to a different URI. By default, Windows PowerShell does not redirect connections, but you can use the AllowRedirection parameter to allow it to redirect the connection.

        You can also limit the number of times that the connection is redirected by setting the MaximumConnectionRedirectionCount property of the $PSSessionOption preference Variable, or the MaximumConnectionRedirectionCount property of the value of the SessionOption parameter. The default value is 5. For more information, see the description of the SessionOption parameter and the help topic for the New-PSSessionOption cmdlet.

        Required?                    false
        Position?                    named
        Default value
        Accept pipeline input?     false
        Accept wildcard characters? false

    -ApplicationName <string>
        Specifies the application name segment of the connection URI. Use this parameter to specify the application name when you are not using the ConnectionURI parameter in the command.

        The default value is the value of the $PSSessionApplicationName preference Variable on the local computer. If this preference Variable is not defined, the default value is WSMan. This value is appropriate for most uses. For more information, see about_preference_variables.

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

        Required?                    false
        Position?                    named
        Default value                WSMan
        Accept pipeline input?     true (ByPropertyName)
        Accept wildcard characters? false

    -ArgumentList <Object[]>
        Supplies the values of local Variables in the command. The Variables in the command are replaced by these values before the command is run on the remote computer. Enter the values in a comma-separated list. Values are associated with Variables in the order that they are listed. The Alias for ArgumentList is “Args”.

        The values in ArgumentList can be actual values, such as “1024”, or they can be references to local Variables, such as “$max”.

        To use local Variables in a command, use the following command format:
        {param($<name1>[, $<name2>]…) <command-with-local-variables>} -ArgumentList <value | $local-variable>

        The “param” keyword lists the local Variables that are used in the command. The ArgumentList parameter supplies the values of the Variables, in the order that they are listed.

        Required?                    false
        Position?                    named
        Default value
        Accept pipeline input?     false
        Accept wildcard characters? false

    -AsJob [<SwitchParameter>]
        Runs the command as a background job on a remote computer. Use this parameter to run commands that take an extensive time to complete.

        When you use AsJob, the command returns an object that represents the job, and then displays the command prompt. You can continue to work in the session while the job completes. To manage the job, use the Job cmdlets. To get the job results, use Receive-Job.

        The AsJob parameter is similar to using Invoke-Command to run a Start-Job command remotely. However, with AsJob, the job is created on the local computer, even though the job runs on a remote computer, and the results of the remote job are automatically returned to the local computer.

        For more information about Windows PowerShell background jobs, see about_jobs and about_remote_Jobs.

        Required?                    false
        Position?                    named
        Default value                None
        Accept pipeline input?     false
        Accept wildcard characters? false

    -Authentication <AuthenticationMechanism>
        Specifies the mechanism that is used to authenticate the user’s credentials. Valid values are Default, Basic, Credssp, Digest, Kerberos, Negotiate, and NegotiateWithImplicitCredential. The default value is Default.

        CredSSP authentication is available only in Windows Vista, Windows Server 2008, and later versions of Windows.

        For information about the values of this parameter, see the description of the System.Management.Automation.Runspaces.AuthenticationMechanism enumeration in MSDN.

        CAUTION: Credential Security Service Provider (CredSSP) authentication, in which the user’s credentials are passed to a remote computer to be authenticated, is designed for commands that require authentication on more than one resource, such as accessing a remote network share. This mechanism increases the security risk of the remote operation. If the remote computer is compromised, the credentials that are passed to it can be used to control the network session.

        Required?                    false
        Position?                    named
        Default value                Default
        Accept pipeline input?     false
        Accept wildcard characters? false

    -CertificateThumbprint <string>
        Specifies the digital public key Certificate (X509) of a user account that has permission to perform this action. Enter the Certificate thumbprint of the Certificate.

        Certificates are used in client Certificate-based authentication. They can only be mapped to local user accounts; they do not work with domain accounts.

        To get a Certificate thumbprint, use the Get-Item or Get-ChildItem commands in the Windows PowerShell Cert: drive.

        Required?                    false
        Position?                    named
        Default value
        Accept pipeline input?     false
        Accept wildcard characters? false

    -ComputerName <string[]>
        Specifies the computers on which the command runs. The default is the local computer.

        When you use the ComputerName parameter, Windows PowerShell creates a temporary connection that is used only to run the specified command and is then closed. If you need a persistent connection, use the Session parameter.

        Type the NETBIOS name, IP address, or fully-qualified domain name of one or more computers in a comma-separated list. To specify the local computer, type the computer name, “localhost”, or a dot (.).

        To use an IP address in the value of the ComputerName parameter, the command must include the Credential parameter. Also, the computer must be configured for HTTPS transport or the IP address of the remote computer must be included in the WinRM TrustedHosts list on the local computer. For instructions for adding a computer name to the TrustedHosts list, see “How to Add a Computer to the Trusted Host List” in about_remote_TroubleShooting.

        Note: On Windows Vista, and later versions of Windows, to include the local computer in the value of the ComputerName parameter, you must open Windows PowerShell with the “Run as administrator” option.

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

    -ConfigurationName <string>
        Specifies the session configuration that is used for the new PSSession.

        Enter a configuration name or the fully qualified resource URI for a session configuration. If you specify only the configuration name, the following schema URI is prepended: http://schemas.microsoft.com/powershell.

        The session configuration for a session is located on the remote computer. If the specified session configuration does not exist on the remote computer, the command fails.

        The default value is the value of the $PSSessionConfigurationName preference Variable on the local computer. If this preference Variable is not set, the default is Microsoft.PowerShell. For more information, see about_preference_variables.

        Required?                    false
        Position?                    named
        Default value                http://Schemas.Microsoft.com/PowerShell/Microsoft.PowerShell
        Accept pipeline input?     true (ByPropertyName)
        Accept wildcard characters? false

    -ConnectionURI <Uri[]>
        Specifies a Uniform Resource Identifier (URI) that defines the connection endpoint. The URI must be fully qualified.

        The format of this string is:
            <Transport>://<ComputerName>:<Port>/<ApplicationName>

        The default value is:
            http://localhost:80/WSMAN

        Valid values for the Transport segment of the URI are HTTP and HTTPS. If you do not specify a ConnectionURI, you can use the UseSSL, ComputerName, Port, and ApplicationName parameters to specify the URI values.

        If the destination computer redirects the connection to a different URI, Windows PowerShell prevents the redirection unless you use the AllowRedirection parameter in the command.

        Required?                    false
        Position?                    1
        Default value                http://localhost:80/wsman
        Accept pipeline input?     true (ByPropertyName)
        Accept wildcard characters? false

    -Credential <PSCredential>
        Specifies a user account that has permission to perform this action. The default is the current user.

        Type a user name, such as “User01” or “Domain01\User01”, or enter a Variable that contains a PSCredential object, such as one generated by the Get-Credential cmdlet. When you type a user name, you will be prompted for a password.

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

    -FilePath <string>
        Runs the specified local script on one or more remote computers. Enter the path and file name of the script, or pipe a script path to Invoke-Command. The script must reside on the local computer or in a directory that the local computer can access. Use the ArgumentList parameter to specify the values of parameters in the script.

        When you use this parameter, Windows PowerShell converts the contents of the specified script file to a script block, transmits the script block to the remote computer, and runs it on the remote computer.

        Required?                    true
        Position?                    2
        Default value
        Accept pipeline input?     false
        Accept wildcard characters? false

    -HideComputerName [<SwitchParameter>]
        Omits the computer name of each object from the output display. By default, the name of the computer that generated the object appears in the display.

        This parameter affects only the output display. It does not change the object.

        Required?                    false
        Position?                    named
        Default value
        Accept pipeline input?     false
        Accept wildcard characters? false

    -InputObject <psobject>
        Specifies input to the command. Enter a Variable that contains the objects or type a command or expression that gets the objects.

        When using InputObject, use the $input automatic Variable in the value of the ScriptBlock parameter to represent the input objects.

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

    -JobName <string>
        Specifies a friendly name for the background job. By default, jobs are named “Job<n>”, where <n> is an ordinal number. This parameter is valid only with the AsJob parameter.

        If you use the JobName parameter in a command, the command is run as a job, and Invoke-Command returns a job object, even if you do not include the AsJob parameter in the command.

        For more information about Windows PowerShell background jobs, see about_jobs.

        Required?                    false
        Position?                    named
        Default value                Job<n>
        Accept pipeline input?     false
        Accept wildcard characters? false

    -Port <int>
        Specifies the network port on the remote computer used for this command. The default is port 80 (the HTTP port).

        Before using an alternate port, you must configure the WinRM listener on the remote computer to listen at that port. To configure the listener, type the following two commands at the Windows PowerShell prompt:

        Remove-Item -path WSMan:\Localhost\listener\listener* -recurse
        New-Item -path WSMan:\Localhost\listener -Transport http -Address * -port <port-number>

        Do not use the Port parameter unless you must. The Port set in the command applies to all computers or sessions on which the command runs. An alternate port setting might prevent the command from running on all computers.

        Required?                    false
        Position?                    named
        Default value
        Accept pipeline input?     false
        Accept wildcard characters? false

    -ScriptBlock <scriptblock>
        Specifies the commands to run. Enclose the commands in curly braces ( { } ) to create a script block. This parameter is required.

        By default, any Variables in the command are evaluated on the remote computer. To include local Variables in the command, use the ArgumentList parameter.

        Required?                    true
        Position?                    1
        Default value
        Accept pipeline input?     false
        Accept wildcard characters? false

    -Session <PSSession[]>
        Runs the command in the specified Windows PowerShell sessions (PSSessions). Enter a Variable that contains the PSSessions or a command that creates or gets the PSSessions, such as a New-PSSession or Get-PSSession command.

        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 that share data. To run a single command or a series of unrelated commands, use the ComputerName parameter.

        To create a PSSession, use the New-PSSession cmdlet. For more information, see about_pssessions.

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

    -SessionOption <PSSessionOption>
        Sets advanced options for the session. Enter a SessionOption object that you create by using the New-PSSessionOption cmdlet.

        The default values for the options are determined by the value of the $PSSessionOption preference Variable, if it is set. Otherwise, the session uses the system defaults.

        For a description of the session options, including the default values, see the help topic for the New-PSSessionOption cmdlet. For information about the $PSSessionOption preference Variable, see about_preference_variables.

        Required?                    false
        Position?                    named
        Default value
        Accept pipeline input?     false
        Accept wildcard characters? false

    -ThrottleLimit <int>
        Specifies the maximum number of concurrent connections that can be established to run this command. If you omit this parameter or enter a value of 0, the default value, 32, is used.

        The throttle limit applies only to the current command, not to the session or to the computer.

        Required?                    false
        Position?                    named
        Default value                32
        Accept pipeline input?     false
        Accept wildcard characters? false

    -UseSSL [<SwitchParameter>]
        Uses the Secure Sockets Layer (SSL) protocol to establish a connection to the remote computer. By default, SSL is not used.

        WS-Management encrypts all Windows PowerShell content transmitted over the network. UseSSL is an additional protection that sends the data across an HTTPS, instead of HTTP.

        If you use this parameter, but SSL is not available on the port used for the command, the command fails.

        Required?                    false
        Position?                    named
        Default value
        Accept pipeline input?     false
        Accept wildcard characters? false

    <CommonParameters>
        This cmdlet supports the common parameters: Verbose, Debug,
        ErrorAction, ErrorVariable, WarningAction, WarningVariable,
        OutBuffer and OutVariable. For more information, type,
        “Get-Help about_CommonParameters“.

INPUTS
    System.Management.Automation.ScriptBlock
        You can pipe a command in a script block to Invoke-Command. Use the $input automatic Variable to represent the input objects in the command.

OUTPUTS
    System.Management.Automation.PSRemotingJob or the output of the invoked command
        When you use the AsJob parameter, Invoke-Command returns a job object. Otherwise, it returns the output of the invoked command (the value of the ScriptBlock parameter).

NOTES

        — On Windows Vista, and later versions of Windows, to use the ComputerName parameter of Invoke-Command to run a command on the local computer, you must open Windows PowerShell with the “Run as administrator” option.

        — When you run commands on multiple computers, Windows PowerShell connects to the computers in the order in which they appear in the list. However, the command output is displayed in the order that it is received from the remote computers, which might be different.

        — Errors that result from the command that Invoke-Command runs are included in the command results. Errors that would be terminating errors in a local command are treated as non-terminating errors in a remote command. This strategy ensures that terminating errors on one computer do not terminate the command on all computers on which it is run. This practice is used even when a remote command is run on a single computer.

        — If the remote computer is not in a domain that the local computer trusts, the computer might not be able to authenticate the user’s credentials. To add the remote computer to the list of “trusted hosts” in WS-Management, use the following command in the WSMan provider, where <Remote-Computer-Name> is the name of the remote computer:
        Set-Item -path WSMan:\Localhost\Client\TrustedHosts -value <Remote-Computer-Name>.

    ————————– EXAMPLE 1 ————————–

    C:\PS>Invoke-Command -filepath c:\scripts\test.ps1 -computerName Server01

    Disks: C:, D:, E:
    Status: Warning, Normal, Normal

    Description
    ———–
    This command runs the Test.ps1 script on the Server01 computer.

    The command uses the FilePath parameter to specify a script that is located on the local computer. The script runs on the remote computer and the results are returned to the local computer.

    ————————– EXAMPLE 2 ————————–

    C:\PS>Invoke-Command -computername server01 -credential domain01\user01 -ScriptBlock {Get-Culture}

    Description
    ———–
    This command runs a Get-Culture command on the Server01 remote computer.

    It uses the ComputerName parameter to specify the computer name and the Credential parameter to run the command in the security context of “Domain01\User01,” a user with permission to run commands. It uses the ScriptBlock parameter to specify the command to be run on the remote computer.

    In response, Windows PowerShell displays a dialog box that requests the password and an authentication method for the User01 account. It then runs the command on the Server01 computer and returns the result.

    ————————– EXAMPLE 3 ————————–

    C:\PS>$s = New-PSSession -computername server02 -credential domain01\user01

    C:\PS> Invoke-Command -session $s -ScriptBlock {Get-Culture}

    Description
    ———–
    This example runs the same “Get-Culture” command in a session (a persistent connection) on the Server02 remote computer. Typically, you create a session only when you are running a series of commands on the remote computer.

    The first command uses the New-PSSession cmdlet to create a session on the Server02 remote computer. Then, it saves the session in the $s Variable.

    The second command uses the Invoke-Command cmdlet to run the Get-Culture command on Server02. It uses the Session parameter to specify the session saved in the $s Variable.

    In response, Windows PowerShell runs the command in the session on the Server02 computer.

    ————————– EXAMPLE 4 ————————–

    C:\PS>Invoke-Command -computername Server02 -ScriptBlock {$p = Get-Process powershell}

    C:\PS> Invoke-Command -computername Server02 -ScriptBlock {$p.virtualmemorysize}
    C:\PS>

    C:\PS> $s = New-PSSession -computername Server02
    C:\PS> Invoke-Command -session $s -ScriptBlock {$p = Get-Process powershell}
    C:\PS> Invoke-Command -session $s -ScriptBlock {$p.virtualmemorysize}
    17930240

    Description
    ———–
    This example compares the effects of using ComputerName and Session parameters of Invoke-Command. It shows how to use a session to run a series of commands that share the same data.

    The first two commands use the ComputerName parameter of Invoke-Command to run commands on the Server02 remote computer. The first command uses the Get-Process command to get the PowerShell process on the remote computer and to save it in the $p Variable. The second command gets the value of the VirtualMemorySize property of the PowerShell process.

    The first command succeeds. But, the second command fails because when you use the ComputerName parameter, Windows PowerShell creates a connection just to run the command. Then, it closes the connection when the command is complete. The $p Variable was created in one connection, but it does not exist in the connection created for the second command.

    The problem is solved by creating a session (a persistent connection) on the remote computer and by running both of the related commands in the same session.

    The third command uses the New-PSSession cmdlet to create a session on the Server02 computer. Then it saves the session in the $s Variable. The fourth and fifth commands repeat the series of commands used in the first set, but in this case, the Invoke-Command command uses the Session parameter to run both of the commands in the same session.

    In this case, because both commands run in the same session, the commands succeed, and the $p value remains active in the $s session for later use.

    ————————– EXAMPLE 5 ————————–

    C:\PS>$command = { Get-Eventlog -log “windows powershell” | where {$_.message -like “*certificate*”} }

    C:\PS> Invoke-Command -computername S1, S2 -ScriptBlock $command

    Description
    ———–
    This example shows how to enter a command that is saved in a local Variable.

    When the entire command is saved in a local Variable, you can specify the Variable as the value of the ScriptBlock parameter. You do not have to use the “param” keyword or the ArgumentList Variable to submit the value of the local Variable.

    The first command saves a Get-Eventlog command in the $command Variable. The command is formatted as a script block.

    The second command uses the Invoke-Command cmdlet to run the command in $command on the S1 and S2 remote computers.

    ————————– EXAMPLE 6 ————————–

    C:\PS>Invoke-Command -computername server01, server02, TST-0143, localhost -configurationname MySession.PowerShell -ScriptBlock {Get-Eventlog “windows powershell”}

    Description
    ———–
    This example demonstrates how to use the Invoke-Command cmdlet to run a single command on multiple computers.

    The command uses the ComputerName parameter to specify the computers. The computer names are presented in a comma-separated list. The list of computers includes the “localhost” value, which represents the local computer.

    The command uses the ConfigurationName parameter to specify an alternate session configuration for Windows PowerShell and the ScriptBlock parameter to specify the command.

    In this example, the command in the script block gets the events in the Windows PowerShell event log on each remote computer.

    ————————– EXAMPLE 7 ————————–

    C:\PS>$version = Invoke-Command -computername (Get-Content machines.txt) -ScriptBlock {(Get-Host).version}

    Description
    ———–
    This command gets the version of the Windows PowerShell host running on 200 remote computers.

    Because only one command is run, it is not necessary to create persistent connections (sessions) to each of the computers. Instead, the command uses the ComputerName parameter to indicate the computers.

    The command uses the Invoke-Command cmdlet to run a Get-Host command. It uses dot notation to get the Version property of the Windows PowerShell host.

    To specify the computers, it uses the Get-Content cmdlet to get the contents of the Machine.txt file, a file of computer names.

    These commands run synchronously (one at a time). When the commands complete, the output of the commands from all of the computers is saved in the $version Variable. The output includes the name of the computer from which the data originated.

    ————————– EXAMPLE 8 ————————–

    C:\PS>$s = New-PSSession -computername Server01, Server02

    C:\PS> Invoke-Command -session $s -ScriptBlock {Get-Eventlog system} -AsJob

    Id Name    State     HasMoreData Location         Command
    — —-    —–     —–         ———–        ——–             ——-
    1    Job1    Running    True         Server01,Server02 Get-Eventlog system

    C:\PS> $j = Get-Job

    C:\PS> $j | Format-List -property *

    HasMoreData : True
    StatusMessage :
    Location     : Server01,Server02
    Command     : Get-Eventlog system
    JobStateInfo : Running
    Finished     : System.Threading.ManualResetEvent
    InstanceId    : e124bb59-8cb2-498b-a0d2-2e07d4e030ca
    Id            : 1
    Name         : Job1
    ChildJobs     : {Job2, Job3}
    Output        : {}
    Error         : {}
    Progress     : {}
    Verbose     : {}
    Debug         : {}
    Warning     : {}
    StateChanged :

    C:\PS> $results = $j | Receive-Job

    Description
    ———–
    These commands run a background job on two remote computers. Because the Invoke-Command command uses the AsJob parameter, the commands run on the remote computers, but the job actually resides on the local computer and the results are transmitted to the local computer.

    The first command uses the New-PSSession cmdlet to create sessions on the Server01 and Server02 remote computers.

    The second command uses the Invoke-Command cmdlet to run a background job in each of the sessions. The command uses the AsJob parameter to run the command as a background job. This command returns a job object that contains two child job objects, one for each of the jobs run on the two remote computers.

    The third command uses a Get-Job command to save the job object in the $j Variable.

    The fourth command uses a pipeline operator (|) to send the value of the $j Variable to the Format-List cmdlet, which displays all properties of the job object in a list.

    The fifth command gets the results of the jobs. It pipes the job object in $j to the Receive-Job cmdlet and stores the results in the $results Variable.

    ————————– EXAMPLE 9 ————————–

    C:\PS>$MWFO-LOg = Microsoft-Windows-Forwarding/Operational

    C:\PS> Invoke-Command -computername server01 -ScriptBlock {param($log, $num) Get-Eventlog -logname $log -newest $num} -ArgumentList $MWFO-log, 10

    Description
    ———–
    This example shows how to include the values of local Variables in a command run on a remote computer.

    The first command saves the name of the Microsoft-Windows-Forwarding/Operational event log in the $MWFO-Log Variable.

    The second command uses the Invoke-Command cmdlet to run a Get-EventLog command on the Server01 remote computer that gets the 10 newest events from the Microsoft-Windows-Forwarding/Operational event log on Server01.

    This command uses the “param” keyword to create two Variables, $log and $num, that are used as placeholders in the Get-EventLog command. These placeholders have arbitrary names that do not need to match the names of the local Variables that supply their values.

    The values of the ArgumentList parameter demonstrate the two different ways to specify values in the argument list. The value of the $log placeholder is the $MFWO-Log Variable, which is defined in the first command. The value of the $num Variable is 10.

    Before the command is sent to the remote computer, the Variables are replaced with the specified values.

    ————————– EXAMPLE 10 ————————–

    C:\PS>Invoke-Command -computername S1, S2 -ScriptBlock {Get-Process powershell}

    PSComputerName    Handles NPM(K)    PM(K)     WS(K) VM(M) CPU(s)     Id ProcessName
    ————–    ——- ——    —–     —– —– ——     — ———–
    S1                575     15        45100     40988 200     4.68     1392 powershell
    S2                777     14        35100     30988 150     3.68     67 powershell

    C:\PS> Invoke-Command -computername S1, S2 -ScriptBlock {Get-Process powershell} -HideComputerName

    Handles NPM(K)    PM(K)     WS(K) VM(M) CPU(s)     Id ProcessName
    ——- ——    —–     —– —– ——     — ———–
    575     15        45100     40988 200     4.68     1392 powershell
    777     14        35100     30988 150     3.68     67 powershell

    Description
    ———–
    This example shows the effect of using the HideComputerName parameter of Invoke-Command.

    The first two commands use the Invoke-Command cmdlet to run a Get-Process command for the PowerShell process. The output of the first command includes the PsComputerName property, which contains the name of the computer on which the command ran. The output of the second command, which uses the HideComputerName parameter, does not include the PsComputerName column.

    Using the HideComputerName parameter does not change the object. You can still use the Format cmdlets to display the PsComputerName property of any of the affected objects.

    ————————– EXAMPLE 11 ————————–

    C:\PS>Invoke-Command -comp (Get-Content servers.txt) -filepath c:\scripts\sample.ps1 -ArgumentList Process, Service

    Description
    ———–
    This example uses the Invoke-Command cmdlet to run the Sample.ps1 script on all of the computers listed in the Servers.txt file. The command uses the FilePath parameter to specify the script file. This command allows you to run the script on the remote computers, even if the script file is not accessible to the remote computers.

    When you submit the command, the content of the Sample.ps1 file is copied into a script block and the script block is run on each of the remote computers. This procedure is equivalent to using the ScriptBlock parameter to submit the contents of the script.

    ————————– EXAMPLE 12 ————————–

    C:\PS>$LiveCred = Get-Credential

    C:\PS> Invoke-Command -ConfigurationName Microsoft.Exchange `
             -ConnectionUri https://ps.exchangelabs.com/powershell `
             -Credential $LiveCred -Authentication Basic `
             -ScriptBlock {Invoke-Command {Set-Mailbox dan -DisplayName “Dan Park”}

    Description
    ———–
    This example shows how to run a command on a remote computer that is identified by a URI (Internet address). This particular example runs a Set-Mailbox command on a remote Exchange server. The backtick (`) in the command is the Windows PowerShell continuation character.

    The first command uses the Get-Credential cmdlet to store Windows Live ID credentials in the $LiveCred variab the credentials dialog box appears, enter Windows Live ID credentials.

    The second command uses the Invoke-Command cmdlet to run a Set-Mailbox command. The command uses the ConfigurationName parameter to specify that the command should run in a session that uses the Microsoft.Exchange session configuration. The ConnectionURI parameter specifies the URL of the Exchange server endpoint.

    The credential parameter specifies tle. Whenhe Windows Live credentials stored in the $LiveCred Variable. The AuthenticationMechanism parameter specifies the use of basic authentication. The ScriptBlock parameter specifies a script block that contains the command.

    ————————– EXAMPLE 13 ————————–

    C:\PS>$max = New-PSSessionOption -MaximumRedirection 1

    C:\PS> Invoke-Command -ConnectionUri https://ps.exchangelabs.com/powershell `
             -ScriptBlock {Invoke-Command {Get-Mailbox dan} `
             -AllowRedirection -SessionOption $max

    Description
    ———–
    This command shows how to use the AllowRedirection and SessionOption parameters to manage URI redirection in a remote command.

    The first command uses the New-PSSessionOption cmdlet to create a PSSessionOpption object that it saves in the $max Variable. The command uses the MaximumRedirection parameter to set the MaximumConnectionRedirectionCount property of the PSSessionOption object to 1.

    The second command uses the Invoke-Command cmdlet to run a Get-Mailbox command on a remote server running Microsoft Exchange Server. The command uses the AllowRedirection parameter to provide explicit permission to redirect the connection to an alternate endpoint. It also uses the SessionOption parameter to specify the session object in the $max Variable.

    As a result, if the remote computer specified by the ConnectionURI parameter returns a redirection message, Windows PowerShell will redirect the connection, but if the new destination returns another redirection message, the redirection count value of 1 is exceeded, and Invoke-Command returns a non-terminating error.

    ————————– EXAMPLE 14 ————————–

    C:\PS>$so = New-PSSessionOption -SkipCACheck

    PS C:\> Invoke-Command $s { Get-HotFix } -SessionOption $so -credential server01\user01

    Description
    ———–
    This example shows how to create and use a SessionOption parameter.

    The first command uses the New-PSSessionOption cmdlet to create a session option. It saves the resulting SessionOption object in the $so parameter.

    The second command uses the Invoke-Command cmdlet to run a Get-HotFix command remotely. The value of the SessionOption parameter is the SessionOption object in the $so Variable.

    ————————– EXAMPLE 15 ————————–

    C:\PS>Enable-WSManCredSSP -delegate server02

    C:\PS> Connect-WSMan Server02

    C:\PS> Set-Item WSMan:\server02*\service\auth\credSSP -value $true

    C:\PS> $s = New-PSSession server02

    C:\PS> Invoke-Command -session $s -script {Get-Item \\Net03\Scripts\LogFiles.ps1} -authentication credssp -credential domain01\admin01

    Description
    ———–
    This example shows how to access a network share from within a remote session.

    The command requires that CredSSP delegation be enabled in the client settings on the local computer and in the service settings on the remote computer. To run the commands in this example, you must be a member of the Administrators group on the local computer and the remote computer.

    The first command uses the Enable-WSManCredSSP cmdlet to enable CredSSP delegation from the Server01 local computer to the Server02 remote computer. This configures the CredSSP client setting on the local computer.

    The second command uses the Connect-WSMan cmdlet to connect to the Server02 computer. This action adds a node for the Server02 computer to the WSMan: drive on the local computer, allowing you to view and change the WS-Management settings on the Server02 computer.

    The third command uses the Set-Item cmdlet to change the value of the CredSSP item in the Service node of the Server02 computer to True. This action enables CredSSP in the service settings on the remote computer.

    The fourth command uses the New-PSSession cmdlet to create a PSSession on the Server02 computer. It saves the PSSession in the $s Variable.

    The fifth command uses the Invoke-Command cmdlet to run a Get-Item command in the session in $s that gets a script from the Net03\Scripts network share. The command uses the Credential parameter and it uses the Authentication parameter with a value of CredSSP.

RELATED LINKS
    Online version: http://go.microsoft.com/fwlink/?LinkID=135225
    about_remote
    about_pssessions
    New-PSSession
    Get-PSSession
    Remove-PSSession
    Enter-PSSession
    Exit-PSSession
    WS-Management Provider

Get-Command

NAME
    Get-Command

SYNOPSIS
    Gets basic information about cmdlets and other elements of Windows PowerShell commands.

SYNTAX
    Get-Command [[-Name] <string[]>] [-CommandType {Alias | Function | Filter | Cmdlet | ExternalScript | Application | Script | All}] [[-ArgumentList] <Object[]>] [-Module <string[]>] [-Syntax] [-TotalCount <int>] [<CommonParameters>]

    Get-Command [-Noun <string[]>] [-Verb <string[]>] [[-ArgumentList] <Object[]>] [-Module <string[]>] [-Syntax] [-TotalCount <int>] [<CommonParameters>]

DESCRIPTION
    The Get-Command cmdlet gets basic information about cmdlets and other elements of Windows PowerShell commands in the session, such as Aliases, Functions, filters, scripts, and applications.

    Get-Command gets its data directly from the code of a cmdlet, Function, script, or Alias, unlike Get-Help, which gets its information from help topic files.

    Without parameters, “Get-Command” gets all of the cmdlets and Functions in the current session. “Get-Command *” gets all Windows PowerShell elements and all of the non-Windows-PowerShell files in the Path Environment Variable ($env:path). It groups the files in the “Application” command type.

    You can use the Module parameter of Get-Command to find the commands that were added to the session by adding a Windows PowerShell snap-in or importing a module.

PARAMETERS
    -ArgumentList <Object[]>
        Gets information about a cmdlet or Function when it is used with the specified parameters (“arguments”), such as a path. The Alias for ArgumentList is Args.

        To detect parameters that are added to a cmdlet when it is used with a particular provider, set the value of ArgumentList to a path in the provider drive, such as “HKML\Software” or “cert:\my”.

        Required?                    false
        Position?                    2
        Default value
        Accept pipeline input?     false
        Accept wildcard characters? false

    -CommandType <CommandTypes>
        Gets only the specified types of commands. Use “CommandType” or its Alias, “Type”. By default, Get-Command gets cmdlets and Functions.

        Valid values are:
        — Alias: All Windows PowerShell Aliases in the current session.

        — All: All command types. It is the equivalent of “Get-Command *”.

        — Application: All non-Windows-PowerShell files in paths listed in the Path Environment Variable ($env:path), including .txt, .exe, and .dll files.

        — Cmdlet: The cmdlets in the current session. “Cmdlet” is the default.

        — ExternalScript: All .ps1 files in the paths listed in the Path Environment Variable ($env:path).

        — Filter and Function: All Windows PowerShell Functions.

        — Script: Script blocks in the current session.

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

    -Module <string[]>
        Gets the commands that came from the specified modules or snap-ins. Enter the names of modules or snap-ins, or enter snap-in or module objects.

        You can refer to this parameter by its name, Module, or by its Alias, PSSnapin. The parameter name that you choose has no effect on the command or its output.

        This parameter takes string values, but you can also supply a PSModuleInfo or PSSnapinInfo object, such as the objects that Get-Module, Get-PSSnapin, and Import-PSSession return.

        Required?                    false
        Position?                    named
        Default value                None
        Accept pipeline input?     true (ByPropertyName)
        Accept wildcard characters? false

    -Name <string[]>
        Gets information only about the cmdlets or command elements with the specified name. <String> represents all or part of the name of the cmdlet or command element. Wildcards are permitted.

        To list commands with the same name in execution order, type the command name without wildcard characters. For more information, see the Notes section.

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

    -Noun <string[]>
        Gets cmdlets and Functions with names that include the specified noun. <String> represents one or more nouns or noun patterns, such as “process” or “*item*”. Wildcards are permitted.

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

    -Syntax [<SwitchParameter>]
        Gets only specified data about the command element.
                 * For Aliases, retrieves the standard name.
                 * For cmdlets, retrieves the syntax.
                 * For Functions and filters, retrieves the Function definition.
                 * For scripts and applications (files), retrieves the path and filename.

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

    -TotalCount <int>
        Gets only the specified number of command elements. You can use this parameter to limit the output of a command.

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

    -Verb <string[]>
        Gets information about cmdlets and Functions with names that include the specified verb. <String> represents one or more verbs or verb patterns, such as “remove” or *et”. Wildcards are permitted.

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

    <CommonParameters>
        This cmdlet supports the common parameters: Verbose, Debug,
        ErrorAction, ErrorVariable, WarningAction, WarningVariable,
        OutBuffer and OutVariable. For more information, type,
        “Get-Help about_CommonParameters“.

INPUTS
    System.String
        You can pipe a “Name”, “Command”, and “Verb” noun-property specified, or a string object to Get-Command.

OUTPUTS
    Object
        The type of object returned depends on the type of command element retrieved. For example, Get-Command on a cmdlet retrieves a CmdletInfo object, while Get-Command on a DLL retrieves an ApplicationInfo object.

NOTES

        Without parameters, “Get-Command” gets information about the Windows PowerShell cmdlets and Functions. Use the parameters to qualify the elements retrieved.

        Unlike Get-Help, which displays the contents of XML-based help topic files, Get-Command gets its cmdlet information directly from the cmdlet code in the system.

        Get-Command returns the commands in alphabetical order. When the session contains more than one command with the same name, Get-Command returns the commands in execution order. The first command that is listed is the command that runs when you type the command name without qualification. For more information, see about_command_precedence.

    ————————– EXAMPLE 1 ————————–

    C:\PS>Get-Command

    Description
    ———–
    This command gets information about all of the Windows PowerShell cmdlets and Functions.

    The default display lists the command type (“Cmdlet” or “Function” or “Filter”), the name of the cmdlet or Function, and the syntax or Function definition.

    ————————– EXAMPLE 2 ————————–

    C:\PS>Get-Command -Verb set | Format-List

    Description
    ———–
    This command gets information about all of the cmdlets and Functions with the verb “set”, and it displays some of that information in a list.

    The list format includes fields that are omitted from the table display, including the complete syntax. To display all fields (all properties of the object), type “Get-Command -Verb set | Format-List *”.

    ————————– EXAMPLE 3 ————————–

    C:\PS>Get-Command -type cmdlet | Sort-Object noun | Format-Table -group noun

    Description
    ———–
    This command retrieves all of the cmdlets, sorts them alphabetically by the noun in the cmdlet name, and then displays them in noun-based
    groups. This display can help you find the cmdlets for a task.

    By default, Get-Command displays items in the order in which the system discovers them, which is also the order in which they are selected to run when a run command is ambiguous.

    ————————– EXAMPLE 4 ————————–

    C:\PS>Get-Command -Module Microsoft.PowerShell.Security, TestModule

    Description
    ———–
    This command gets the commands in the Microsoft.PowerShell.Security snap-in and the Test-Module module.

    The Module parameter gets commands that were added by importing modules or adding Windows PowerShell snap-ins.

    ————————– EXAMPLE 5 ————————–

    C:\PS>Get-Command Get-ChildItem -args cert: -Syntax

    Description
    ———–
    This command retrieves information about the Get-ChildItem cmdlet when Get-ChildItem is used with the Windows PowerShell Certificate provider.

    When you compare the syntax displayed in the output with the syntax that is displayed when you omit the Args (ArgumentList) parameter, you’ll see that the Certificate provider dynamically adds a parameter, CodeSigningCert, to the Get-ChildItem cmdlet.

    ————————– EXAMPLE 6 ————————–

    C:\PS>(Get-Command Get-ChildItem -ArgumentList cert:).parametersets[0].parameters | Where-Object { $_.IsDynamic }

    Description
    ———–
    This command retrieves only parameters that are added to the Get-ChildItem cmdlet dynamically when it is used with the Windows PowerShell Certificate provider. This is an alternative to the method used in the previous example.

    In this command, the “Get-Command Get-ChildItem -ArgumentList cert:” is processed first. It requests information from Get-Command about the Get-ChildItem cmdlet when it is used with the Certificate provider. The “.parametersets[0]” selects the first parameter set (set 0) of “Get-ChildItem -ArgumentList cert:” and “.parameters” selects the parameters in that parameter set. The resulting parameters are piped to the Where-Object cmdlet to test each parameter (“$_.”) by using the IsDynamic property. To find the properties of the objects in a command, use Get-Member.

    ————————– EXAMPLE 7 ————————–

    C:\PS>Get-Command *

    Description
    ———–
    This command gets information about the Windows PowerShell cmdlets, Functions, filters, scripts, and Aliases in the current console.

    It also gets information about all of the files in the paths of the Path Environment Variable ($env:path). It returns an ApplicationInfo object (System.Management.Automation.ApplicationInfo) for each file, not a FileInfo object (System.IO.FileInfo).

    ————————– EXAMPLE 8 ————————–

    C:\PS>Get-Command | Where-Object {$_.definition -like “*first*”}

    CommandType     Name                        Definition
    ———–     —-                        ———
    Cmdlet         Select-Object             Select-Object [[-Property]

    Description
    ———–
    This command finds a cmdlet or Function based on the name of one of its parameters. You can use this command to identify a cmdlet or Function when all that you can recall is the name of one of its parameters.

    In this case, you recall that one of the cmdlets or Functions has a First parameter that gets the first “n” objects in a list, but you cannot remember which cmdlet it is.

    This command uses the Get-Command cmdlet to get a CmdletInfo object representing each of the cmdlets and Functions in the session. The CmdletInfo object has a Definition property that contains the syntax of the cmdlet or Function, which includes its parameters.

    The command uses a pipeline operator (|) to pass the CmdletInfo object to the Where-Object cmdlet, which examines the definition (syntax) of each object ($_) for a value that includes “first”.

    The result shows that the First parameter belongs to the Select-Object cmdlet.

    ————————– EXAMPLE 9 ————————–

    C:\PS>Get-Command dir | Format-List

    Name             : dir
    CommandType     : Alias
    Definition        : Get-ChildItem
    ReferencedCommand : Get-ChildItem
    ResolvedCommand : Get-ChildItem

    Description
    ———–
    This example shows how to use the Get-Command cmdlet with an Alias. Although it is typically used on cmdlets, Get-Command also displays information about the code in scripts, Functions, Aliases, and executable files.

    This command displays the “dir” Alias in the current console. The command pipes the result to the Format-List cmdlets.

    ————————– EXAMPLE 10 ————————–

    C:\PS>Get-Command notepad

    CommandType     Name         Definition
    ———–     —-         ———-
    Application     notepad.exe    C:\WINDOWS\system32\notepad.exe
    Application     NOTEPAD.EXE    C:\WINDOWS\NOTEPAD.EXE

    Description
    ———–
    This example shows how to use Get-Command to determine which command Windows PowerShell runs when it has access to multiple commands with the same name. When you use the Name parameter without wildcard characters, Get-Command lists the commands with that name in execution precedence order.

    This command shows which Notepad program Windows PowerShell runs when you type “Notepad” without a fully qualified path. The command uses the Name parameter without wildcard characters.

    The sample output shows the Notepad commands in the current console. It indicates that Windows PowerShell will run the instance of Notepad.exe in the C:\Windows\System32 directory.

    ————————– EXAMPLE 11 ————————–

    C:\PS>(Get-Command Get-Date).pssnapin

    C:\PS> (Get-Command remove-gpo).module

    Description
    ———–
    These commands show how to find the snap-in or module from which a particular cmdlet originated.

    The first command uses the PSSnapin property of the CmdletInfo object to find the snap-in that added the Get-Date cmdlet.

    The second command uses the Module property of the CmdletInfo object to find the module that added the Remove-GPO cmdlet.

RELATED LINKS
    Online version: http://go.microsoft.com/fwlink/?LinkID=113309
    about_command_precedence
    Get-Help
    Get-PSDrive
    Get-Member
    Import-PSSession
    Export-PSSession

Export-PSSession

NAME
    Export-PSSession

SYNOPSIS
    Imports commands from another session and saves them in a Windows PowerShell module.

SYNTAX
    Export-PSSession [-Session] <PSSession> [-OutputModule] <string> [[-CommandName] <string[]>] [[-FormatTypeName] <string[]>] [-AllowClobber] [-ArgumentList <Object[]>] [-CommandType {Alias | Function | Filter | Cmdlet | ExternalScript | Application | Script | All}] [-Encoding <string>] [-Force] [-Module <string[]>] [<CommonParameters>]

DESCRIPTION
    The Export-PSSession cmdlet gets cmdlets, Functions, Aliases, and other command types from another PSSession on a local or remote computer and saves them in a Windows PowerShell module. To add the commands from the module to the current session, use the Import-Module cmdlet.

    Unlike Import-PSSession, which imports commands from another PSSession into the current session, Export-PSSession saves the commands in a module. The commands are not imported into the current session.

    To export commands, first use the New-PSSession cmdlet to create a PSSession that has the commands that you want to export. Then use the Export-PSSession cmdlet to export the commands. By default, Export-PSSession exports all commands, except for commands that exist in the current session, but you can use the CommandName parameters to specify the commands to export.

    The Export-PSSession cmdlet uses the implicit remoting feature of Windows PowerShell. When you import commands into the current session, they run implicitly in the original session or in a similar session on the originating computer.

PARAMETERS
    -AllowClobber [<SwitchParameter>]
        Exports the specified commands, even if they have the same names as commands in the current session.

        If you import a command with the same name as a command in the current session, the imported command hides or replaces the original commands. For more information, see about_command_precedence.

        Export-PSSession does not import commands that have the same names as commands in the current session. The default behavior is designed to prevent command name conflicts.

        Required?                    false
        Position?                    named
        Default value                False
        Accept pipeline input?     false
        Accept wildcard characters? false

    -ArgumentList <Object[]>
        Exports the variant of the command that results from using the specified arguments (parameter values).

        For example, to export the variant of the Get-Item command in the Certificate (Cert:) drive in the PSSession in $s, type “Export-PSSession -Session $s -command Get-Item -ArgumentList cert:”.

        Required?                    false
        Position?                    named
        Default value                None
        Accept pipeline input?     false
        Accept wildcard characters? false

    -CommandName <string[]>
        Exports only the commands with the specified names or name patterns. Wildcards are permitted. Use “CommandName” or its Alias, “Name”.

        By default, Export-PSSession exports all commands from the PSSession except for commands that have the same names as commands in the current session. This prevents imported commands from hiding or replacing commands in the current session. To export all commands, even those that hide or replace other commands, use the AllowClobber parameter.

        If you use the CommandName parameter, the formatting files for the commands are not exported unless you use the FormatTypeName parameter. Similarly, if you use the FormatTypeName parameter, no commands are exported unless you use the CommandName parameter.

        Required?                    false
        Position?                    3
        Default value                All commands in the session.
        Accept pipeline input?     false
        Accept wildcard characters? true

    -CommandType <CommandTypes>
        Exports only the specified types of command objects. Use “CommandType” or its Alias, “Type”.

        Valid values are:
        — Alias: All Windows PowerShell Aliases in the current session.
        — All: All command types. It is the equivalent of “Get-Command *”.
        — Application: All files other than Windows PowerShell files in paths listed in the Path Environment Variable ($env:path), including .txt, .exe, and .dll files.
        — Cmdlet: The cmdlets in the current session. “Cmdlet” is the default.
        — ExternalScript: All .ps1 files in the paths listed in the Path Environment Variable ($env:path).
        — Filter and Function: All Windows PowerShell Functions.
        — Script: Script blocks in the current session.

        Required?                    false
        Position?                    named
        Default value                All commands in the session.
        Accept pipeline input?     false
        Accept wildcard characters? false

    -Encoding <string>
        Specifies the encoding for the output files. Valid values are “Unicode”, “UTF7”, “UTF8”, “ASCII”, “UTF32”, “BigEndianUnicode”, “Default”, and “OEM”. The default is “UTF-8”.

        Required?                    false
        Position?                    named
        Default value                UTF-8
        Accept pipeline input?     false
        Accept wildcard characters? false

    -Force [<SwitchParameter>]
        Overwrites one or more existing output files, even if the file has the read-only attribute.

        Required?                    false
        Position?                    named
        Default value                False
        Accept pipeline input?     false
        Accept wildcard characters? false

    -FormatTypeName <string[]>
        Exports formatting instructions only for the specified Microsoft .NET Framework types. Enter the type names. By default, Export-PSSession exports formatting instructions for all .NET Framework types that are not in the System.Management.Automation namespace.

        The value of this parameter must be the name of a type that is returned by a Get-FormatData command in the session from which the commands are being imported. To get all of the formatting data in the remote session, type *.

        If you use the FormatTypeName parameter, no commands are exported unless you use the CommandName parameter.
        Similarly, if you use the CommandName parameter, the formatting files for the commands are not exported unless you use the FormatTypeName parameter.

        Required?                    false
        Position?                    4
        Default value
        Accept pipeline input?     false
        Accept wildcard characters? false

    -Module <string[]>
        Exports only the commands in the specified Windows PowerShell snap-ins and modules. Enter the snap-in and module names. Wildcards are not permitted.

        For more information, see about_PSSnapins and Import-Module.

        Required?                    false
        Position?                    named
        Default value                All commands in the session.
        Accept pipeline input?     false
        Accept wildcard characters? false

    -OutputModule <string>
        Specifies a path (optional) and name for the module that Export-PSSession creates. The default path is $home\Documents\WindowsPowerShell\Modules. This parameter is required.

        If the module subdirectory or any of the files that Export-PSSession creates already exist, the command fails. To overwrite existing files, use the Force parameter.

        Required?                    true
        Position?                    2
        Default value
        Accept pipeline input?     false
        Accept wildcard characters? false

    -Session <PSSession>
        Specifies the PSSession from which the commands are exported. Enter a Variable that contains a session object or a command that gets a session object, such as a Get-PSSession command. This parameter is required.

        Required?                    true
        Position?                    1
        Default value                None
        Accept pipeline input?     false
        Accept wildcard characters? false

    <CommonParameters>
        This cmdlet supports the common parameters: Verbose, Debug,
        ErrorAction, ErrorVariable, WarningAction, WarningVariable,
        OutBuffer and OutVariable. For more information, type,
        “Get-Help about_CommonParameters“.

INPUTS
    None
        You cannot pipe objects to Export-PSSession.

OUTPUTS
    System.IO.FileInfo
        Export-PSSession returns a list of files that comprise the module that it created.

NOTES

        Export-PSSession relies on the Windows PowerShell remoting infrastructure. To use this cmdlet, the computer must be configured for remoting. For more information, see about_remote_requirements.

        You cannot use Export-PSSession to export a Windows PowerShell provider.

        Exported commands run implicitly in the PSSession from which they were exported. However, the details of running the commands remotely are handled entirely by Windows PowerShell. You can run the exported commands just as you would run local commands.

        Export-Module captures and saves information about the PSSession in the module that it exports. If the PSSession from which the commands were exported is closed when you import the module, and there are no active PSSessions to the same computer, the commands in the module attempt to re-create the PSSession. If attempts to re-create the PSSession fail, the exported commands will not run.

        The session information that Export-Module captures and saves in the module does not include session options, such as those that you specify in the $PSSessionOption automatic Variable or by using the SessionOption parameters of the New-PSSession, Enter-PSSession, or Invoke-Command cmdlet. If the original PSSession is closed when you import the module, the module will use another PSSession to the same computer, if one is available. To enable the imported commands to run in a correctly configured session, create a PSSession with the options that you want before you import the module.

        To find the commands to export, Export-PSSession uses the Invoke-Command cmdlet to run a Get-Command command in the PSSession. To get and save formatting data for the commands, it uses the Get-FormatData and Export-FormatData cmdlets. You might see error messages from Invoke-Command, Get-Command, Get-FormatData, and Export-FormatData when you run an Export-PSSession command. Also, Export-PSSession cannot export commands from a session that does not include the Get-Command, Get-FormatData, Select-Object, and Get-Help cmdlets.

        Export-PSSession uses the Write-Progress cmdlet to display the progress of the command. You might see the progress bar while the command is running.

        Exported commands have the same limitations as other remote commands, including the inability to start a program with a user interface, such as Notepad.

        Because Windows PowerShell profiles are not run in PSSessions, the commands that a profile adds to a session are not available to Export-PSSession. To export commands from a profile, use an Invoke-Command command to run the profile in the PSSession manually before exporting commands.

        The module that Export-PSSession creates might include a formatting file, even if the command does not import formatting data. If the command does not import formatting data, any formatting files that are created will not contain formatting data.

    ————————– EXAMPLE 1 ————————–

    C:\PS>$s = New-PSSession -computerName Server01

    C:\PS> Export-PSSession -Session $s -OutputModule Server01

    Description
    ———–
    The commands in this example export all commands from a PSSession on the Server01 computer to the Server01 module on the local computer except for commands that have the same names as commands in the current session. It also exports the formatting data for the commands.

    The first command creates a PSSession on the Server01 computer. The second command exports the commands and formatting data from the session into the Server01 module.

    ————————– EXAMPLE 2 ————————–

    C:\PS>$s = New-PSSession -ConnectionUri http://exchange.microsoft.com/mailbox -credential exchangeadmin01@hotmail.com -authentication negotiate

    C:\PS> Export-PSSession -Session $r -Module exch* -CommandName get-*, set-* -FormatTypeName * -OutputModule $pshome\Modules\Exchange -Encoding ASCII

    Description
    ———–
    These commands export the Get and Set commands from a Microsoft Exchange Server snap-in on a remote computer to an Exchange module in the $pshome\Modules directory on the local computer.

    Placing the module in the $pshome\Module directory makes it accessible to all users of the computer.

    ————————– EXAMPLE 3 ————————–

    C:\PS>$s = New-PSSession -computerName Server01 -credential Server01\User01

    C:\PS> Export-PSSession -Session $s -OutputModule TestCmdlets -type cmdlet -CommandName *test* -FormatTypeName *

    C:\PS> Remove-PSSession $s

    C:\PS> Import-Module TestCmdlets

    C:\PS> Get-Help test*

    C:\PS> test-files

    Description
    ———–
    These commands export cmdlets from a PSSession on a remote computer and save them in a module on the local computer. Then, the commands add the cmdlets from the module to the current session so that they can be used.

    The first command creates a PSSession on the Server01 computer and saves it in the $s Variable.

    The second command exports the cmdlets whose names begin with “Test” from the PSSession in $s to the TestCmdlets module on the local computer.

    The third command uses the Remove-PSSession cmdlet to delete the PSSession in $s from the current session. This command shows that the PSSession need not be active to use the commands that were imported from it.

    The fourth command, which can be run in any session at any time, uses the Import-Module cmdlet to add the cmdlets in the TestCmdlets module to the current session.

    The fifth command uses the Get-Help cmdlet to get help for cmdlets whose names begin with “Test.” After the commands in a module are added to the current session, you can use the Get-Help and Get-Command cmdlets to learn about the imported commands, just as you would use them for any command in the session.

    The sixth command uses the Test-Files cmdlet, which was exported from the Server01 computer and added to the session.

    Although it is not evident, the Test-Files command actually runs in a remote session on the computer from which the command was imported. Windows PowerShell creates a session from information that is stored in the module.

    ————————– EXAMPLE 4 ————————–

    C:\PS>Export-PSSession -Session $s -AllowClobber -OutputModule AllCommands

    Description
    ———–
    This command exports all commands and all formatting data from the PSSession in the $s Variable into the current session. The command uses the AllowClobber parameter to include commands with the same names as commands in the current session.

    ————————– EXAMPLE 5 ————————–

    C:\PS>$options = New-PSSessionOption -NoMachineProfile

    C:\PS> $s = New-PSSession -computername Server01 -Sessionoption $options

    C:\PS> Export-PSSession -Session $s -OutputModule Server01

    C:\PS> Remove-PSSession $s

    C:\PS> New-PSSession -computername Server01 -Sessionoption $options

    C:\PS> Import-Module Server01

    Description
    ———–
    This example shows how to run the exported commands in a session with particular options when the PSSession from which the commands were exported is closed.

    When you use Export-PSSession, it saves information about the original PSSession in the module that it creates. When you import the module, if the original remote session is closed, the module will use any open remote session that connects to originating computer.

    If the current session does not include a remote session to the originating computer, the commands in the module will re-establish a session to that computer. However, Export-PSSession does not save special options, such as those set by using the SessionOption parameter of New-PSSession, in the module.

    Therefore, if you want to run the exported commands in a remote session with particular options, you need to create a remote session with the options that you want before you import the module.

    The first command uses the New-PSSessionOption cmdlet to create a PSSessionOption object, and it saves the object in the $options Variable.

    The second command creates a PSSession that includes the specified options. The command uses the New-PSSession cmdlet to create a PSSession on the Server01 computer. It uses the SessionOption parameter to submit the option object in $options.

    The third command uses the Export-PSSession cmdlet to export commands from the PSSession in $s to the Server01 module.

    The fourth command uses the Remove-PSSession cmdlet to delete the PSSession in the $s Variable.

    The fifth command uses the New-PSSession cmdlet to create a new PSSession that connects to the Server01 computer. This PSSession also uses the session options in the $options Variable.

    The sixth command uses the Import-Module cmdlet to import the commands from the Server01 module. The commands in the module run in the PSSession on the Server01 computer.

RELATED LINKS
    Online version: http://go.microsoft.com/fwlink/?LinkID=135213
    about_command_precedence
    Import-PSSession
    New-PSSession
    Import-Module
    Invoke-Command
    about_pssessions