Powershell外部程序作为变量

时间:2012-10-07 17:47:39

标签: variables powershell

我刚开始使用PowerShell。并创建了一个脚本来监控我的服务器。 但是,我还需要从我的服务器监视我的硬盘和raid配置。这只能通过HP的软件完成。

所以我想要的是:
我有一个HP命令行实用程序,我可以使用它来监视阵列和磁盘。 当我启动这个实用程序时,我得到了这个:

PS C:\Program Files (x86)\Compaq\Hpacucli\Bin> .\hpacucli.exe controller slot=3 physicaldrive "1I:0:1 (port 1I:box 0:bay  1, 750 GB)" show status | out-host 
physicaldrive 1I:0:1 (port 1I:box 0:bay 1, 750 GB): OK

我只想将此输出作为变量在我的脚本中进一步使用它。

如何做到这一点。

我试过了:

$disk1 = "c:\program files (x86)\Compaq\hpacucli\bin\hpacucli.exe controller slot=3 physicaldrive "1I:0:1 (port 1I:box 0:bay  1, 750 GB)" show status | out-host"

但这不起作用

所以我只想将physicaldrive 1I:0:1 (port 1I:box 0:bay 1, 750 GB): OK作为变量。

我希望有人可以帮助我。所以我可以学习进一步使用PowerShell。

全部谢谢。丹尼斯

1 个答案:

答案 0 :(得分:3)

删除out-host cmdlet,因为它消耗了exe的输出,例如:

$disk1 = .\hpacucli.exe controller slot=3 physicaldrive "1I:0:1 (port 1I:box 0:bay 1, 750 GB)" show status

使用PowerShell时,请记住,无论何时调用管道并且有输出,它都会转到输出流,在那里它可以被变量捕获(如上所述),或者如果输出不是,则显示在屏幕上抓获。当您输送到Out-Host时,它会绕过正常输出并“直接”向屏幕显示输入。这就是为什么你无法将数据捕获到变量。

在函数中,这与传统语言略有不同,因为生成未捕获到变量(或重定向到$ null)的输出的每个语句都将生成该函数的输出。对于许多首次使用PowerShell的用户而言,当他们的功能返回超出预期时,这可能会令人惊讶。有关详细信息,请查看accepted answer to this SO question