9009
9009

Reputation: 87

Cannot loop items from a string array using PowerShell

I have the following code and I cannot loop the items using PowerShell.

$ipAddress = @('107.20.253.26', '107.20.178.220', '8.8.8.8')

for($i=0; $i -le $ipAddress.count; $i++) {

    $resolve = nslookup $i | Format-list
    $resolve | Out-File $resolveFile

}

Upvotes: 1

Views: 1083

Answers (1)

G42
G42

Reputation: 10019

For me, this loops over the IPs fine. There is an easier way to do in PowerShell though using foreach.
And remove Format-Table; it is useful when writing to host but just turned your nslookup result to Microsoft.PowerShell.Commands.Internal.Format.FormatEntryData datatype.
Use -Append with Out-File to avoid overwriting previous result.

$ipAddress = @('107.20.253.26', '107.20.178.220', '8.8.8.8')

foreach($ip in $ipAddress) {

    # remove Format-Table
    $resolve = nslookup $ip

    # Add Append flag so that you are not overwriting previous contents on each loop
    $resolve | Out-File $resolveFile -Append

}

Upvotes: 2

Related Questions