PowerShell函数$输入参数

时间:2012-10-23 19:50:38

标签: powershell parameters

首先,我只是学习PowerShell,但我编写了许多脚本语言。

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

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

我只想循环查看返回的行,看看有多少行已“运行”,如果没有则会打印出错误。

代码(部分:功能和相关代码)

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

1 个答案:

答案 0 :(得分:6)

小心,$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
}