我試圖在使用invoke-command
的遠程計算機上執行代碼。該方法的一部分包含ScriptBlock
參數,並且我知道我沒有正確地做某件事。Powershell ScriptBlock不執行
首先我試圖創建腳本的方法,它是這樣的:
param([string] $filename)
function ValidatePath($file, $fileType = "container")
{
$fileExist = $null
if(-not (test-path $file -PathType $fileType))
{
throw "The path $file does not exist!"
$fileExist = false
}
else
{
echo $filename found!
$fileExist = true
}
return $fileExist
}
$responseObject = Invoke-Command -ComputerName MININT-OU9K10R
-ScriptBlock{validatePath($filename)} -AsJob
$result = Receive-Job -id $responseObject.Id
echo $result
要調用這個,我會做.\myScriptName.ps1 -filename C:\file\to\test
。該腳本將執行,但不會調用該函數。
然後我想,也許我應該把這個函數放到一個新的腳本中。這看起來像:
文件1:
$responseObject = Invoke-Command -ComputerName MININT-OU9K10R -ScriptBlock {
.\file2.ps1 -filename C:\something } -AsJob
$result = Receive-Job -id $responseObject.Id
echo $result
文件2:
Param([string] $filename)
這些都不辦法將執行的功能,我想知道爲什麼;或者,我需要做些什麼才能使其發揮作用。
function ValidatePath($file, $fileType = "container")
{
$fileExist = $null
if(-not (test-path $file -PathType $fileType))
{
throw "The path $file does not exist!"
$fileExist = false
}
else
{
echo $filename found!
$fileExist = true
}
return $fileExist
}
將在腳本塊是什麼樣的,如果我使用的UNC路徑? – BlackHatSamurai
你會使用一個UNC路徑,如果你把你的腳本放在一個文件中,而不是'。\ file2.ps1',哪個是遠程計算機無法訪問的本地文件的相對路徑(它將在它自己的默認工作目錄中查找該文件),您將在計算機上創建共享,將腳本文件放在該文件中,然後使用看起來像'\\ yourcomputer \ share \ file2.ps1'的路徑。將代碼放入ScriptBlock中您試圖調用ValidatePath函數的代碼可能會更好,因爲代碼會傳遞給遠程計算機。這不適合發表評論,我會將其添加到答案中。 –
太棒了!謝謝! – BlackHatSamurai