Author Posts

April 8, 2016 at 3:21 pm

Hi,

Following the thread "another-empty-pipe-error-when-export-csv-used/#post-10028", I tried to use Dave Wyatt's second option of "force a foreach loop to pipe its results somewhere (placing the loop into a subexpression, and piping the results of the subexpression to the next command)" and derived the following to see which of our organizations servers are no longer in DNS. Unfortunately all I get is the screen display (helpful) and an empty file (not so much.):

        $Names = import-csv -Path "C:\temp\AD_servers.csv" | % {$_.Name}
$(
Foreach ($name in $Names)
{
    $Addresses = $null
    try {
        $Addresses = [System.Net.Dns]::GetHostAddresses("$Name").IPAddressToString
    }
    catch { 
        $Addresses = "Server IP cannot resolve."
    }
    foreach($Address in $addresses) {
        write-host "$Name,"$Address
    }
}
) |export-csv "C:\temp\result.csv"

Suggestions?

Thanks,
-Bob King

April 8, 2016 at 4:11 pm

Try this:

$Names = Import-Csv -Path 'C:\temp\servers.csv' | ForEach-Object -Process {$_.Name}

@(
    Foreach ($name in $Names) {
        $Addresses = $null
       
        Try {$Addresses = [System.Net.Dns]::GetHostAddresses("$name").IPAddressToString}
        
        Catch {$Addresses = 'Server IP cannot resolve.'}
        
        Foreach($Address in $Addresses) {
            [pscustomobject] @{
                Name      = $name
                IPAddress = $Address
            }
        }
    }
) | Export-Csv -Path 'C:\temp\result.csv' -NoTypeInformation

This works because I'm passing an object to Export-Csv. You used Write-Host; this only puts text in the console. Nothing else. So there is no input for Export-Csv.

April 8, 2016 at 4:47 pm

Richard's correct. Read the OUTPUTS section of the Write-Host help file. It tells you that it empties the pipeline, that their is nothing left after that.

April 8, 2016 at 11:37 pm

And I forgot to mention, every time you use Write-Host, and I'm quoting Don Jones, you kill a puppy. And we don't want to kill puppy's, don't we? 🙂