【问题标题】:Why does GetCommandLineArgs return a DLL when running pwsh.exe?为什么 GetCommandLineArgs 在运行 pwsh.exe 时会返回 DLL?
【发布时间】:2020-10-14 23:41:23
【问题描述】:

我正在运行以下命令作为测试代码的一部分,试图确定脚本是在交互式会话(即使用 CLI)中运行,还是从无控制台远程会话(SSH、SCP、FTP)中运行。

因此,在 Powershell Core (pwsh.exe) CLI 会话中使用 [Environment]::GetCommandLineArgs() 时,我得到:C:\Program Files\PowerShell\6\pwsh.dll。这很令人惊讶,因为我本来希望得到 pwsh.exe 而不是 DLL。

为什么我得到的是 DLL 而不是 EXE?
怎么回事?

【问题讨论】:

    标签: windows powershell powershell-core


    【解决方案1】:

    这是一个已知问题,在 .NET 5.0 中仍未修复,PowerShell Core 7.1 是基于该问题构建的(在撰写本文时,两者都处于预览状态,但我不希望修复以及时发布这些版本)。

    GitHub issue #11305

    但是,有一个解决方法实际上通常更可取

    [System.Diagnostics.Process]::GetCurrentProcess().MainModule.FileName
    
    # Shorter, but slower equivalent (works only from PowerShell):
    #  (Get-Process -Id $PID).MainModule.FileName
    

    [System.Diagnostics.Process]::GetCurrentProcess().MainModule.FileName 优于 [Environment]::GetCommandLineArgs()[0] 的原因有两个:

    • 前者总是报告一个完整路径。

    • 至少在 .NET Core 3.1 之前,后者可以报告一个临时位置,即用于将自身提取到幕后此类位置的单文件 .NET Core 可执行文件。

    请注意,.NET 5.0+ 将有一个专用的 [Environment]::ProcessPath 属性,它的性能也会更好 - 请参阅 GitHub PR #42768


    如果您想获得[Environment]::GetCommandLineArgs()更正 版本——也就是说,真正的可执行文件存储在索引0 中,而真正的参数 在剩余的元素:

    # Get the original array...
    # Note: Modifying the array directly works, but you can enclose 
    #       the call in @(...) in order to create a *copy* of it.
    $cmdLineArgs = [Environment]::GetCommandLineArgs()
    # ... and fix the entry for the executable (index 0)
    $cmdLineArgs[0] = [Diagnostics.Process]::GetCurrentProcess().MainModule.FileName
    

    通过从cmd.exe 调用 PowerShell CLI 进行演示:

    C:>pwsh -noprofile -c "$a=[Environment]::GetCommandLineArgs(); $a[0]=[Diagnostics.Process]::GetCurrentProcess().MainModule.FileName; $a"
    C:\Program Files\PowerShell\6\pwsh.exe
    -noprofile
    -c
    $a=[Environment]::GetCommandLineArgs(); $a[0]=[Diagnostics.Process]::GetCurrentProcess().MainModule.FileName; $a
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2010-12-11
      • 2022-01-27
      • 2014-03-25
      • 1970-01-01
      • 2013-03-04
      • 1970-01-01
      • 1970-01-01
      • 2021-02-23
      相关资源
      最近更新 更多