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

20,285

Solution 1

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)"
}

Solution 2

# First column in csv file must be titled PCName, second column must be titled MacAddress.
Import-Csv myfile.csv | %{ wdsutil /Set-Device /Device:$_.PCName /ID:$_.MacAddress } 

Warning: not tested.

Share:
20,285
JohnnyFromBF
Author by

JohnnyFromBF

Updated on May 29, 2020

Comments

  • JohnnyFromBF
    JohnnyFromBF almost 4 years

    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.