Running against CSV, but for each $ColumnA run against matching $ColumnB

-CSV Contains hostnames and IP addresses for devices we are running against.

-Want to execute script against all hostnames, but it MUST be run against the IP for each hostname, not the hostname.

 

Would a simple ForEach loop be possible here?
EX:

$IPList = get-content C:\Some\Path\IPList.CSV

$Host = $IPList |Select-Object {$_.Hostname} -expand IP

ForEach ($Host in $IPList) { 

MAINSCRIPT

}

 

This should give you an example of how to do what you’re after:
[pre]
Function Test-ExampleCSV
{
[CmdletBinding()]
Param (
[Parameter(Mandatory=$True)][string[]]$CSVFile,
)
$CSVContent = Import-CSV -Import-Csv -Path $CSVFile -ErrorAction STOP
ForEach ($Item in $CSVContent)
{
Write-Verbose “$($Item.Hostname)”
Write-Verbose “$($Item.IPAddress)”
Test-Connection $Item.IPAddress
}
}
[/pre]
I am assuming column names are Hostname and IPAddress.

Each row in your CSV file is actioned one at a time…

Okay, so my theory of calling the $Host variable in the foreach against $IPList would not work?

Why does the script need to run against the IP address?

If you’re using invoke-command, that uses WinRM and you need to jump through some additional hoops to connect via the IP.

having said that, if the list contains the IP addresses, you can pull that.

File: Mylist.csv
Header(first row): hostname,ipaddress

$list=(import-csv Mylist.csv)
foreach ($add in $list.ipaddress){
write-host $add}

We need to run against the IP of a separate device , which is listed according to location (Hostname). WinRM does not exist on the devices we are executing against.

However, I see what you’re doing in that example, and I can replace “Write-host $Add” with my main script. (We’re talking 200 lines of code.) from what I can tell.

 

Just for my own clarification, the below would call MAINSCRIPT against each entry in the IP column , yes? (Column names are “Hostname” and “IP”)

$IPList = (import-csv IPList.csv)

foreach ($Thing in $IPList.IP) {

MAINSCRIPT

}

I can’t really answer the question without knowing what mainscript does, so speaking generally:

 

if you nest the MAINSCRIPT in the foreach block AND the script has a variable (such as $Thing in your example) then it should.

 

If the MAINSCRIPT accepts a parameter passed at runtime you could do

.\mainscript.ps1 $Thing

 

-edit - reply deleted. It was incorrect.

I believe your suggestion will work, as the $Thing variable is defined previously, yes - as in my original post in this topic.

Thank you to everyone for the ideas! This forum has taught me tons so far. Love it!

-post deleted - can be removed.-