如何在 powershell 中使用变量调用命令?
Posted
技术标签:
【中文标题】如何在 powershell 中使用变量调用命令?【英文标题】:How do I invoke a command using a variable in powershell? 【发布时间】:2022-01-22 22:54:17 【问题描述】:我想在 powershell 中调用 shutdown.exe 可执行文件,它位于 C:\WINDOWS\System32\shutdown.exe
。
由于我们已经在变量$env:windir
中获得了C:\WINDOWS
,我只想使用它并将路径的其余部分连接到命令中。我正在尝试这个:
PS C:\Users\shina> .\$env:windir\System32\shutdown.exe -s
但我收到以下错误:
.\$env:windir\System32\shutdown.exe: The term '.\$env:windir\System32\shutdown.exe' is not recognized as a name of a cmdlet, function, script file, or executable program.
Check the spelling of the name, or if a path was included, verify that the path is correct and try again.
我怎样才能做到这一点?
【问题讨论】:
将&
放在开头而不是 DOT 后跟完整路径
这应该可以。只删除环境变量前的 `.\`;它已经包含该文件夹的路径。
【参考方案1】:
你可以使用:
& $env:windir\System32\shutdown.exe -s
或者
. $env:windir\System32\shutdown.exe -s
(注意空格)。
&
是呼叫操作员。你可以阅读更多关于它here:
运行命令、脚本或脚本块。调用运算符,也称为“调用运算符”,可让您运行存储在变量中并由字符串或脚本块表示的命令。
.
是点源运算符。你可以阅读更多关于它here:
在当前范围内运行脚本,以便将脚本创建的任何函数、别名和变量添加到当前范围,覆盖现有的。
点源运算符后跟一个空格。使用空格将点与代表当前目录的点 (.) 符号区分开来。
【讨论】:
感谢您的回答!您能否详细说明命令开头的“&”是什么意思?抱歉这个问题,我正在学习 @DanielOliveira 答案已更新。以上是关于如何在 powershell 中使用变量调用命令?的主要内容,如果未能解决你的问题,请参考以下文章
在 PowerShell 中,如何在文件中定义函数并从 PowerShell 命令行调用它?