Bla*_*rai 1 .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
Run Code Online (Sandbox Code Playgroud)
打电话给我,我会的.\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
Run Code Online (Sandbox Code Playgroud)
文件2:
Param([string] $filename)
Run Code Online (Sandbox Code Playgroud)
这些方法都不会执行这个功能,我想知道为什么; 或者,我需要做些什么才能使它发挥作用.
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
}
Run Code Online (Sandbox Code Playgroud)
那是因为Invoke-Command执行远程计算机上脚本块中的代码.未在远程计算机上定义ValidatePath函数,并且那里不存在脚本文件file2.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} -AsJob
Run Code Online (Sandbox Code Playgroud)
注意确保"@不缩进.它必须位于行的开头.
顺便说一句,虽然这没有实际意义,但是在throw语句之后立即设置变量有什么意义呢?一旦抛出错误,该函数就会终止.$fileExist = false在任何情况下都不会执行.您可能想要使用Write-Error.
| 归档时间: |
|
| 查看次数: |
1269 次 |
| 最近记录: |