Tag Archives: InputObject

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-Unique

NAME
    Get-Unique

SYNOPSIS
    Returns the unique items from a sorted list.

SYNTAX
    Get-Unique [-AsString] [-InputObject <psobject>] [<CommonParameters>]

    Get-Unique [-OnType] [-InputObject <psobject>] [<CommonParameters>]

DESCRIPTION
    The Get-Unique cmdlet compares each item in a sorted list to the next item, eliminates duplicates, and returns only one instance of each item. The list must be sorted for the cmdlet to work properly.

PARAMETERS
    -AsString [<SwitchParameter>]
        Treats the data as a string. Without this parameter, data is treated as an object, so when you submit a collection of objects of the same type to Get-Unique, such as a collection of files, it returns just one (the first). You can use this parameter to find the unique values of object properties, such as the file names.

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

    -InputObject <psobject>
        Accepts input for Get-Unique. Enter a Variable that contains the objects or type a command or expression that gets the objects.

        Get-Unique treats the input submitted by using InputObject as a collection; it does not enumerate individual items in the collection. Because the collection is a single item, input submitted by using InputObject is always returned unchanged.

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

    -OnType [<SwitchParameter>]
        Returns only one object of each type.

        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.PSObject
        You can pipe any type of object to Get-Unique.

OUTPUTS
    System.Management.Automation.PSObject
        The type of object that Get-Unique returns is determined by the input.

NOTES

        You can also refer to Get-Unique by its built-in Alias, “gu”. For more information, see about_aliases.

        To sort a list, use Sort-Object. You can also use the Unique parameter of Sort-Object to find the unique items in a list.

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

    C:\PS>$a = $(foreach ($line in Get-Content C:\Test1\File1.txt) {$line.tolower().split(” “)}) | sort | Get-Unique

    C:\PS> $a.count

    Description
    ———–
    These commands find the number of unique words in a text file.

    The first command gets the content of the File.txt file. It converts each line of text to lowercase letters and then splits each word onto a separate line at the space (” “). Then, it sorts the resulting list alphabetically (the default) and uses the Get-Unique cmdlet to eliminate any duplicate words. The results are stored in the $a Variable.

    The second command uses the Count property of the collection of strings in $a to determine how many items are in $a.

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

    C:\PS>1,1,1,1,12,23,4,5,4643,5,3,3,3,3,3,3,3 | Sort-Object | Get-Unique

    Description
    ———–
    This command finds the unique members of the set of integers. The first command takes an array of integers typed at the command line, pipes them to the Sort-Object cmdlet to be sorted, and then pipes them to Get-Unique, which eliminates duplicate entries.

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

    C:\PS>Get-ChildItem | Sort-Object {$_.GetType()} | unique -OnType

    Description
    ———–
    This command uses the Get-ChildItem cmdlet to retrieve the contents of the local directory, which includes files and directories. The pipeline operator (|) sends the results to the Sort-Object cmdlet. The “$_.GetType()” statement applies the GetType method to each file or directory. Then, Sort-Object sorts the items by type. Another pipeline operator sends the results to Get-Unique. The OnType parameter directs Get-Unique to return only one object of each type.

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

    C:\PS>Get-Process | Sort-Object | select processname | Get-Unique -AsString

    Description
    ———–
    This command gets the names of processes running on the computer with duplicates eliminated.

    The Get-Process command gets all of the processes on the computer. The pipeline operator (|) passes the result to Sort-Object, which, by default, sorts the processes alphabetically by ProcessName. The results are piped to the Select-Object cmdlet, which selects only the values of the ProcessName property of each object. The results are then piped to Get-Unique to eliminate duplicates.

    The AsString parameter tells Get-Unique to treat the ProcessName values as strings. Without this parameter, Get-Unique treats the ProcessName values as objects and returns only one instance of the object, that is, the first process name in the list.

RELATED LINKS
    Online version: http://go.microsoft.com/fwlink/?LinkID=113335
    Select-Object
    Sort-Object

Get-Member

NAME
    Get-Member

SYNOPSIS
    Gets the properties and methods of objects.

SYNTAX
    Get-Member [[-Name] <string[]>] [-Force] [-InputObject <psobject>] [-MemberType {AliasProperty | CodeProperty | Property | NoteProperty | ScriptProperty | Properties | PropertySet | Method | CodeMethod | ScriptMethod | Methods | ParameterizedProperty | MemberSet | Event | All}] [-Static] [-View {Extended | Adapted | Base | All}] [<CommonParameters>]

DESCRIPTION
    The Get-Member cmdlet gets the “members” (properties and methods) of objects.

    To specify the object, use the InputObject parameter or pipe an object to Get-Member. To retrieve information about static members (members of the class, not of the instance), use the Static parameter. To get only certain types of members, such as NoteProperties, use the MemberType parameter.

