PowerShell:Get ChildItem忽略了字符串变量

PowerShell:Get ChildItem忽略了字符串变量,powershell,Powershell,下面的PowerShell脚本应该测量远程计算机上的文件夹大小,但显然Get ChildItem忽略了我的$Desktop变量值,我得到了0.00 MB。但是,当我用显式字符串替换$Desktop时,例如“C:\Users\user1\Desktop”,它可以正常工作,我得到例如10.MB。我做错什么了吗 $file1="C:\computers_users.csv" import-csv $file1 | ForEach-Object{ $Desktop = "C:\Users\$($_.

下面的PowerShell脚本应该测量远程计算机上的文件夹大小,但显然Get ChildItem忽略了我的$Desktop变量值,我得到了0.00 MB。但是,当我用显式字符串替换$Desktop时,例如“C:\Users\user1\Desktop”,它可以正常工作,我得到例如10.MB。我做错什么了吗

$file1="C:\computers_users.csv"
import-csv $file1 | ForEach-Object{
  $Desktop = "C:\Users\$($_.user)\Desktop"      
  Invoke-Command -ComputerName $_.computer -ScriptBlock {
    $FldSize =(Get-ChildItem $Desktop -recurse | Measure-Object -property length -sum)
    "{0:N2}" -f ($FldSize.sum / 1MB) + " MB"}
}
试试这个:

Invoke-Command -ComputerName $_.computer -ScriptBlock {
    $FldSize =(Get-ChildItem $args[0] -recurse | Measure-Object -property length -sum)
    "{0:N2}" -f ($FldSize.sum / 1MB) + " MB"} -argumentlist $desktop
您需要使用
-argumentlist
传递参数,因为invoke命令会创建一个新的powershell会话,而不知道调用会话变量。

请尝试以下操作:

Invoke-Command -ComputerName $_.computer -ScriptBlock {
    $FldSize =(Get-ChildItem $args[0] -recurse | Measure-Object -property length -sum)
    "{0:N2}" -f ($FldSize.sum / 1MB) + " MB"} -argumentlist $desktop

您需要使用
-argumentlist
传递参数,因为invoke命令会创建一个新的powershell会话,而不知道调用会话变量。

另一方面,在powershell 3.0中,您可以使用$using来传递本地变量和远程计算机:

Invoke-Command ... -ScriptBlock { $FldSize =(Get-ChildItem $using:Desktop ...

另一方面,在PowerShell 3.0中,您可以使用$using将本地变量传递给远程计算机:

Invoke-Command ... -ScriptBlock { $FldSize =(Get-ChildItem $using:Desktop ...

工作!谢谢你向我解释。现在,它还将解决另一个难题。非常感谢。工作顺利!谢谢你向我解释。现在,它还将解决另一个难题。非常感谢。