Jon Markopoulos
Jon Markopoulos

Reputation: 13

How can I use input file to feed powershell command?

I have a csv file with the following info (for readibility I removed commas) :

box1    1.1.1.1     user        password
box2    2.2.2.2     user        password
box3    3.3.3.3     user        password

I need to execute command with parameters from the csv file, like below :

plink -l user -pw password 1.1.1.1 lsvdisk -delim , -nohdr

and feed a file, with the box name on the start of each line.

In other words, I have ~300 storage boxes (V7k/SVC) and I need an inventory of all the UUID of LUNs. Preferably powershell.

Upvotes: 1

Views: 1130

Answers (1)

Joey
Joey

Reputation: 354644

Import-Csv and ForEach-Object are your friend here:

Import-Csv -Header Host,Ip,User,Pw foo.csv | ForEach-Object {
  plink -l $_.User -pw $_.Pw $_.Ip lsvdisk -delim ',' -nohdr
}

Note that we have to enclose the , in quotes to ensure it's passed as a single parameter.¹

Within the script block of ForEach-Object $_ is the current object, which has the properties from the CSV file. We had to give the import custom headers since your file apparently doesn't have any. If that's not how your file looks, then adjust accordingly.

This will give you lots of output, of which perhaps the host name is no longer available. Depending on how the output looks, it may make sense to parse it and wrap it up into nice objects, but I don't really know how the output looks. A simple way of simply capturing output and associating it with the host name would be the following:

Import-Csv -Header Host,Ip,User,Pw foo.csv | ForEach-Object {
  $output = plink -l $_.User -pw $_.Pw $_.Ip lsvdisk -delim ',' -nohdr
  New-Object PSObject -Property @{
    Host = $_.Host
    Output = $output
  }
}

To prefix each line of the output with the host name you can loop over the output again:

Import-Csv -Header Host,Ip,User,Pw foo.csv | ForEach-Object {
  $host = $_.Host
  plink -l $_.User -pw $_.Pw $_.Ip lsvdisk -delim ',' -nohdr | ForEach-Object {
    "${host}: $_"
  }
}

¹ If the command line includes lots of things that PowerShell wants to interpret itself, it's often easier to use %-- to stop parsing for the rest of the line after that, which then passes the rest verbatim to external commands.

Upvotes: 1

Related Questions