Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I loop through a CSV file with a batch or PowerShell script?

I have a CSV file with two different columns, one with PC names and one with MAC addresses like this:

PCxxxx 00-11-22-33-44-55
...
...

These values should be placed into the following CLI command:

wdsutil /Set-Device /Device:PCxxxx /ID:00-11-22-33-44-55

Now since there are about 200 of them, I want to automate this.

As a matter of interest, could one do this with batch? It would be quite complicated, right? I thought of arrays, but don't think one can do this in batch.

Maybe with PowerShell it'd be a bit easier.

like image 835
JohnnyFromBF Avatar asked Apr 26 '12 08:04

JohnnyFromBF


People also ask

Will batch commands work in PowerShell?

To run the batch commands from PowerShell, we can use the Start-Process cmdlet as earlier explained and which executes a cmd command on the server.


1 Answers

In a batch file:

for /f "tokens=1,2 delims= " %%a in (foo.csv) do (
    wdsutil /Set-Device /Device:%%a /ID:%%b
)

Actually, you can do that as a one-liner from cmd directly:

for /f "tokens=1,2 delims= " %a in (foo.csv) do wdsutil /Set-Device /Device:%a /ID:%b

In PowerShell you can use a similar idea:

Get-Content foo.csv | ForEach-Object {
  $name,$mac = -split $_
  wdsutil /Set-Device /Device:$name /ID:$mac
}

Or use the CSV import cmdlet, but given your question you don't seem to have column headers, so you need to provide them manually:

Import-CSV -Delim ' ' -Path foo.csv -Header Name,Mac | ForEach-Object {
    wdsutil /Set-Device "/Device:$($_.Name)" "/ID:$($_.Mac)"
}
like image 140
Joey Avatar answered Sep 20 '22 15:09

Joey