问题描述
我正在尝试使用 Invoke-Command 从远程服务器的文件夹中获取一些文件信息
$files = Invoke-Command -Credential $cred -ComputerName $serversi -ScriptBlock {$remoteFiles= Get-ChildItem -Path $using:path
Write-Host $remoteFiles.getType();
return $remoteFiles;
} ;
Write-Host $files.getType();
远程对象是 System.IO.FileInfo 但它返回为 System.Management.Automation.PSObject
我可以从 PSObject 获取 FileInfo 或 FileInfo 数组吗? 我尝试过的任何方法都不起作用。
解决方法
我无法复制您的错误,但这有效并返回文件对象:
$Path = "C:\"
$files = Invoke-Command -Credential $cred -ArgumentList $Path -ComputerName $serversi -ScriptBlock {
Get-ChildItem -Path $Args[0]
}
,
我认为这会对您有所帮助。一些提示:
- 始终使用具有含义的完整变量名称。如果名称在 PowerShell 中已知,请使用这些名称 (
$serversi
变为$computerName
) - 使用
Write-Verbose
而不是Write-Host
。它会显示您想看到的进度。Write-Host
用于不同的目的,在终端中显示消息,并且会污染管道或您期望的信息。 - 试着把你的论点吐出来,这会让你的眼睛更轻松
@{paramName = paramValue}
- 知道一切都是默认返回的。因此无需使用
Return
关键字。例如,仅当您想提前离开函数时才有用。
$invokeParams = @{
Credential = $credentials
ComputerName = $computerName
}
$VerbosePreference = 'SilentlyContinue' # hide Write-Verbose messages
$VerbosePreference = 'Continue' # show Write-Verbose messages
$files = Invoke-Command @invokeParams -ScriptBlock {
# if you only want files use the '-File' switch
Get-ChildItem -Path $using:path -File
<# # another way
$result = Get-ChildItem -Path $using:path
$result # no need for the 'Return' as everything is returned by default
#>
# NEVER use Write-Host as it is returned and will confuse you
}
foreach ($file in $files) {
# use Write-Verbose to show you details that will not pollute the pipeline
Write-Verbose "File '$($file.FullName)' is of type $($files.getType())"
}