IMPhill
IMPhill

Reputation: 35

Powershell Out-File Not working as expected

Right, I have a Powershell script which looks like this:

Function GatewayScan
{
cls
$CNList = Import-Csv "c:\Users\user\desktop\scans\ComputerList.csv"
"MachineName, GatewayAddress" | out-file "C:\Users\user\desktop\scans\GatewayList.txt" -append -noClobber
foreach ($line in $CNList) {
    IF (test-connection -comp $($line.machinename) -count 1 -quiet) {
    Write-Host "Geting Gateway for " $($line.machinename)
    $gate = get-wmiobject -cn $($line.machinename) win32_networkadapterconfiguration | where {$_.IPEnabled -eq "TRUE"} | select DefaultIPGateway | format-list
    $($line.machinename) + "," + $gate | out-file "C:\Users\user\desktop\scans\GatewayList.txt" -append -noClobber
    }
    Else {
    $($line.machinename) + ", Offline" | out-file "C:\Users\user\desktop\scans\GatewayList.txt" -append -noClobber
    }
}
}

When I run this, it loops through the machines, and pulls out the Default Gateway info. Then it writes this info, along with the machine name to a csv. Problem is, when I oppen the text file it produces, I get something which looks like this:

Machinename,Gateway
PC1,Microsoft.Powershell.Commands.Internal.Format.FormatStartData PC2,Microsoft.Powershell.Commands.Internal.Format.FormatStartData

Any help here would be appreciated, I have no idea what I've done to cause this...

Thanks,

Upvotes: 0

Views: 522

Answers (1)

Shay Levy
Shay Levy

Reputation: 126922

Remove the pipe to Format-List, it generates formatting instructions. Also, make sure you get the raw value of DefaultIPGateway by expanding the property:

... | select -expand DefaultIPGateway

Upvotes: 1

Related Questions