写入输出失败的Foreach循环 - Powershell

时间:2014-03-25 23:15:01

标签: powershell

我是Powershell的新手,我想知道为什么这个功能也没有按我想要的方式工作。以下函数取消注释指定计算机的hosts文件中的行。它很棒!但是我希望能够使用Write-Output将每一行输出到屏幕并获取变量并将其存储在另一个数组中。这个写输出没有做任何事情我无法将它添加到数组中。为什么?上面的写输出工作得很好。

function UnCommentHostsFile($ip){

   Write-Output "This Write-Output Works!"

   $hosts = $hosts | Foreach {

       #This part of the function works great!
       if ($_ -match $regex + $ip){
           $_.replace("#", "")

           #This is where I want to add it to an array and write-output but I can't.
       } 
       else {
           $_
       }

       #This does not output!
       Write-Output $_
   }
}

任何帮助将不胜感激!谢谢! :)

2 个答案:

答案 0 :(得分:1)

要回答您的问题,请执行以下操作:

$hosts = $hosts | Foreach {...}

foreach脚本块中输出到管道的所有内容都将重定向到变量$hosts

Write-Output写入管道,并且您在该脚本块中执行此操作。

如果您想明确写入屏幕,请使用Write-HostWrite-Verbose

答案 1 :(得分:0)

你真的不需要写输出。将它保留为对象,您可以在函数外部格式化该对象。我更新了它,以便对于每一行,如果它与你的正则表达式相匹配,它会替换掉你没有的#,但我删除了Else子句,因为它没有意义。我将$_.replace("#", "")更改为$_ = $_.replace("#", ""),以便它实际更新$ Hosts中的行而不是仅回显它。然后,当完成所有操作后,它将输出整个$ hosts更新的行和所有。

function UnCommentHostsFile($ip){

   $hosts = $hosts | Foreach {

       #This part of the function works great!
       if ($_ -match $regex + $ip){
           $_ = $_.replace("#", "")

           #This is where I want to add it to an array and write-output but I can't.
       } 

       #This does not output!
   }
   $Hosts
}

编辑:当您调用该函数时,它应该吐回$ Hosts中的任何内容,因此它应该输出到屏幕。无需写输出或任何东西。除非您将输出重定向到某个东西,否则它将显示在用户的屏幕上,在这种情况下,只需向管道添加一些内容即可将其打印到屏幕上。

相关问题