获取传递给 powershell.exe 的参数

fra*_*lic 6 powershell

有没有办法确定在 Profile 脚本中传递给 powershell 可执行文件的参数是什么?

用例

我想检查是否设置了工作目录参数,然后cd在我的用户配置文件中用我自己的参数覆盖它。

尝试

我做了一些无助的尝试来从配置文件脚本中获取变量值,但没有成功。它们似乎都没有给我任何关于是否pwsh.exe使用-wd参数调用的信息:

echo $PSBoundParameters
echo $ArgumentList
echo (Get-Variable MyInvocation -Scope 0).Value;
Run Code Online (Sandbox Code Playgroud)

mkl*_*nt0 5

检查PowerShell自己的调用命令行,您可以使用:

  • [Environment]::CommandLine(单弦)

  • [Environment]::GetCommandLineArgs()(参数数组,包括作为第一个参数的可执行文件)。

这些技术也适用于类 Unix 平台。

警告:从 PowerShell Core 7 (.NET Core 3.1) 开始,它是可执行文件pwsh.dll,而不是pwsh[.exe]报告为可执行文件。


要检查$PROFILE文件是否在启动时指定了工作目录,可能如下所示,但请注意该解决方案并非万无一失:

$workingDirSpecified =
  ($PSVersionTable.PSEdition -ne 'Desktop' -and
   [Environment]::GetCommandLineArgs() -match '^-(WorkingDirectory|wd|wo|wor|work|worki|workin|working|workingd|workingdi|workingdir|workingdire|workingdirec|workingdirect|workingdirecto|workingdirector)') -or
  [Environment]::CommandLine -match
    '\b(Set-Location|sl|cd|chdir|Push-Location|pushd|pul)\b'
Run Code Online (Sandbox Code Playgroud)
  • 在 PowerShell Core 中,工作目录可能已使用-WorkingDirectory/-wd参数指定(Windows PowerShell 不支持);例如,
    pwsh -WorkingDirectory /

    • 注意:鉴于仅指定参数名称的前缀就足够了,只要该前缀唯一标识该参数,就还需要测试wo, wor, work, ...
  • 在 PowerShell Core 和 Windows PowerShell 中,工作目录可能已通过 cmdlet 调用(可能通过内置别名)作为-c/-Command参数的一部分进行设置(例如,
    pwsh -NoExit -c "Set-Location /"

    • 注意:在这种情况下,与 with 不同,加载文件时-WorkingDirectory工作目录尚未更改。$PROFILE

上述情况有可能但不太可能产生误报;使用一个人为的例子:
pwsh -NoExit -c "'Set-Location inside a string literal'"