Jeremiah Williams
Jeremiah Williams

Reputation: 149

Powershell Foreach loop not looping through each directory

I'm working on a script that goes through each specific folder in the directory, sorts build_info* files by CreationTime, grabs the most recent one from each directory and assigns it to a unique variable. I have the sorting part working, but the problem is that my loop isn't going through each directory, it's just getting the results from the first and putting it into multiple unique variables.

So, this is what I want it to do:

servers01 most recent build_info*.txt file --> $servers01

servers02 most recent build_info*.txt file --> $servers02

servers03 most recent build_info*.txt file --> $servers03

But this is what it's actually doing:

servers01 most recent build_info*.txt file --> $servers01

servers01 most recent build_info*.txt file --> $servers02

servers01 most recent build_info*.txt file --> $servers03

Here's the code I have so far:

$Directory = dir D:\Files\servers* | ?{$_.PSISContainer};
$Version = @();
$count = 0;

foreach ($d in $Directory) {
    $count++
    $Version = Select-String -Path D:\Files\servers*\build_info*.txt -Pattern "Version: " | Sort-Object CreationTime | Select-Object -ExpandProperty Line -Last 1;
    New-Variable -Name "servers0$count" -Value $Version -Force
}

What do I need to change in order to make sure the loop goes through each path and assigns that path's file to its respective variable?

Upvotes: 1

Views: 2094

Answers (1)

G42
G42

Reputation: 10017

You're looping over the number of directories, but you're not actually looping over the directories as the variable $d is not used in the loop.

Try this, with added Write-Host so you get some feedback.

$Directory = dir D:\Files\servers* | ?{$_.PSISContainer};
$Version = @();
$count = 0;

foreach ($d in $Directory) {
    $count++
    Write-Host "Working on directory $($d.FullName)..."

    $latestFile = Get-ChildItem -Path "$($d.FullName)\build_info*.txt" | Sort-Object CreationTime -Descending | Select-Object -First 1      
    $Version    = Select-String -Path $latestFile.FullName -Pattern "Version: " | Select-Object -ExpandProperty Line -Last 1;

    New-Variable -Name "servers0$count" -Value $Version -Force

}

Upvotes: 3

Related Questions