I'm writing a script to load computer names from a CSV file, then look up their IP addresses.

The script creates an error when using the name from the CSV.

If I run the script in ISE, the error shows up, but the result still comes though. If I run the script from powershell, it errors and the result is null.

If I substitute the $PCname = $_.System for $PCname = "Computer01" everything works fine.

If I write-host $_.System it displays "Computer01". How can I get this to work in powershell?

$file = "\\server.contoso.net\private$\Systems.csv";
$CSV = Import-CSV $file;

$CSV | %{
    if ($_.Skip -eq 0)
    {
        $PCname = $_.System
       # $PCname = "Computer01"
        write-host $PCname
        try
        { 
            $ipaddress = [System.Net.Dns]::GetHostByName($PCname).AddressList[0].IpAddressToString
        }
        Catch [system.exception]
        { 
            if(1)
            { $error[0].tostring() }
        }
    }
}

Error displayed is:

Exception calling "GetHostByName" with "1" argument(s): "The requested name is valid, but no data of the requested type was found"

有帮助吗?

解决方案

Turns out that the values in the CSV at some point had whitespace added after them, which caused a name look up error. I'm not sure why ISE would still be able to look up the host, but removing the whitespace fixed the issue.

Thanks to sha, his recommendation helped me see the whitespace.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top