1

鉴于以下...

  1. 实现运行空间池的 Powershell 脚本
  2. 命名脚本块的哈希表
  3. 调用 New-Object 以创建 SQL 相关对象(SMO、SqlClient 等)的脚本块

我的脚本遍历服务器列表并将每个脚本块及其参数从哈希表添加到运行空间池。一些脚本块调用 New-Object 来实例化各种 .net 对象的实例。

代码是这样的(更新以更准确地反映问题)......

# add, configure and execute runspace script block
$_ps                = [Powershell]::Create()
$_ps.RunspacePool   = $this._pool

$_script_block = {
   $_obj = New-Object Microsoft.SqlServer.Management.Smo.Server($InstanceName) 
}

$_wrapper_script_block = { &$_script_block }  # returns cmdlet not found error
$_wrapper_script_block = { Invoke-Command -ScriptBlock $_script_block } # works

$null = $_ps.AddScript($_wrapper_script_block)
$null = $_ps.AddParameters($Parms)

# syntax may be off - just for demonstration
[ArrayList] $jobs += @{process = $_ps; handle = $_ps.BeginInvoke()}

问题...

当池中有多个运行空间时,脚本块返回“新对象无法识别...”错误。如果我使用完全相同的代码,但仅将一个包含 New-Object 调用的脚本块(相同的脚本块因多个运行空间而失败)提交到运行空间池,则它可以正常工作。

微软的文档(https://docs.microsoft.com/en-us/powershell/module/microsoft.powershell.core/about/about_operators?view=powershell-7)说“调用运算符不解析字符串。这意味着使用调用运算符时,不能在字符串中使用命令参数。” 我从 & 更改为 Invoke-Command,现在它似乎工作正常。我不完全确定发生了什么。

4

1 回答 1

1

我想我发现了我的问题。

根据https://docs.microsoft.com/en-us/powershell/module/microsoft.powershell.core/about/about_operators?view=powershell-7,“调用运算符不解析字符串。这意味着你不能使用调用运算符时在字符串中使用命令参数”。他们给出的示例描述了我的脚本中的行为。

简而言之,不能在使用 & 运算符调用的脚本块中使用 cmdlet 参数。例如,像 &"get-command -Verb 'get'" 这样的东西会抛出一个错误,表明 get-command 找不到。

我很抱歉没有将它包含在我的代码示例中。

于 2020-08-17T18:12:45.903 回答