Ed Pollnac
Ed Pollnac

Reputation: 121

How do I cross referenced a variable with contents of a text file?

File has 2 fields, BinaryID and name. I download files by the BinaryID and need to rename them. The Write-Host example in the ForEach loop only echo's back the last line of the text file for each of the ID's in BinaryID's.

4468 TP_146_18.zip 4468 TP_146_18.zip 4468 TP_146_18.zip 4468 TP_146_18.zip 4468 TP_146_18.zip

$BinaryID = 3927,3988,4073,4151,4265

Get-Content -Path "D:\SIS\PS_Zips.txt" | ForEach-Object {
    $BID = $_.Split(',')
}

ForEach ($ID in $BinaryID) {
if ( $ID -eq $BID[0] ) { Write-Host $BID[0] $BID[1] }
    Write-Host $BID[0] $BID[1]
}

Upvotes: 0

Views: 49

Answers (1)

Theo
Theo

Reputation: 61048

Thanks for explaining that the downloaded files do have an extension (.zip)

One way of doing this is to use Import-Csv with the -Header parameter like this:

$downloadFolder = 'X:\Path\to\where\you\have\downloaded\the\files'
$BinaryID       = 3927,3988,4073,4151,4265

$data  = Import-Csv -Path 'D:\SIS\PS_Zips.txt' -Header BinaryId, FileName
$files = Get-ChildItem -Path $downloadFolder -File -Filter '*.zip' |
         Where-Object { $BinaryID -contains $_.BaseName }

foreach ($file in $files) { 
    $file | Rename-Item -NewName { ($data | Where-Object { $_.BinaryId -eq $file.BaseName }).FileName }
}

The Where-Object filters the files to collect so only files with a BaseName that is in your $BinaryID variable are passed through. Next, all you need is to find the corresponding data row by its BinaryId field and use the FileName field to rename the file.

Upvotes: 2

Related Questions