我正在尝试使用invoke-command在远程机器上执行代码。该方法的一部分包含一个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
}发布于 2013-07-11 09:20:52
这是因为Invoke-Command会在远程计算机上执行脚本块中的代码。远程计算机上未定义file2.ps1函数,脚本文件 ValidatePath 2.ps1不存在。远程计算机无法访问执行Invoke-Command的脚本中的代码,也不能访问运行该脚本的计算机上的文件。您需要将file2.ps1复制到远程计算机,或为其提供指向计算机上可用文件的共享的UNC路径,或者将ValidatePath函数的内容放在脚本块中。请确保将$file的所有实例更改为$filename,反之亦然,并调整代码以交互方式运行,例如,您可以删除$fileExist和return语句。
要将路径验证代码放入传递到远程计算机的scriptblock中,您可以这样做:
$scriptblock = @"
if (-not (Test-Path $filename -PathType 'Container') ) {
throw "The path $file does not exist!"
} else {
echo $filename found!
}
"@
$responseObject = Invoke-Command -ComputerName MININT-OU9K10R -ScriptBlock{$scriptblock} -AsJobN.B.确保"@“没有缩进。它必须在行首。
顺便说一句,虽然这是没有意义的,但是在抛出语句之后立即设置一个变量有什么意义?一旦抛出错误,函数就会终止。$fileExist = false在任何情况下都不会执行。您可能想要使用Write-Error.
https://stackoverflow.com/questions/17583103
复制相似问题