Powershell ScriptBlock不执行

时间:2013-07-11 00:22:03

标签: .net windows powershell powershell-remoting

我正在尝试使用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
}

1 个答案:

答案 0 :(得分:5)

这是因为Invoke-Command执行远程计算机上脚本块中的代码。未在远程计算机上定义ValidatePath函数,并且那里不存在脚本文件 file2.ps1 。没有任何东西可以让远程计算机访问执行Invoke-Command的脚本中的代码或运行脚本的计算机上的文件。您需要将 file2.ps1 复制到远程计算机,或者为您的计算机上的共享提供UNC路径,或者将ValidatePath函数的内容放在脚本块。请务必将 $ file 的所有实例更改为 $ filename ,反之亦然,并调整代码以交互方式运行,例如,您将消除 $ fileExist 返回声明。

要将路径验证代码放入传递给远程计算机的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} -AsJob

N.B。确保“@ 没有缩进。必须位于该行的开头。

顺便说一下,虽然这没有实际意义,但在抛出语句之后立即设置变量有什么意义呢?一旦抛出错误,该函数就会终止。 $fileExist = false在任何情况下都不会执行。您可能想使用写入错误