[英]How can I store the output of a command as a variable in PowerShell?
Say I execute the command: git pshu
which will give me:假设我执行命令:
git pshu
这会给我:
git: 'pshu' is not a git command. See 'git --help'.
Did you mean this?
push
If this was the last command I executed, I want retrieve the command and store its outputs in a variable for further use.如果这是我执行的最后一个命令,我想检索该命令并将其输出存储在一个变量中以供进一步使用。
So far I have tried things like:到目前为止,我已经尝试过类似的事情:
$var = echo (iex (h)[-1].CommandLine)
$var = iex (h)[-1].CommandLine | Out-String
etc.等等。
How can I save such output to a variable?如何将此类输出保存到变量中?
Lets say you are running multiple commands, and you want to store store a run command based on its input.假设您正在运行多个命令,并且您希望根据其输入存储一个运行命令。
Lets say you want to store non existing git commands, as git pshu
.假设您想将不存在的 git 命令存储为
git pshu
。 My proposal will be to store the command and search for the desired pattern on the output as "Did you mean..."
.我的建议是存储命令并在输出中搜索所需的模式为
"Did you mean..."
。 In this case, you can follow as:在这种情况下,您可以按照以下方式操作:
$output = git pshu *>&1
if ( "$output".indexOf("Did you mean") -ge 0 ) {
write-host "Command '$($(get-history)[$(get-history).count-1].CommandLine)' didnt exist"
where $(get-history)[$(get-history).count-1].CommandLine
will contain the latest run command, in this example, `git pshu'其中
$(get-history)[$(get-history).count-1].CommandLine
将包含最新的运行命令,在本例中为 `git pshu'
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.