首页 > 解决方案 > 获取传递给 powershell.exe 的参数

问题描述

有没有办法在 Profile 脚本中确定将哪些参数传递给 powershell 可执行文件?

用例

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

尝试

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

echo $PSBoundParameters
echo $ArgumentList
echo (Get-Variable MyInvocation -Scope 0).Value;

标签: powershell

解决方案


检查 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'
  • 在 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'"


推荐阅读