PowerShell远程会话和范围问题:命令似乎在本地运行

时间:2010-02-03 23:35:50

标签: powershell powershell-remoting

这是一个示例脚本,尝试在服务器上创建远程会话,然后使用WMI获取服务器的IIS应用程序池列表,并列出其名称:

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

此功能包含在名为“Test-Remoting.ps1”的文件中。我将PowerShell,CD打开到包含该文件的目录中,将该文件点源,然后调用该函数:

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

但是此脚本的结果是我的本地计算机上的应用程序池列表,而不是 TestServer。

或者,如果我在PowerShell提示符下手动运行以下行(与函数中的行相同),我执行获取远程服务器上的应用程序池列表:

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:\>

我认为有一个关于PowerShell远程处理和范围的概念我没有注意到。任何人都可以帮助解释这种行为吗?

1 个答案:

答案 0 :(得分:5)

我相信Enter / Exit-PSSession意味着更具互动性。从Enter-PSSession帮助:

SYNOPSIS
    Starts an interactive session with a remote computer.

在脚本中,使用New-PSSession和Invoke-Command,如下所示:

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

更新:要远程执行完整脚本,请使用Invoke-Command上的FilePath参数:

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

这会将脚本复制到远程计算机server01并使用提供的参数在那里执行。