PowerShell - 将变量传递给Invioke-Command
问题描述:
由于某些原因,当我尝试在下面的代码中的Get-ChildItem后面使用$ scanpath变量时,它不起作用。但如果我把实际的路径放在$ scanpath的地方,它就可以工作。我究竟做错了什么? $ computer和$ savepath变量都能正常工作。PowerShell - 将变量传递给Invioke-Command
$computer = 'Server'
$scanpath = 'P$\Directory\Directory\Z'
$savepath = 'C:\Z-Media.csv'
Invoke-Command -ComputerName $computer -scriptblock {Get-ChildItem $scanpath -recurse -include *.mp3,*.wma,*.wmv,*.mov,*.mpg,*.ogg,*.jpg -force | select FullName, Length | Sort-Object { [long]$_.Length } -descending} | Export-Csv $savepath -NoTypeInformation
答
PowerShell的3+ - 该
$scanpath
与脚本块不在同一范围内。你有2种方法来解决这个问题:
PowerShell的3+ - 该Using
范围修改
Invoke-Command -ComputerName $computer -scriptblock {Get-ChildItem $Using:scanpath -recurse}
更多信息请参见about_Scopes。
使用是一种特殊的作用域修饰符,它在 远程命令中标识一个局部变量。默认情况下,远程命令中的变量假定在远程会话中定义为 。
任何版本 - 参数
Invoke-Command -ComputerName $computer -scriptblock {param($thisPath) Get-ChildItem $thisPath -recurse} -ArgumentList $scanpath
你可以给一个脚本块参数,就像一个功能。 Invoke-Command
需要一个-ArgumentList
参数,该参数将值传递给scriptblock的参数。
+0
$使用:scanpath是我需要的。谢谢! – shank 2015-02-06 20:39:38
你是什么意思的“它不工作”?您是否在PowerShell中收到错误消息,可以分享该消息的内容吗? – MatthewG 2015-02-06 20:21:13
它只是回来了一个空文件,没有错误。 – shank 2015-02-06 20:38:36