Question

Here's a sample script that attempts to create a remote session on a server, then use WMI to get a list of the server's IIS application pools, and list their names:

    function Test-Remoting
    {
        [CmdletBinding()]
        param
        (    
        )
        begin
        {
            Enter-PSSession TestServer
            $appPools = Get-WmiObject -namespace "root\MicrosoftIISv2" -class "IIsApplicationPool" -Authentication 6
            $appPools | ForEach-Object {
                $appPool = $_;
                $appPool.Name
            }
            Exit-PSSession
        }    
    }

This function is contained in a file called "Test-Remoting.ps1." I open up PowerShell, CD into the directory that contains this file, dot-source the file in, and call the function:

PS C:\Users\moskie> . .\Test-Remoting.ps1
PS C:\Users\moskie> Test-Remoting

But the result of this script is a list of the application pools on my local machine, and not TestServer.

Alternatively, if I run the following lines (identical to the ones in the function) manually at the PowerShell prompt, I do get the list of app pools on the remote server:

PS C:\Users\moskie> Enter-PSSession TestServer
[TestServer]: PS C:\> $appPools = Get-WmiObject -namespace "root\MicrosoftIISv2" -class "IIsApplicationPool" -Authentication 6
[TestServer]: PS C:\> $appPools | ForEach-Object { $appPool = $_; $appPools.Name }
<a list of the names of the application pools on TestServer>
[TestServer]: PS C:\>

I think there's a concept I'm oblivious to, regarding PowerShell remoting and scope. Can anyone help explain this behavior?

Was it helpful?

Solution

I believe Enter/Exit-PSSession is meant more interactive use. From the Enter-PSSession help:

SYNOPSIS
    Starts an interactive session with a remote computer.

In a script, use New-PSSession and Invoke-Command like so:

$session = New-PSSession server01
Invoke-Command -Session $session {hostname}
Remove-PSSession -Session $session

Update: To execute a complete script remotely use the FilePath parameter on Invoke-Command:

icm server01 -FilePath C:\users\keith\myscript.ps1 -arg 1,2

This will copy the script to the remote computer server01 and execute it there with the supplied parameters.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top