user2312915
user2312915

Reputation: 39

Trying to capture IP from powershell script, getting System.String[] instead

I'm trying to pull a machine's IPAddress, MACAddress, and DefaultIPGateway information from the Win32_NetworkAdapterConfiguration object into an exported CSV file named NetworkAdapterConfiguration.csv using this script:

$StrComputer = $env:computername
$NetAdConfig = gwmi Win32_NetworkAdapterConfiguration -Comp $StrComputer
$NetAdConfig | Select-Object IPAddress,MACAddress,DefaultIPGateway | Export-Csv -Path C:\CSVFolder\NetworkAdapterConfiguration.csv -Encoding ascii -NoTypeInformation

When I view this CSV I get "System.String[]" where the IP and DefaultIPGateway values should be displayed. I'm assuming this information gets represented as an array and that is why I'm seeing the System.String[] view, but I have little experience with Powershell. Any help, advice, and references are much appreciated.

Upvotes: 0

Views: 3156

Answers (2)

boeprox
boeprox

Reputation: 1868

I have a function that I wrote called Convert-OutputForCSV that can help to remove the string[] issues you are seeing as well. You could do something like this to expand out the arrays into a more readable property.

$StrComputer = $env:computername
$NetAdConfig = gwmi Win32_NetworkAdapterConfiguration -Comp $StrComputer
$NetAdConfig | Select-Object IPAddress,MACAddress,DefaultIPGateway |
Convert-OutputForCSV | 
Export-Csv -Path C:\CSVFolder\NetworkAdapterConfiguration.csv -Encoding ascii -NoTypeInformation

Upvotes: 1

Bill_Stewart
Bill_Stewart

Reputation: 24525

The IPAddress and DefaultIPGateway properties are arrays. If you are sure your machines only have one IP address and default gateway, you can do this:

$computer = $ENV:COMPUTERNAME
get-wmiobject Win32_NetworkAdapterConfiguration -filter "IPEnabled=TRUE" -computername $computer | foreach-object {
  new-object PSObject -property @{
    "Computer" = $computer
    "MACAddress" = $_.MACAddress
    "IPAddress" = $_.IPAddress[0]
    "DefaultIPGateway" = $_.DefaultIPGateway[0]
  } | select-object Computer,MACAddress,IPAddress,DefaultIPGateway
}

Here's another way that uses Select-Object:

$computer = $ENV:COMPUTERNAME
get-wmiobject Win32_NetworkAdapterConfiguration -filter "IPEnabled=TRUE" -computername $computer | foreach-object {
    $_ | select-object `
      @{Name="ComputerName";     Expression={$_.__SERVER}},
      @{Name="MACAddress";       Expression={$_.MACAddress}},
      @{Name="IPAddress";        Expression={$_.IPAddress[0]}},
      @{Name="DefaultIPGateway"; Expression={$_.DefaultIPGateway[0]}}
}

Upvotes: 2

Related Questions