PowerShell 函数 $ 输入参数

标签 powershell parameters

首先,我只是在学习 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

最佳答案

注意,$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
}

关于PowerShell 函数 $ 输入参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13038129/

相关文章:

loops - 修改未枚举的对象时出错

Powershell - 删除两个变量之间的空格

javascript - 如何在 angularjs 2 中的 @Input 参数上执行函数?

windows - 如何使用 windows azure powershell 获取系统时间

Powershell - 输出到屏幕和日志文件

php - 通过 URL 传递多个变量并在下一页读取所有变量

c# - 将数组作为 `params` 参数传递

ios - 如何接受多种类型作为函数中的参数?

asp.net - 使用 <asp :HyperLink> that is passing parameters 创建弹出窗口

powershell - 如何使用 Powershell 从电子邮件中获取 samaccountname?