2015-02-06 49 views
2

由於某些原因,當我嘗試在下面的代碼中的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 
+0

你是什麼意思的「它不工作」?您是否在PowerShell中收到錯誤消息,可以分享該消息的內容嗎? – MatthewG 2015-02-06 20:21:13

+0

它只是回來了一個空文件,沒有錯誤。 – shank 2015-02-06 20:38:36

回答

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