powershell - 获取传递给 powershell.exe 的参数
问题描述
有没有办法在 Profile 脚本中确定将哪些参数传递给 powershell 可执行文件?
用例
我想检查是否设置了 WorkingDirectory 参数,然后cd
在我的用户配置文件中用我自己的参数覆盖它。
尝试
我做了一些无助的尝试来从配置文件脚本中获取变量值,但没有运气。他们似乎都没有给我任何关于是否使用参数pwsh.exe
调用的信息:-wd
echo $PSBoundParameters
echo $ArgumentList
echo (Get-Variable MyInvocation -Scope 0).Value;
解决方案
要检查 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
- 注意:在这种情况下,与 with 不同,加载文件时
上述情况可能但不太可能产生误报;使用一个人为的例子:
pwsh -NoExit -c "'Set-Location inside a string literal'"
推荐阅读
- java - Oracle ADF 中的正则表达式
- python - 如何在刽子手游戏中添加空格
- android - 从网格 RecyclerView 到 details 活动的共享过渡效果
- python - Python抓取错误MissingSchema:无效的URL
- python - 随机森林多类 Python 不会提高准确性
- php - 从同一个类创建多个对象
- asp.net - 为什么在我定义了密钥后,我的 ASp.NET React 项目中会出现“唯一的“密钥”道具”错误?
- git - 如果存在其他以后的提交,我将 git commit 推送到远程怎么办?
- php - 如何在我的终端上制作正确的 PHP 版本?
- java - H2:计数查询中的重复列名与嵌套查询