3

首先,我只是在学习 PowerShell,但我已经使用多种脚本语言进行了编程。

我正在编写一个脚本来从远程服务器上的命令中检索输出,然后检查该输出中是否存在“运行”一词。现在它检索命令的输出,我把它放在我的变量中,$data. 问题是我将它放在我的“clean_data”函数中,并且它与我传递给函数的变量中的内容不同。

我想知道的是,$data变量的输出在打印到屏幕时究竟如何具有一个内容,但是当传递给一个函数并立即打印时有一个新的内容?我错过了什么?

我只想遍历返回的行以查看其中有多少“正在运行”,如果没有则打印一个很好的错误。

CODE(部分:功能及相关代码)

function clean_data($input) {
  Write-Output "Received data"$input
  Write-Output "Cleaning data"
  $output=@()
  foreach ($line in $input) {
     Write-Output "Looking at: "$line.ToString()
     if ($line.ToString().Contains("running")) {
         $output+=$line
     }
   }
   Write-Output $output
   return ,$output
}

$data = Get-Job -id $jobid.id | Receive-Job
Write-output "Data Type: "$data.GetType().Fullname
Write-Output "Output of $cmd"
Write-Output "============================================================"
Write-Output $data
Write-Output "============================================================"
clean_data $data
Write-Output $newdata
Remove-Job -Id $jobid.Id

输出

Data Type:
System.Object[]
Output of C:\opcragt.bat servername
============================================================

C:\Windows\system32>"D:\Program Files\HP\HP BTO Software\bin\win64\opcragt.cmd" servername


Node: servername
HPOM Managed Node status:
-------------------------
OV Performance Core coda (3500) is running
OV Communication Broker ovbbccb (10988) is running
OV Control ovcd (10400) is running
OV Config and Deploy ovconfd (5092) is running

Subagent EA:
Action Agent opcacta (9716) is running
Monitor Agent opcmona (9872) is running
Message Agent opcmsga (14712) is running
Message Interceptor opcmsgi (13512) is running
WMI Interceptor opcwbemi (6608) is running

**************************************************
Remote administration completed successfully on all nodes.

============================================================
Received data
Current
-------
Cleaning data
4

1 回答 1

7

小心,$input是 PowerShell 使用的自动变量,允许对传递给函数的数据进行迭代。试试这个:

function clean_data($data) {
  Write-Verbose "Received data: $data"
  Write-Verbose "Cleaning data"
  $output = @()
  foreach ($line in $data) {
     Write-Verbose "Processing line: $line"
     if ($line -match 'running') {
          $output += $line
     }
   }
   $output
}
于 2012-10-23T21:12:52.203 回答