PARAMETERS
    -Force [<SwitchParameter>]
        Adds the intrinsic members (PSBase, PSAdapted, PSObject, PSTypeNames) and the compiler-generated get_ and set_ methods to the display. By default, Get-Member gets these properties in all views other than “Base” and “Adapted,” but it does not display them.

        The following list describes the properties that are added when you use the Force parameter:

        — PSBase: The original properties of the .NET Framework object without extension or adaptation. These are the properties defined for the object class and listed in MSDN.
        — PSAdapted: The properties and methods defined in the Windows PowerShell extended type system.
        — PSExtended: The properties and methods that were added in the Types.ps1xml files or by using the Add-Member cmdlet.
        — PSObject: The adapter that converts the base object to a Windows PowerShell PSObject object.
        — PSTypeNames: A list of object types that describe the object, in order of specificity. When formatting the object, Windows PowerShell searches for the types in the Format.ps1xml files in the Windows PowerShell installation directory ($pshome). It uses the formatting definition for the first type that it finds.

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

    -InputObject <psobject>
        Specifies the object whose members are retrieved.

        Using the InputObject parameter is not the same as piping an object to Get-Member. The differences are as follows:

        — When you pipe a collection of objects to Get-Member, Get-Member gets the members of the individual objects in the collection, such as the properties of the integers in an array of integers.

        — When you use InputObject to submit a collection of objects, Get-Member gets the members of the collection, such as the properties of the array in an array of integers.

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

    -MemberType <PSMemberTypes>
        Gets only members with the specified member type. The default is All.

        The valid values for this parameter are:

        — AliasProperty: A property that defines a new name for an existing property.
        — CodeMethod: A method that references a static method of a .NET Framework class.
        — CodeProperty: A property that references a static property of a .NET Framework class.
        — Event: Indicates that the object sends a message to indicate an action or a change in state.
        — MemberSet: A predefined collection of properties and methods, such as PSBase, PSObject, and PSTypeNames.
        — Method: A method of the underlying .NET Framework object.
        — NoteProperty: A property with a static value.
        — ParameterizedProperty: A property that takes parameters and parameter values.
        — Property: A property of the underlying .NET Framework object.
        — PropertySet: A predefined collection of object properties.
        — ScriptMethod: A method whose value is the output of a script.
        — ScriptProperty: A property whose value is the output of a script.

        — All: Gets all member types.
        — Methods: Gets all types of methods of the object (for example, Method, CodeMethod, ScriptMethod).
        — Properties: Gets all types of properties of the object (for example, Property, CodeProperty, AliasProperty, ScriptProperty).

        Not all objects have every type of member. If you specify a member type that the object does not have, Windows PowerShell returns a null value.

        To get related types of members, such as all extended members, use the View parameter. If you use the MemberType parameter with the Static or View parameters, Get-Member gets the members that belong to both sets.

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

    -Name <string[]>
        Specifies the names of one or more properties or methods of the object. Get-Member gets only the specified properties and methods.

        If you use the Name parameter with the MemberType, View, or Static parameters, Get-Member gets only the members that satisfy the criteria of all parameters.

        To get a static member by name, use the Static parameter with the Name parameter.

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

    -Static [<SwitchParameter>]
        Gets only the static properties and methods of the object.

        Static properties and methods are defined on the class of objects, not on any particular instance of the class.

        If you use the Static parameter with the View parameter, the View parameter is ignored. If you use the Static parameter with the MemberType parameter, Get-Member gets only the members that belong to both sets.

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

    -View <PSMemberViewTypes>
        Gets only particular types of members (properties and methods). Specify one or more of the values. The default is “Adapted, Extended”.

        Valid values are:
        — Base: Gets only the original properties and methods of the .NET Framework object (without extension or adaptation).
        — Adapted: Gets only the properties and methods defined in the Windows PowerShell extended type system.
        — Extended: Gets only the properties and methods that were added in the Types.ps1xml files or by using the Add-Member cmdlet.
        — All: Gets the members in the Base, Adapted, and Extended views.

        The View parameter determines the members retrieved, not just the display of those members.

        To get particular member types, such as script properties, use the MemberType parameter. If you use the MemberType and View parameters in the same command, Get-Member gets the members that belong to both sets. If you use the Static and View parameters in the same command, the View parameter is ignored.

        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.PSObject
        You can pipe any object to Get-Member

OUTPUTS
    Microsoft.PowerShell.Commands.MemberDefinition
        Get-Member returns an object for each property or method that its gets.

NOTES

        You can retrieve information about a collection object either by using the InputObject parameter or by piping the object, preceded by a comma, to Get-Member.

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

    C:\PS>Get-Service | Get-Member

     TypeName: System.ServiceProcess.ServiceController

    Name                     MemberType    Definition
    —-                     ———-    ———-
    Name                     AliasProperty Name = ServiceName
    Close                     Method        System.Void Close()
    Continue                 Method        System.Void Continue()
    CreateObjRef             Method        System.Runtime.Remoting.ObjRef CreateObjRef(Type requestedType)
    Dispose                 Method        System.Void Dispose()
    Equals                    Method        System.Boolean Equals(Object obj)
    ExecuteCommand            Method        System.Void ExecuteCommand(Int32 command)
    GetHashCode             Method        System.Int32 GetHashCode()
    GetLifetimeService        Method        System.Object GetLifetimeService()
    GetType                 Method        System.Type GetType()
    InitializeLifetimeService Method        System.Object InitializeLifetimeService()
    Pause                     Method        System.Void Pause()
    Refresh                 Method        System.Void Refresh()
    Start                     Method        System.Void Start(), System.Void Start(String[] args)
    Stop                     Method        System.Void Stop()
    ToString                 Method        System.String ToString()
    WaitForStatus             Method        System.Void WaitForStatus(ServiceControllerStatus desiredStatus), System.Voi…
    CanPauseAndContinue     Property     System.Boolean CanPauseAndContinue {get;}
    CanShutdown             Property     System.Boolean CanShutdown {get;}
    CanStop                 Property     System.Boolean CanStop {get;}
    Container                 Property     System.ComponentModel.IContainer Container {get;}
    DependentServices         Property     System.ServiceProcess.ServiceController[] DependentServices {get;}
    DisplayName             Property     System.String DisplayName {get;set;}
    MachineName             Property     System.String MachineName {get;set;}
    ServiceHandle             Property     System.Runtime.InteropServices.SafeHandle ServiceHandle {get;}
    ServiceName             Property     System.String ServiceName {get;set;}
    ServicesDependedOn        Property     System.ServiceProcess.ServiceController[] ServicesDependedOn {get;}
    ServiceType             Property     System.ServiceProcess.ServiceType ServiceType {get;}
    Site                     Property     System.ComponentModel.ISite Site {get;set;}
    Status                    Property     System.ServiceProcess.ServiceControllerStatus Status {get;}

    Description
    ———–
    This command displays the properties and methods of the process objects (System.ServiceProcess.ServiceController) that are generated by the Get-Service cmdlet.

    The command uses the pipeline operator (|) to send the output of a Get-Service command to Get-Member.

    Because the Get-Member part of the command does not have any parameters, it uses all of the default values. As such, it gets all member types, but it does not get static members and does not display intrinsic members.

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

    C:\PS>Get-Service | Get-Member -Force

    C:\PS> (Get-Service -schedule).psbase

    Description
    ———–
    This example gets all of the members (properties and methods) of the service objects (System.ServiceProcess.ServiceController) retrieved by the Get-Service cmdlet, including the intrinsic members, such as PSBase and PSObject, and the get_ and set_ methods.

    The first command uses the Get-Service cmdlet to get objects that represent the services on the system. It uses a pipeline operator (|) to pass the service objects to the Get-Member cmdlet.

    The Get-Member command uses the Force parameter to add the intrinsic members and compiler-generated members of the objects to the display. Get-Member gets these members, but it hides them by default.

    You can use these properties and methods in the same way that you would use an adapted method of the object. The second command shows how to display the value of the PSBase property of the Schedule service.

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

    C:\PS>Get-Service    | Get-Member -View extended

     TypeName: System.ServiceProcess.ServiceController

    Name MemberType    Definition
    —- ———-    ———-
    Name AliasProperty Name = ServiceName

    Description
    ———–
    This command gets the methods and properties of service objects that were extended by using the Types.ps1xml file or the Add-Member cmdlet.

    The Get-Member command uses the View parameter to get only the extended members of the service objects. In this case, the extended member is the Name property, which is an Alias property of the ServiceName property.

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

    C:\PS>Get-Eventlog -log system | gm -MemberType scriptproperty

     TypeName: System.Diagnostics.EventLogEntry

    Name    MemberType     Definition
    —-    ———-     ———-
    EventID ScriptProperty System.Object EventID {get=$this.get_EventID() -band 0xFFFF;}

    Description
    ———–
    This command gets the script properties of event log objects in the System log in Event Viewer. In this case, the only script property is the EventID.

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

    C:\PS>Get-Eventlog -log system | Get-Member -MemberType scriptproperty

     TypeName: System.Diagnostics.EventLogEntry

    Name    MemberType     Definition
    —-    ———-     ———-
    EventID ScriptProperty System.Object EventID {get=$this.get_EventID() -band 0xFFFF;}

    Description
    ———–
    This command gets the script properties of event log objects in the System log in Event Viewer.

    The command uses the MemberType parameter to get only objects with a value of AliasProperty for their MemberType property.

    The command returns the EventID property of the EventLog object.

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

    C:\PS>$a = “Get-Process“, “Get-Service“, “Get-Culture“, “Get-PSDrive“, “Get-ExecutionPolicy

    C:\PS> foreach ($cmdlet in $a) {Invoke-Expression $cmdlet | Get-Member -Name machinename}

    TypeName: System.Diagnostics.Process

    Name        MemberType Definition
    —-        ———- ———-
    MachineName Property System.String MachineName {get;}

     TypeName: System.ServiceProcess.ServiceController

    Name        MemberType Definition
    —-        ———- ———-
    MachineName Property System.String MachineName {get;set;}

    Description
    ———–
    This command gets objects that have a MachineName property from a list of cmdlets.

    The first command stores the names of several cmdlets in the $a Variable.

    The second command uses a ForEach statement to invoke each command, send the results to Get-Member, and limit the results from Get-Member to members that have the name “MachineName.”

    The results show that only process objects (System.Diagnostics.Process) and service objects (System.ServiceProcess.ServiceController) have a MachineName property.

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

    C:\PS>$a = Get-Member -InputObject @(1)

    C:\PS>$a.count

    1

    C:\PS> $a = Get-Member -InputObject 1,2,3

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

    C:\PS>$a.count
    1

    Description
    ———–
    This example demonstrates how to find the properties and methods of an array of objects when you have only one object of the given type.

    Because the goal of the command is to find the properties of an array, the first command uses the InputObject parameter. It uses the “at” symbol (@) to indicate an array. In this case, the array contains only one object, the integer 1.

    The third command uses the Get-Member cmdlet to get the properties and methods of an array of integers, and the command saves them in the $a Variable.

    The fourth command uses the Count property of the array to find the number of objects in the $a Variable.

