New-PSSession 文件操作失败

File operation failed with New-PSSession

我正在加载一个 json 文件,其中包含一个计算机名称列表,每个名称都包含一个我需要操作的文件列表。对于这个例子,我只显示文件大小。

但是我收到文件未找到错误。我认为这是因为 new-pssession 没有激活或打开。我确认该文件确实存在于远程计算机上。在 new-pssession 之后我需要做些什么来“activate/open”会话吗?

$cred = Get-Credential -UserName admin -Message "Enter Password" 
$computers = Get-Content "sample.json" | ConvertFrom-Json    
foreach($computer in $computers){
    $s = new-pssession -ComputerName $computer.computer -Credential $cred
    foreach($file in $computer.files){        
        write-host $file has (get-item $file).length "bytes"
    }
    remove-pssession $s 
}

json 文件

[
    {
        "computer": "machine1",
        "files": [
            "c:\temp\done.png",
            "c:\temp\Permissions.xlsx"
        ]
    },
    {
        "computer": "machine2",
        "files": [
            "c:\software\TortoiseSVN.msi",
            "c:\software\TortoiseSVN.txt"
        ]
    }
]

mklement0 points out in his helpful comment, New-PSSession will only establish the persistent connection with the remote hosts, however if you need to execute code on them you would need to use Invoke-Command.

我已删除此示例的 New-PSSession,因为在这种情况下不需要它,但请注意,在使用 PSSession 时,您将使用-Session 参数而不是 -ComputerName.

$cred = Get-Credential -UserName admin -Message "Enter Password" 
$computers = Get-Content "sample.json" | ConvertFrom-Json
foreach($computer in $computers)
{
    Invoke-Command -ComputerName $computer.computer {
        $computer = $using:computer
        foreach($file in $computer.files)
        {
            Write-Host "$file has $((Get-Item $file).Length) bytes"
        }
    } -Credential $cred 
}

由于 Invoke-Command 允许在远程主机上并行执行 脚本块 ,因此您的代码也可以这样做,但是会稍微复杂一些。 $computers 将被传递到每个远程会话,并且每个主机都需要弄清楚 object[] 中的哪个 object 必须 运行:

$cred = Get-Credential -UserName admin -Message "Enter Password" 
$computers = Get-Content "sample.json" | ConvertFrom-Json
Invoke-Command -ComputerName $computers.computer {
    $computers = $using:computers
    $files = $computers.Where({ $_.computer -eq $env:ComputerName }).files
    foreach($file in $files)
    {
        Write-Host "$file has $((Get-Item $file).Length) bytes"
    }
} -Credential $cred