【问题标题】:Execute a PowerShell script within RunAs in a script在脚本中的 RunAs 中执行 PowerShell 脚本
【发布时间】:2021-08-07 01:22:38
【问题描述】:

我需要根据检测到的环境以另一个用户身份运行 PowerShell 脚本(用户实际上将执行身份验证)。该脚本利用智能卡进行登录。我遇到的问题是,当 PowerShell.exe 实例从 runas 启动时,它只是打印我的命令,实际上并没有运行它。

注意:文件路径中的空格用双-`转义,这里没有显示,因此在实际命令中转义了“”。也用过```"。

例子:

Start-Process runas.exe "/netonly /smartcard /user:domain\$env:USERNAME ""powershell.exe -noexit -Command `'&$filePath -arg1 -arg2`' "" "

或

Start-Process runas.exe "/netonly /smartcard /user:domain\$env:USERNAME ""powershell.exe -noexit -File `'$filePath -arg1 -arg2`' "" "

文件路径指向同一个 .ps1 文件。目录类似于:C:\Users\Username\My Documents\script.ps1

当它运行时,我只是得到一个实际上并没有运行的脚本窗口,它只是打印文件名。我也尝试过使用-File,但这只是崩溃(不管-noexit)。 runas 位工作正常,我收到智能卡提示等,这只是我正在努力解决的实际 PowerShell 启动。

直接从 PowerShell Cli 调用它们就可以正常工作,但是在 .ps1 中它就不起作用了。

任何帮助将不胜感激。

【问题讨论】:

    标签: powershell runas powershell-7.0


    【解决方案1】:

    通常没有理由使用Start-Process 来运行控制台应用程序,例如runas.exe - 除非您明确希望应用程序在新窗口 中异步运行(默认情况下) - 请参阅this answer 了解更多信息。

    消除Start-Process 简化了引用:

    runas.exe /netonly /smartcard /user:domain\$env:USERNAME "powershell.exe -noexit -File \`"$filePath\`" -arg1 -arg2"
    

    注意 - 不幸的是 - 需要手动 \ - 转义嵌入的 " 字符。 (`"),至少需要 v7.1 - 请参阅this answer。


    至于你尝试了什么:

    在 Windows 上,将 '...' 封闭的字符串从 外部 PowerShell(例如通过 runas.exe)传递给 PowerShell CLI 的 -Command (-c) 参数会导致它被解释作为 逐字 PowerShell 字符串,按原样打印其内容(空白规范化除外)。

    您可以通过从cmd.exe 运行以下命令来验证这一点,例如:

    C:\>powershell -c 'Get-Date; whatever I type here is used as-is -   almost'
    
    Get-Date; whatever I type here is used as-is - almost
    

    注意almost 之前的多个 空格是如何被标准化为单个 的。

    原因是在 Windows 上只有 double-quoting ("...") 在命令行上具有 句法 功能 - ' 字符被逐字解释 ,因此通过。

    因此,当-Command (-c) 参数看到它的参数时——在命令行解析之后——并且然后解释结果空间-加入,可能是双引号去掉的参数作为 PowerShell 源代码,'...' 的跨度像往常一样被解释为逐字 PowerShell 字符串(请参阅概念性的 about_Quoting_Rules 帮助主题,其中讨论了PowerShell 字符串文字的类型)。

    具体来说:

    • 'Get-Date; whatever I type here is used as-is - almost' 被 PowerShell CLI 解析为以下参数 (!):

      • 'Get-Date;, whatever, I, type, here, is, used, as-is, -, almost' - 注意关于空格数量的任何信息原来分离这些论点的过程中丢失了。
    • 然后将这些参数与一个 单个空格 连接起来形成字符串,然后 PowerShell 将 解释为 PowerShell 源代码,从而产生:

      • 'Get-Date; whatever I type here is used as-is - almost'
    • 这相当于一个逐字(单引号)PowerShell 字符串文字,其内容随后按原样输出。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-01-06
      • 1970-01-01
      • 2011-05-04
      • 2021-11-06
      • 2012-09-18
      相关资源
      最近更新 更多