RELATED LINKS
    Online version: http://go.microsoft.com/fwlink/?LinkID=113322
    Add-Member
    Get-Help
    Get-Command
    Get-PSDrive

Format-Wide

NAME
    Format-Wide

SYNOPSIS
    Formats objects as a wide table that displays only one property of each object.

SYNTAX
    Format-Wide [[-Property] <Object>] [-AutoSize] [-Column <int>] [-DisplayError] [-Expand <string>] [-Force] [-GroupBy <Object>] [-InputObject <psobject>] [-ShowError] [-View <string>] [<CommonParameters>]

DESCRIPTION
    The Format-Wide cmdlet formats objects as a wide table that displays only one property of each object. You can use the Property parameter to determine which property is displayed.

PARAMETERS
    -AutoSize [<SwitchParameter>]
        Adjusts the column size and number of columns based on the width of the data. By default, the column size and number are determined by the view. You cannot use the AutoSize and Column parameters in the same command.

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

    -Column <int>
        Specifies the number of columns in the display. You cannot use the AutoSize and Column parameters in the same command.

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

    -DisplayError [<SwitchParameter>]
        Displays errors at the command line.

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

    -Expand <string>
        Formats the collection object, as well as the objects in the collection. This parameter is designed to format objects that support the ICollection (System.Collections) interface. The default value is EnumOnly.

        Valid values are:
        — EnumOnly: Displays the properties of the objects in the collection.
        — CoreOnly: Displays the properties of the collection object.
        — Both: Displays the properties of the collection object and the properties of objects in the collection.

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

    -Force [<SwitchParameter>]
        Overrides restrictions that prevent the command from succeeding, just so the changes do not compromise security. For example, Force will override the read-only attribute or create directories to complete a file path, but it will not attempt to change file permissions.

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

    -GroupBy <Object>
        Formats the output in groups based on a shared property or value. Enter an expression or a property of the output.

        The value of the GroupBy parameter can be a new calculated property. To create a calculated, property, use a hash table. Valid keys are:

        — Name (or Label) <string>
        — Expression <string> or <script block>
        — FormatString <string>

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

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

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

    -Property <Object>
        Specifies the object properties that appear in the display and the order in which they appear. Wildcards are permitted.

        If you omit this parameter, the properties that appear in the display depend on the object being displayed. The parameter name (“Property”) is optional. You cannot use the Property and View parameters in the same command.

        The value of the Property parameter can be a new calculated property. To create a calculated, property, use a hash table. Valid keys are:

        — Expression <string> or <script block>
        — FormatString <string>

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

    -ShowError [<SwitchParameter>]
        Sends errors through the pipeline.

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

    -View <string>
        Specifies the name of an alternate table format or “view.” You cannot use the Property and View parameters in the same 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
    System.Management.Automation.PSObject
        You can pipe any object to Format-Wide.

OUTPUTS
    Microsoft.PowerShell.Commands.Internal.Format
        Format-Wide returns format objects that represent the table.

