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

Mos*_*kie 3 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
        }    
    }
Run Code Online (Sandbox Code Playgroud)

此函数包含在名为"Test-Remoting.ps1"的文件中.我将PowerShell,CD打开到包含该文件的目录中,将该文件点源,并调用该函数:

PS C:\Users\moskie> . .\Test-Remoting.ps1
PS C:\Users\moskie> Test-Remoting
Run Code Online (Sandbox Code Playgroud)

但是此脚本的结果是我本地计算机上的应用程序池列表,而不是 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:\>
Run Code Online (Sandbox Code Playgroud)

关于PowerShell远程处理和范围,我认为有一个我不知道的概念.谁能帮助解释这种行为?

Kei*_*ill 5

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

SYNOPSIS
    Starts an interactive session with a remote computer.
Run Code Online (Sandbox Code Playgroud)

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

$session = New-PSSession server01
Invoke-Command -Session $session {hostname}
Remove-PSSession -Session $session
Run Code Online (Sandbox Code Playgroud)

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

icm server01 -FilePath C:\users\keith\myscript.ps1 -arg 1,2
Run Code Online (Sandbox Code Playgroud)

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