在脚本中的 RunAs 中执行 PowerShell 脚本

Execute a PowerShell script within RunAs in a script

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

注意:文件路径中的空格会用双“-”转义,只是此处未显示,因此在实际命令中转义了“”。也用过```".

示例:

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

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

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

如有任何帮助,我们将不胜感激。

通常没有理由使用 Start-Process to run a console application such as runas.exe - unless you explicitly want the application to run in a new window, asynchronously (by default) - see 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 CLI 的 -Command (-c) 参数] PowerShell(例如通过 runas.exe)导致它被解释为 逐字的 PowerShell 字符串,按原样打印其内容(白色 space 规范化除外) .

您可以通过 运行 来自 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 之前的 多个 space 是如何标准化为 单个 的。

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

因此,当 -Command (-c) 参数看到它的参数时 -- 命令行解析之后 - 和 then 将生成的 space 连接,可能是双引号剥离的参数 解释为 PowerShell 源代码 '...' 的范围是像往常一样解释为逐字的 PowerShell 字符串(请参阅概念性 about_Quoting_Rules 帮助主题,其中讨论了 PowerShell 字符串文字 的类型)。

具体来说:

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

    • 'Get-Date;whateverItypehereisusedas-is-almost' - 请注意有关最初分隔这些参数的白色space 数量的任何信息如何在该过程中丢失
  • 然后将这些参数与 单个 space 连接起来,形成字符串,PowerShell 然后将其解释为 作为 PowerShell 源代码,产生:

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