Powershell 尝试编写一个函数,该函数接受带有参数和参数列表的scriptblock,编辑该scriptblock,然后运行invoke命令
我正在编辑一个函数,它将直接在VM上调用命令。我经常遇到的问题是,如果有人将函数声明作为脚本块传递,则调用create时会出现错误,因为Powershell 尝试编写一个函数,该函数接受带有参数和参数列表的scriptblock,编辑该scriptblock,然后运行invoke命令,powershell,invoke-command,scriptblock,Powershell,Invoke Command,Scriptblock,我正在编辑一个函数,它将直接在VM上调用命令。我经常遇到的问题是,如果有人将函数声明作为脚本块传递,则调用create时会出现错误,因为params()不在脚本块的顶部 试图弄清楚如何仍然先设置fulllanguage,然后使用params执行函数 function Invoke-DirectOnVM { [CmdletBinding()] Param ( [Parameter(Mandatory = $true)] [CloudEngine.Configurat
params()
不在脚本块的顶部
试图弄清楚如何仍然先设置fulllanguage
,然后使用params执行函数
function Invoke-DirectOnVM
{
[CmdletBinding()]
Param (
[Parameter(Mandatory = $true)]
[CloudEngine.Configurations.EceInterfaceParameters]
$Parameters,
[Parameter(Mandatory = $true)]
[String[]]$VMNames,
[Parameter(Mandatory = $true)]
[Object]$VMCredential,
[Parameter(Mandatory = $true)]
[ScriptBlock]$ScriptBlock,
[Object[]]$ArgumentList = $null
)
{
Invoke-Command -VMName $localVMs -Credential $using:VMCredential -ScriptBlock ([ScriptBlock]::Create($("Import-Module OpenUpSession; Set-FullLanguage; `r`n" + $using:ScriptBlock)))
}
从脚本块中删除
$using:
,它应该可以正常工作。我冒昧地清理了一下代码。结果如下:
function Invoke-DirectOnVM
{
[CmdletBinding()]
Param (
[Parameter(Mandatory)]
[CloudEngine.Configurations.EceInterfaceParameters]
$Parameters,
[Parameter(Mandatory)]
[String[]]
$VMNames,
[Parameter(Mandatory)]
$VMCredential,
[Parameter(Mandatory)]
[ScriptBlock]
$ScriptBlock,
[Parameter()]
[Object[]]
$ArgumentList = $null
)
$PSBoundParameters.Remove("ScriptBlock")
Invoke-Command @PSBoundParameters -ScriptBlock ([ScriptBlock]::Create( "Import-Module OpenUpSession; Set-FullLanguage; `r`n" + $ScriptBlock ))
}
不要强制脚本块
-ScriptBlock{Import Module OpenUpSession;Set FullLanguage;$using:ScriptBlock.Invoke($using:ArgumentList)}
尝试了此操作。获取错误:+-全语言$使用:scriptBlock.Invoke($using:argumentList)}-Argum…+~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~Using表达式中不允许使用表达式。您没有使用我输入的内容,我可以在您的错误中看到}-Argum
,但这不在您的代码或我的代码中。请让你发布的代码准确地表示你正在使用的代码。足够公平。我删除了代码位,但结果是一样的。$using:ScriptBlock和.invoketh出现错误,可以修复该错误<代码>-ScriptBlock{Param($ScriptBlock,$ArgumentList);导入模块OpenUpSession;设置FullLanguage;$ScriptBlock.Invoke($ArgumentList)}-ArgumentList$ScriptBlock,$ArgumentList