【问题标题】:Powershell ScriptBlock Not ExecutingPowershell ScriptBlock 未执行
【发布时间】:2013-07-09 02:50:33
【问题描述】:

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

【问题讨论】:

    标签: .net windows powershell powershell-remoting


    【解决方案1】:

    这是因为 Invoke-Command 在远程计算机上执行脚本块中的代码。远程计算机上没有定义 ValidatePath 函数,脚本文件 file2.ps1 不存在。没有任何东西可以让远程计算机访问执行 Invoke-Command 的脚本中的代码或运行该脚本的计算机上的文件。您需要将 file2.ps1 复制到远程计算机,或者提供一个 UNC 路径,指向您计算机上可用文件的共享,或者将 ValidatePath 函数的内容放在脚本块。确保将 $file 的所有实例更改为 $filename 或反之亦然,并调整代码以交互运行,例如您将消除 $fileExistreturn 语句。

    要将路径验证代码放入传递给远程计算机的脚本块中,您需要执行以下操作:

    $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
    

    注意确保 "@ 没有缩进。它必须位于行首。

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

    【讨论】:

    • 如果我使用 UNC 路径,脚本块会是什么样子?
    • 如果您将脚本放在文件中,您将使用 UNC 路径。而不是.\file2.ps1,它是远程计算机无权访问的本地文件的相对路径(它会在自己的默认工作目录中查找文件),而是在您的计算机上创建一个共享,将脚本文件放在那里,并使用类似于\\yourcomputer\share\file2.ps1 的路径。您最好将代码放在您尝试调用 ValidatePath 函数的 ScriptBlock 中,因为该代码会被传递到远程计算机。这不适合评论,我会将其添加到答案中。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-06-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-09-18
    相关资源
    最近更新 更多