我正在加载一个 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/