NOTES

        You can also refer to Format-Wide by its built-in Alias, “fw”. For more information, see about_aliases.

        The GroupBy parameter assumes that the objects are sorted. Before using Format-Custom to group the objects, use Sort-Object to sort them.

        The -View parameter lets you specify an alternate format for the table. You can use the views defined in the *.format.PS1XML files in the Windows PowerShell directory or you can create your own views in new PS1XML files and use the Update-FormatData cmdlet to include them in Windows PowerShell.

        The alternate view for the View parameter must use table format; if it does not, the command fails. If the alternate view is a list, use Format-List. If the alternate view is neither a list nor a table, use Format-Custom.

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

    C:\PS>Get-ChildItem | Format-Wide -Column 3

    Description
    ———–
    This command displays the names of files in the current directory in three columns across the screen. The Get-ChildItem cmdlet gets objects representing each file in the directory. The pipeline operator (|) passes the file objects through the pipeline to Format-Wide, which formats them for output. The Column parameter specifies the number of columns.

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

    C:\PS>Get-ChildItem HKCU:\software\microsoft | Format-Wide -Property pschildname -AutoSize

    Description
    ———–
    This command displays the names of Registry keys in the HKEY_CURRENT_USER\Software\Microsoft key. The Get-ChildItem cmdlet gets objects representing the keys. The path is specified as “HKCU:”, one of the drives exposed by the Windows PowerShell Registry provider, followed by the key path. The pipeline operator (|) passes the Registry key objects through the pipeline to Format-Wide, which formats them for output. The Property parameter specifies the name of the property, and the AutoSize parameter adjusts the columns for readability.

RELATED LINKS
    Online version: http://go.microsoft.com/fwlink/?LinkID=113304

Format-Table

NAME
    Format-Table

SYNOPSIS
    Formats the output as a table.

SYNTAX
    Format-Table [[-Property] <Object[]>] [-AutoSize] [-DisplayError] [-Expand <string>] [-Force] [-GroupBy <Object>] [-HideTableHeaders] [-InputObject <psobject>] [-ShowError] [-View <string>] [-Wrap] [<CommonParameters>]

DESCRIPTION
    The Format-Table cmdlet formats the output of a command as a table with the selected properties of the object in each column. The object type determines the default layout and properties that are displayed in each column, but you can use the Property parameter to select the properties that you want to see.

    You can also use a hash table to add calculated properties to an object before displaying it and to specify the column headings in the table. To add a calculated property, use the Property or GroupBy parameters.

PARAMETERS
    -AutoSize [<SwitchParameter>]
        Adjusts the column size and number of columns based on the width of the data. By default, the column size and number are determined by the view.

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

    -DisplayError [<SwitchParameter>]
        Displays errors at the command line.

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

    -Expand <string>
        Formats the collection object, as well as the objects in the collection. This parameter is designed to format objects that support the ICollection (System.Collections) interface. The default value is EnumOnly.

        Valid values are:
        — EnumOnly: Displays the properties of the objects in the collection.
        — CoreOnly: Displays the properties of the collection object.
        — Both: Displays the properties of the collection object and the properties of objects in the collection.

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

    -Force [<SwitchParameter>]
        Directs the cmdlet to display all of the error information. Use with the DisplayError or ShowError parameters. By default, when an error object is written to the error or display streams, only some of the error information is displayed.

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

    -GroupBy <Object>
        Arranges sorted output in separate tables based on a property value. For example, you can use GroupBy to list services in separate tables based on their status.

        Enter an expression or a property of the output. The output must be sorted before you send it to Format-Table.

        The value of the GroupBy parameter can be a new calculated property. To create a calculated, property, use a hash table. Valid keys are:

        — Name (or Label) <string>
        — Expression <string> or <script block>
        — FormatString <string>

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

    -HideTableHeaders [<SwitchParameter>]
        Omits the column headings from the table.

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

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

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

    -Property <Object[]>
        Specifies the object properties that appear in the display and the order in which they appear. Type one or more property names (separated by commas), or use a hash table to display a calculated property. Wildcards are permitted.

        If you omit this parameter, the properties that appear in the display depend on the object being displayed. The parameter name (“Property”) is optional. You cannot use the Property and View parameters in the same command.

        The value of the Property parameter can be a new calculated property. To create a calculated, property, use a hash table. Valid keys are:

        — Name (or Label) <string>
        — Expression <string> or <script block>
        — FormatString <string>
        — Width <int32>
        — Alignment (value can be “Left”, “Center”, or “Right”)

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

    -ShowError [<SwitchParameter>]
        Sends errors through the pipeline.

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

    -View <string>
        Specifies the name of an alternate table format or “view.” You cannot use the Property and View parameters in the same command.

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

    -Wrap [<SwitchParameter>]
        Displays text that exceeds the column width on the next line. By default, text that exceeds the column width is truncated.

        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.PSObject
        You can pipe any object to Format-Table.

OUTPUTS
    Microsoft.PowerShell.Commands.Internal.Format
        Format-Table returns format objects that represent the table.

