简体   繁体   English

如何将命令的输出存储为 PowerShell 中的变量?

[英]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.

相关问题 将 powershell 命令的输出存储在变量中 - store the output of powershell command in a variable 如何将 Powershell 输出存储到变量? - How to store Powershell output to a variable? PowerShell:我如何将 output 哈希表作为 json 并使用 foreach 循环将其存储在变量中? - PowerShell: How can I output a hashtable as json and store it in a variable using a foreach loop? 如何在Powershell脚本中输出被调用命令的所有输出 - How can I output all the output of a called command in Powershell script 如何将命令 output 保存到变量中,以及如何将该变量用作 Powershell 中的命令参数? - How do I save a command output to a variable, and how do I use that variable as command parameter in Powershell? 将带有多行输出的命令存储到 Powershell 中的变量或文件 - Store command with multi line output to variable or file in Powershell 如何过滤命令的输出? (电源外壳) - How can I filter output of my command? (Powershell) 如何让 PowerShell 连接一些命令输出和一个字符串? - How can I make PowerShell concatenate some command output and a string? 如何在 powershell 中仅获取 output 命令的一行? - How can I get only one line for output of command in powershell? 如何在下一个命令中使用 PowerShell output? - How can I use a PowerShell output in the next command?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM