使用 PowerShell 模块“RunAsUser”时将参数传递给脚本块

问题描述 投票:0回答:1

我正在编写一个要在 Datto RMM 中的组件中使用的 PowerShell 脚本。

要以登录用户身份运行,我使用 PowerShell 模块 RunAsUser。

我希望能够将变量从 Datto 作业传递到脚本块内的命令。这是我的代码

$scriptblock = {
    param($Message, $WaitSeconds, $Title, $BoxType)

    $wshell = New-Object -ComObject Wscript.Shell
    $Output =  $wshell.Popup($Message, $WaitSeconds, $Title, $BoxType)
 
    # Due to scope, none of the variables in the scriptblock
    # can be seen outside the block so we need to
    # provide an ouput to the calling object if it wants it.
    Write-Host $Output
}

# see https://github.com/KelvinTegelaar/RunAsUser for specifics
# of invoke-ascurrentuser
$str = invoke-ascurrentuser -scriptblock $scriptblock -ArgumentList $env:Message, $env:WaitSeconds, $env:Title, $env:BoxType -CaptureOutput

我没有收到错误,但也没有收到消息框。

我尝试过的一些方法没有给我带来错误,但出现一个最小的消息框,就好像参数都是空白的一样。

windows powershell
1个回答
0
投票

Invoke-AsCurrentUser
RunAsUser
模块的一部分,从 v2.4.0 开始不支持参数传递,因此没有
-ArgumentList
参数。

相反,您必须将您希望脚本块进行操作的调用者范围中的任何值“烘焙”到脚本块中:

# Create the script block from an expandable string that references
# variables from the caller's scope and expands them up front.
# Note: This assumes that the environment variables referenced below
#       (e.g. $env:Message) exist and have appropriate values.
$scriptblock = [scriptblock]::Create(@"
    # Note: NO param(...) declaration.

    # Note the need to `-escape those $ chars. that shouldn't be
    # expanded up front.
    `$wshell = New-Object -ComObject Wscript.Shell
    
    # Reference the environment variables here, using appropriate
    # embedded quoting:
    `$wshell.Popup("$env:Message", $env:WaitSeconds, "$env:Title", $env:BoxType)

    # Note: No need for an explicit output command:
    #       The .Popup() call's return value is *implicitly* output.
}
"@)

$str = Invoke-AsCurrentUser -scriptblock $scriptblock -CaptureOutput
© www.soinside.com 2019 - 2024. All rights reserved.