NOTES

        You can also refer to Format-Table by its built-in Alias, “FT”. For more information, see about_aliases.

        The GroupBy parameter assumes that the objects are sorted. Before using Format-Custom to group the objects, use Sort-Object to sort them.

        The View parameter lets you specify an alternate format for the table. You can use the views defined in the *.format.PS1XML files in the Windows PowerShell directory or you can create your own views in new PS1XML files and use the Update-FormatData cmdlet to include them in Windows PowerShell.

        The alternate view for the View parameter must use table format; if it does not, the command fails. If the alternate view is a list, use Format-List. If the alternate view is neither a list nor a table, use Format-Custom.

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

    C:\PS>Get-PSSnapin | Format-Table -auto

    Description
    ———–
    This command formats information about Windows PowerShell snap-ins in a table. By default, they are formatted in a list. The Get-PSSnapin cmdlets gets objects representing the snap-ins. The pipeline operator (|) passes the object to the Format-Table command. Format-Table formats the objects in a table. The Autosize parameter adjusts the column widths to minimize truncation.

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

    C:\PS>Get-Process | Sort-Object -Property basepriority | Format-Table -GroupBy basepriority -Wrap

    Description
    ———–
    This command displays the processes on the computer in groups with the same base priority.

    The Get-Process cmdlet gets objects representing each process on the computer. The pipeline operator (|) passes the object to the Sort-Object cmdlet, which sorts the objects in order of their base priority.

    Another pipeline operator passes the results to the Format-Table command. The GroupBy parameter arranges the data about the processes into groups based on the value of their BasePriority property. The Wrap parameter ensures that data is not truncated.

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

    C:\PS>Get-Process | Sort-Object starttime | Format-Table -View starttime

    Description
    ———–
    This command displays information about the processes on the computer in group based on the start date of the process. It uses the Get-Process cmdlet to get objects representing the processes on the computer. The pipeline operator (|) sends the output of Get-Process to the Sort-Object cmdlet, which sorts it based on the StartTime property. Another pipeline operator sends the sorted results to Format-Table.

    The View parameter is used to select the StartTime view that is defined in the DotNetTypes.format.ps1xml formatting file for System.Diagnostics.Process objects, such as those returned by Get-Process. This view converts the StartTime of the process to a short date and then groups the processes by start date.

    The DotNetTypes.format.ps1xml formatting file also contains a Priority view for processes, and you can create your own format.ps1xml files with customized views.

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

    C:\PS>Get-Service | Format-Table -Property Name, DependentServices

    Description
    ———–
    This command displays all of the services on the computer in a table with two columns, Name and DependentServices. The command uses the Get-Service cmdlet to get all of the services on the computer. The pipeline operator (|) sends the results to the Format-Table cmdlet, which formats the output in a table. The Property parameter specifies the properties that appear in the table as columns. The name of the Property parameter is optional, so you can omit it (“Format-Table name, dependentservices”).

    Property and DependentServices are just two of the properties of service objects. To view all of the properties, type “Get-Service | Get-Member“.

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

    C:\PS>Get-Process notepad | Format-Table ProcessName, `
    @{Label=”TotalRunningTime”; Expression={(Get-Date) – $_.StartTime}}

    Description
    ———–
    This command shows how to use a calculated property in a table. The command displays a table with the process name and total running time of all Notepad processes on the local computer. The total running time is calculated by subtracting the start time of each process from the current time.

    The command uses the Get-Process cmdlet to get all processes named “Notepad” on the local computer. The pipeline operator (|) sends the results to Format-Table, which displays a table with two columns: ProcessName, a standard property of processes, and TotalRunningTime, a calculated property.

    The TotalRunningTime property is specified by a hash table with two keys, Label and Expression. The name of the property is assigned to the Label key. The calculation is assigned to the Expression key. The expression gets the StartTime property of each process object and subtracts it from the result of a Get-Date command, which gets the current date (and time).

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

    C:\PS>$processes = Get-WmiObject -ComputerName Server01 win32_process -filter “name=’notepad.exe'”

    C:\PS> $processes | Format-Table ProcessName, @{ Label = “Total Running Time”; `
    Expression={(Get-Date) – $_.ConvertToDateTime($_.CreationDate)}}

    Description
    ———–
    These commands are similar to the previous command, except that these commands use the Get-WmiObject cmdlet and the Win32_Process class to display information about Notepad processes on a remote computer.

    The first command uses the Get-WmiObject cmdlet to get instances of the Windows Management Instrumentation (WMI) Win32_Process class that describes all of the processes on the Server01 computer that are named Notepad.exe. The command stores the process information in the $processes Variable.

    The second command uses a pipeline operator (|) to send the process information in the $processes Variable to the Format-Table cmdlet, which displays the ProcessName of each process along with a new calculated property.

    The command assigns the name of the new calculated property, Total Running Time, to the Label key. The script block that is assigned to the Expression key calculates how long the process has been running by subtracting the creation date of the process from the current date. The Get-Date cmdlet gets the current date. The ConvertToDateTime method converts the CreationDate property of the Win32_Process object from a WMI CIM_DATETIME object to a Microsoft .NET Framework DateTime object that can be compared with the output of Get-Date. Then, the converted creation date is subtracted from the current date. The result is the value of Total Running Time.

    The backtick characters (`) are line continuation characters.

RELATED LINKS
    Online version: http://go.microsoft.com/fwlink/?LinkID=113303
    Format-List
    Format-Wide
    Format-Custom

Format-List

NAME
    Format-List

SYNOPSIS
    Formats the output as a list of properties in which each property appears on a new line.

SYNTAX
    Format-List [[-Property] <Object[]>] [-DisplayError] [-Expand <string>] [-Force] [-GroupBy <Object>] [-InputObject <psobject>] [-ShowError] [-View <string>] [<CommonParameters>]

DESCRIPTION
    The Format-List cmdlet formats the output of a command as a list of properties in which each property is displayed on a separate line. You can use Format-List to format and display all or selected properties of an object as a list (Format-List *).

    Because more space is available for each item in a list than in a table, Windows PowerShell displays more properties of the object in the list, and the property values are less likely to be truncated.

PARAMETERS
    -DisplayError [<SwitchParameter>]
        Displays errors at the command line.

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

    -Expand <string>
        Formats the collection object, as well as the objects in the collection. This parameter is designed to format objects that support the ICollection (System.Collections) interface. The default value is EnumOnly.

        Valid values are:
        — EnumOnly: Displays the properties of the objects in the collection.
        — CoreOnly: Displays the properties of the collection object.
        — Both: Displays the properties of the collection object and the properties of objects in the collection.

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

    -Force [<SwitchParameter>]
        Directs the cmdlet to display all of the error information. Use with the DisplayError or ShowError parameters. By default, when an error object is written to the error or display streams, only some of the error information is displayed.

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

    -GroupBy <Object>
        Formats the output in groups based on a shared property or value. Enter an expression or a property of the output.

        The value of the GroupBy parameter can be a new calculated property. To create a calculated, property, use a hash table. Valid keys are:

        — Name (or Label) <string>
        — Expression <string> or <script block>
        — FormatString <string>

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

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

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

    -Property <Object[]>
        Specifies the object properties that appear in the display and the order in which they appear. Wildcards are permitted.

        If you omit this parameter, the properties that appear in the display depend on the object being displayed. The parameter name (“Property”) is optional. You cannot use the Property and View parameters in the same command.

        The value of the Property parameter can be a new calculated property. To create a calculated, property, use a hash table. Valid keys are:

        — Name (or Label) <string>
        — Expression <string> or <script block>
        — FormatString <string>

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

    -ShowError [<SwitchParameter>]
        Sends errors through the pipeline.

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

    -View <string>
        Specifies the name of an alternate list format or “view.” You cannot use the Property and View parameters in the same 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
    System.Management.Automation.PSObject
        You can pipe any object to Format-List.

OUTPUTS
    Microsoft.PowerShell.Commands.Internal.Format
        Format-List returns the format objects that represent the list.

NOTES

        You can also refer to Format-List by its built-in Alias, “FL”. For more information, see about_aliases.

        The format cmdlets, such as Format-List, arrange the data to be displayed but do not display it. The data is displayed by the output features of Windows PowerShell and by the cmdlets that contain the Out verb (the Out cmdlets), such as Out-Host, Out-File, and Out-Printer.

        If you do not use a format cmdlet, Windows PowerShell applies that default format for each object that it displays.

        The GroupBy parameter assumes that the objects are sorted. Before using Format-Custom to group the objects, use Sort-Object to sort them.

        The View parameter lets you specify an alternate format for the table. You can use the views defined in the *.format.PS1XML files in the Windows PowerShell directory, or you can create your own views in new PS1XML files and use the Update-FormatData cmdlet to include them in Windows PowerShell.

        The alternate view for the View parameter must use the list format; if not, the command fails. If the alternate view is a table, use Format-Table. If the alternate view is neither a list nor a table, use Format-Custom.

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

    C:\PS>Get-Service | Format-List

    Description
    ———–
    This command formats information about services on the computer as a list. By default, the services are formatted as a table. The Get-Service cmdlet gets objects representing the services on the computer. The pipeline operator (|) passes the results through the pipeline to Format-List. Then, the Format-List command formats the service information in a list and sends it to the default output cmdlet for display.

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

    C:\PS>$a = Get-ChildItem $pshome\*.ps1xml

    Description
    ———–
    These commands display information about the PS1XML files in the Windows PowerShell directory as a list. The first command gets the objects representing the files and stores them in the $a Variable. The second command uses Format-List to format information about objects stored in $a. This command uses the InputObject parameter to pass the Variable to Format-List, which then sends the formatted output to the default output cmdlet for display.

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

    C:\PS>Get-Process | Format-List -Property name, basepriority, priorityclass

    Description
    ———–
    This command displays the name, base priority, and priority class of each process on the computer. It uses the Get-Process cmdlet to get an object representing each process. The pipeline operator (|) passes the process objects through the pipeline to Format-List. Format-List formats the processes as a list of the specified properties. The “Property” parameter name is optional, so you can omit it.

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

    C:\PS>Get-Process winlogon | Format-List -Property *

    Description
    ———–
    This command displays all of the properties of the Winlogon process. It uses the Get-Process cmdlet to get an object representing the Winlogon process. The pipeline operator (|) passes the Winlogon process object through the pipeline to Format-List. The command uses the Property parameter to specify the properties and the * to indicate all properties. Because the name of the Property parameter is optional, you can omit it and type the command as: “Format-List *”. Format-List automatically sends the results to the default output cmdlet for display.

RELATED LINKS
    Online version: http://go.microsoft.com/fwlink/?LinkID=113302

Format-Custom

NAME
    Format-Custom

SYNOPSIS
    Uses a customized view to format the output.

SYNTAX
    Format-Custom [[-Property] <Object[]>] [-Depth <int>] [-DisplayError] [-Expand <string>] [-Force] [-GroupBy <Object>] [-InputObject <psobject>] [-ShowError] [-View <string>] [<CommonParameters>]

DESCRIPTION
    The Format-Custom cmdlet formats the output of a command as defined in an alternate view. Format-Custom is designed to display views that are not just tables or just lists. You can use the views defined in the *format.PS1XML files in the Windows PowerShell directory, or you can create your own views in new PS1XML files and use the Update-FormatData cmdlet to add them to Windows PowerShell.

PARAMETERS
    -Depth <int>
        Specifies the number of columns in the display.

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

    -DisplayError [<SwitchParameter>]
        Displays errors at the command line.

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

    -Expand <string>
        Formats the collection object, as well as the objects in the collection. This parameter is designed to format objects that support the ICollection (System.Collections) interface. The default value is EnumOnly.

        Valid values are:
        — EnumOnly: Displays the properties of the objects in the collection.
        — CoreOnly: Displays the properties of the collection object.
        — Both: Displays the properties of the collection object and the properties of objects in the collection.

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

    -Force [<SwitchParameter>]
        Directs the cmdlet to display all of the error information. Use with the DisplayError or ShowError parameters. By default, when an error object is written to the error or display streams, only some of the error information is displayed.

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

    -GroupBy <Object>
        Formats the output in groups based on a shared property or value. Enter an expression or a property of the output.

        The value of the GroupBy parameter can be a new calculated property. To create a calculated, property, use a hash table. Valid keys are:

        — Name (or Label) <string>
        — Expression <string> or <script block>
        — FormatString <string>

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

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

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

    -Property <Object[]>
        Specifies the object properties that appear in the display and the order in which they appear. Wildcards are permitted.

        If you omit this parameter, the properties that appear in the display depend on the object being displayed. The parameter name (“Property”) is optional. You cannot use the Property and View parameters in the same command.

        The value of the Property parameter can be a new calculated property. To create a calculated property, use a hash table. Valid keys are:

        — Expression <string> or <script block>
        — Depth <int32>

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

    -ShowError [<SwitchParameter>]
        Sends errors through the pipeline.

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

    -View <string>
        Specifies the name of an alternate format or “view.” If you omit this parameter, Format-Custom uses a default custom view. You cannot use the Property and View parameters in the same 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
    System.Management.Automation.PSObject
        You can pipe any object to Format-Custom

OUTPUTS
    Microsoft.PowerShell.Commands.Internal.Format
        Format-Custom returns the format objects that represent the display.

NOTES

        Format-Custom is designed to display views that are not just tables or just lists. To display an alternate table view, use Format-Table. To display an alternate list view, use Format-List.

        You can also refer to Format-Custom by its built-in Alias, “fc”. For more information, see about_aliases.

        The GroupBy parameter assumes that the objects are sorted. Before using Format-Custom to group the objects, use Sort-Object to sort them.

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

    C:\PS>Get-Command Start-Transcript | Format-Custom -View MyView

    Description
    ———–
    This command formats information about the Start-Transcript cmdlet in the format defined by the MyView view, a custom view created by the user. To run this command successfully, you must first create a new PS1XML file, define the MyView view, and then use the Update-FormatData command to add the PS1XML file to Windows PowerShell.

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

    C:\PS>Get-Process Winlogon | Format-Custom

    Description
    ———–
    This command formats information about the Winlogon process in an alternate customized view. Because the command does not use the View parameter, Format-Custom uses a default custom view to format the data.

RELATED LINKS
    Online version: http://go.microsoft.com/fwlink/?LinkID=113301

ForEach-Object

NAME
    ForEach-Object

SYNOPSIS
    Performs an operation against each of a set of input objects.

SYNTAX
    ForEach-Object [-Process] <ScriptBlock[]> [-Begin <scriptblock>] [-End <scriptblock>] [-InputObject <psobject>] [<CommonParameters>]

DESCRIPTION
    The ForEach-Object cmdlet performs an operation on each of a set of input objects. The input objects can be piped to the cmdlet or specified by using the InputObject parameter.

    The operation to perform is described within a script block that is provided to the cmdlet as the value of the Process parameter. The script block can contain any Windows PowerShell script.

    Within the script block, the current input object is represented by the $_ Variable.
    In addition to using the script block that describes the operations to be carried out on each input object, you can provide two additional script blocks. One, specified as the value of the Begin parameter, runs before the first input object is processed. The other, specified as the value of the End parameter, runs after the last input object is processed.

    The results of the evaluation of all the script blocks, including the ones specified with Begin and End, are passed down the pipeline.

PARAMETERS
    -Begin <scriptblock>
        Specifies a script block to run before processing any input objects.

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

    -End <scriptblock>
        Specifies a script block to run after processing all input objects.

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

    -InputObject <psobject>
        Accepts an object that the script block specified in the process parameter will act upon. Enter a Variable that contains the objects, or type a command or expression that gets the objects.

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

    -Process <ScriptBlock[]>
        Specifies the script block that is applied to each incoming object.

        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.Management.Automation.PSObject
        You can pipe any object to ForEach-Object.

OUTPUTS
    System.Management.Automation.PSObject
        The objects that ForEach-Object returns are determined by the input.

NOTES

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

    C:\PS>30000,56798,12432 | ForEach-Object -Process {$_/1024}

    Description
    ———–
    This command accepts an array of integers, divides each one of them by 1024, and displays the results.

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

    C:\PS>Get-ChildItem C:\ | ForEach-Object -Process { $_.length / 1024 }

    Description
    ———–
    This command retrieves the files and directories in the root of the C: drive, and it returns and displays the size of each of them. The zeros represent directories in which no file size was available.

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

    C:\PS>$events = Get-Eventlog -logname system -newest 1000

    C:\PS> $events | ForEach-Object -Begin {Get-Date} -Process {Out-File -filepath events.txt -append -InputObject $_.message} -End {Get-Date}

    Description
    ———–
    This command retrieves the 1000 most recent events from the system log and stores them in the $events Variable. It then pipes the events to the ForEach-Object cmdlet. The Begin parameter displays the current date and time. Next, the Process parameter uses the Out-File cmdlet to create a text file named events.txt and stores the message property of each of the events in that file. Last, the End parameter is used to display the date and time after all of the processing has completed.

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

    C:\PS>Get-Itemproperty -path hkcu:\Network\* | ForEach-Object {Set-Itemproperty -path $_.pspath -name RemotePath -value $_.RemotePath.ToUpper();}

    Description
    ———–
    This command changes the value of the RemotePath Registry entry in all of the subkeys under the HKCU:\Network key to uppercase text. You can use this format to change the form or content of a Registry entry value.

    Each subkey in the Network key represents a mapped network drive that will reconnect at logon. The RemotePath entry contains the UNC path of the connected drive. For example, if you map the E: drive to \\Server\Share, there will be an E subkey of HKCU:\Network and the value of the RemotePath Registry entry in the E subkey will be \\Server\Share.

    The command uses the Get-ItemProperty cmdlet to get all of the subkeys of the Network key and the Set-ItemProperty cmdlet to change the value of the RemotePath Registry entry in each key. In the Set-ItemProperty command, the path is the value of the PSPath property of the Registry key. (This is a property of the Microsoft .NET Framework object that represents the Registry key; it is not a Registry entry.) The command uses the ToUpper() method of the RemotePath value, which is a string (REG_SZ).

    Because Set-ItemProperty is changing the property of each key, the ForEach-Object cmdlet is required to access the property.

RELATED LINKS
    Online version: http://go.microsoft.com/fwlink/?LinkID=113300

Export-FormatData

NAME
    Export-FormatData

SYNOPSIS
    Saves formatting data from the current session in a formatting file.

SYNTAX
    Export-FormatData [-Force] [-IncludeScriptBlock] [-InputObject <ExtendedTypeDefinition[]>] [-NoClobber] [-Path <string>] [<CommonParameters>]

DESCRIPTION
    The Export-FormatData cmdlet creates Windows PowerShell formatting files (format.ps1xml) from the formatting objects in the current session. It takes the ExtendedTypeDefinition objects that Get-FormatData returns and saves them in a file in XML format.

    Windows PowerShell uses the data in formatting files (format.ps1xml) to generate the default display of Microsoft .NET Framework objects in the session. You can view and edit the formatting files and use the Update-FormatData cmdlet to add the formatting data to a session.

    For more information about formatting files in Windows PowerShell, see about_Format.ps1xml.

PARAMETERS
    -Force [<SwitchParameter>]
        Overwrites an existing output file, even if the file has the read-only attribute.

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

    -IncludeScriptBlock [<SwitchParameter>]
        Determines whether script blocks in the format data are exported.

        Because script blocks contain code and can be used maliciously, they are not exported by default.

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

    -InputObject <ExtendedTypeDefinition[]>
        Specifies the format data objects to be exported. Enter a Variable that contains the objects or a command that gets the objects, such as a Get-FormatData command. You can also pipe the objects from Get-FormatData to Export-FormatData.

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

    -NoClobber [<SwitchParameter>]
        Prevents the cmdlet from overwriting existing files. By default, Export-FormatData overwrites files without warning unless the file has the read-only attribute.

        To direct Export-FormatData to overwrite read-only files, use the Force parameter.

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

    -Path <string>
        Specifies a location for the output file. Enter a path (optional) and file name with a format.ps1xml file name extension. If you omit the path, Export-FormatData creates the file in the current directory.

        If you use a file name extension other than .ps1xml, the Update-FormatData cmdlet will not recognize the file.

        If you specify an existing file, Export-FormatData overwrites the file without warning, unless the file has the read-only attribute. To overwrite a read-only file, use the Force parameter. To prevent files from being overwritten, use the NoClobber parameter.

        Required?                    false
        Position?                    named
        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.Management.Automation.ExtendedTypeDefinition
        You can pipe ExtendedTypeDefinition objects from Get-FormatData to Export-FormatData.

OUTPUTS
    None
        Export-FormatData does not return any objects. It generates a file and saves it in the specified path.

NOTES

        To use any formatting file, including an exported formatting file, the execution policy for the session must allow scripts and configuration files to run. For more information, see about_execution_policies.

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

    C:\PS>Get-FormatData -typename * | Export-FormatData -Path allformat.ps1xml -IncludeScriptBlock

    Description
    ———–
    This command exports all of the format data in the session to the AllFormat.ps1xml file.

    The command uses the Get-FormatData cmdlet to get the format data in the session. A value of * (all) for the TypeName parameter directs the cmdlet to get all of the data in the session.

    The command uses a pipeline operator (|) to send the format data from the Get-FormatData command to the Export-FormatData cmdlet, which exports the format data to the AllFormat.ps1 file.

    The Export-FormatData command uses the IncludeScriptBlock parameter to include script blocks in the format data in the file.

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

    C:\PS>$f = Get-FormatData -typename helpinfoshort

    C:\PS> Export-FormatData -InputObject $f -Path c:\test\help.format.ps1xml -IncludeScriptBlock

    Description
    ———–
    These commands export the format data for the HelpInfoShort type to the Help.format.ps1xml file.

    The first command uses the Get-FormatData cmdlet to get the format data for the HelpInfoShort type, and it saves it in the $f Variable.

    The second command uses the InputObject parameter of the Export-FormatData to enter the format data saved in the $f Variable. It also uses the IncludeScriptBlock parameter to include script blocks in the output.

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

    C:\PS>Get-FormatData -typename System.Diagnostics.Process | Export-FormatData -Path process.format.ps1xml

    C:\PS> Update-FormatData -prependPath .\process.format.ps1xml

    C:\PS> Get-Process p*

    Handles NPM(K) PM(K) WS(K) VM(M) CPU(s)    Id ProcessName
    ——- —— —– —– —– ——    — ———–
        323                                     5600 powershell
        336                                     3900 powershell_ise
        138                                     4076 PresentationFontCache

    Description
    ———–
    This example shows the effect of omitting the IncludeScriptBlock parameter from an Export-FormatData command.

    The first command uses the Get-FormatData cmdlet to get the format data for the System.Diagnostics.Process object that the Get-Process cmdlet returns. The command uses a pipeline operator (|) to send the formatting data to the Export-FormatData cmdlet, which exports it to the Process.format.ps1xml file in the current directory.

    In this case, the Export-FormatData command does not use the IncludeScriptBlock parameter.

    The second command uses the Update-FormatData cmdlet to add the Process.format.ps1xml file to the current session. The command uses the PrependPath parameter to ensure that the formatting data for process objects in the Process.format.ps1xml file is found before the standard formatting data for process objects.

    The third command shows the effects of this change. The command uses the Get-Process cmdlet to get processes that have names that begin with “P”. The output shows that property values that are calculated by using script blocks are missing from the display.

RELATED LINKS
    Online version: http://go.microsoft.com/fwlink/?LinkID=144302
    Get-FormatData
    Update-FormatData

Export-Clixml

NAME
    Export-Clixml

SYNOPSIS
    Creates an XML-based representation of an object or objects and stores it in a file.

SYNTAX
    Export-Clixml [-Path] <string> -InputObject <psobject> [-Depth <int>] [-Encoding <string>] [-Force] [-NoClobber] [-Confirm] [-WhatIf] [<CommonParameters>]

DESCRIPTION
    The Export-Clixml cmdlet creates an XML-based representation of an object or objects and stores it in a file. You can then use the Import-Clixml cmdlet to re-create the saved object based on the contents of that file.

    This cmdlet is similar to ConvertTo-Xml, except that Export-Clixml stores the resulting XML in a file. ConvertTo-Xml returns the XML, so you can continue to process it in Windows PowerShell.

PARAMETERS
    -Depth <int>
        Specifies how many levels of contained objects are included in the XML representation. The default value is 2.

        The default value can be overridden for the object type in the Types.ps1xml files. For more information, see about_types.ps1xml.

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

    -Encoding <string>
        Specifies the type of encoding for the target file. Valid values are ASCII, UTF8, UTF7, UTF32, Unicode, BigEndianUnicode, Default, and OEM. UTF8 is the default.

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

    -Force [<SwitchParameter>]
        Causes the cmdlet to clear the read-only attribute of the output file if necessary. The cmdlet will attempt to reset the read-only attribute when the command completes.

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

    -InputObject <psobject>
        Specifies the object to be converted. Enter a Variable that contains the objects, or type a command or expression that gets the objects. You can also pipe objects to Export-Clixml.

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

    -NoClobber [<SwitchParameter>]
        Ensures that the cmdlet does not overwrite the contents of an existing file. By default, if a file exists in the specified path, Export-Clixml overwrites the file without warning.

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

    -Path <string>
        Specifies the path to the file where the XML representation of the object will be stored.

        Required?                    true
        Position?                    1
        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
    System.Management.Automation.PSObject
        You can pipe any object to Export-Clixml.

OUTPUTS
    System.IO.FileInfo
        Export-Clixml creates a file that contains the XML.

NOTES

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

    C:\PS>”This is a test” | Export-Clixml sample.xml

    Description
    ———–
    This command creates an XML file that stores a representation of the string, “This is a test”.

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

    C:\PS>Get-Acl C:\test.txt | Export-Clixml -Path fileacl.xml

    C:\PS> $fileacl = Import-Clixml fileacl.xml

    Description
    ———–
    This example shows how to export an object to an XML file and then create an object by importing the XML from the file.

    The first command uses the Get-Acl cmdlet to get the security descriptor of the Test.txt file. It uses a pipeline operator to pass the security descriptor to Export-Clixml, which stores an XML-based representation of the object in a file named FileACL.xml.

    The second command uses the Import-Clixml cmdlet to create an object from the XML in the FileACL.xml file. Then, it saves the object in the $FileAcl Variable.

RELATED LINKS
    Online version: http://go.microsoft.com/fwlink/?LinkID=113297
    Import-Clixml
    ConvertTo-Xml
    Export-Csv
    ConvertTo-Html