Bob
Bob

Reputation: 686

Write-Output Failing Inside Foreach Loop - Powershell

I am new to Powershell and I am wondering why this function doesn't work the way I want it too. The following function uncomments line in the hosts file of the computer specified. It works great! But I want the ability to output each line to the screen using a Write-Output and get the variable and store it in another array. This Write-Output doesn't do anything and I cannot add it to the array. Why? The above Write-Output works just fine.

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 $_
   }
}

Any help would be greatly appreciated! Thanks! :)

Upvotes: 0

Views: 5379

Answers (2)

TheMadTechnician
TheMadTechnician

Reputation: 36287

You don't really need the Write-Output. Leave it as an object, and you can format that object however you want outside the function. I updated it so that for each line if it matches your regex it replaces # with nothing as you already had it, but I removed the Else clause because it was pointless. I changed $_.replace("#", "") to $_ = $_.replace("#", "") so that it actually updates the line in $Hosts instead of just echoing it. Then when all is said and done it outputs the entire $hosts updated lines and all.

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
}

Edit: When you call the function it should spit back whatever is in $Hosts, so it should output to the screen. No need to write-output or anything. It will show up on screen for the user, unless you are redirecting the output to something, in which case just add a bit to the pipe that prints it to the screen.

Upvotes: 0

mjolinor
mjolinor

Reputation: 68243

To answer your question, when you do this:

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

everything that is output to the pipeline within that foreach script block is going to get re-directed to the variable $hosts.

Write-Output writes to the pipeline, and you're doing it within that script block.

If you want to explicitly write to the screen, use Write-Host, or Write-Verbose.

Upvotes: 1

Related Questions