powershell - 文件操作因 New-PSSession 失败

标签 powershell powershell-remoting

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

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

$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在他有用的评论中指出,New-PSSession只会与远程主机建立持久连接,但是如果您需要在它们上执行代码,则需要使用 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 允许在远程主机上并行执行脚本 block ,因此您的代码也可以完成相同的操作,但会稍微复杂一些。 $computers 将被传递到每个远程 session ,每个主机需要确定 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

关于powershell - 文件操作因 New-PSSession 失败,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/70660821/

相关文章:

powershell - Select-Object cmdlet 中要输出的可变数量的字段

json - 从成功的 Invoke-RestMethod 中选择对象数据失败

powershell - PowerShell 中哈希表值的字符串插值

.net - GAC(64位系统)比较?

arrays - 为什么我不能在 Powershell 的 foreach 循环中查找数组索引?

c++ - 通过 Powershell 远程 session 执行时程序输出不同

c# - 如何使用 PowerShell 远程处理从 C# 向 Active Directory 用户添加图像?

windows - WinRM 连接问题?

c# - 为什么 PowerShell 类不加载管理单元

powershell - Powershell的Invoke-Command不会接受-ComputerName参数的变量吗?