Home > Blockchain >  Powershell IF conditional isn't firing in the way I expected. Unsure what I'm doing wrong
Powershell IF conditional isn't firing in the way I expected. Unsure what I'm doing wrong

Time:11-15

I am writing a simple script that makes use of 7zip's command-line to extract archives within folders and then delete the original archives.

There is a part of my script that isn't behaving how I would expect it to. I can't get my if statement to trigger correctly. Here's a snippet of the code:

if($CurrentRar.Contains(".part1.rar")){

        [void] $RarGroup.Add($CurrentRar)
        # Value of CurrentRar: 
        # Factory_Selection_2.part1.rar

        $CurrentRarBase = $CurrentRar.TrimEnd(".part1.rar")
        # Value: Factory_Selection_2

        for ($j = 1; $j -lt $AllRarfiles.Count; $j  ){

            $NextRar = $AllRarfiles[$j].Name
            # Value: Factory_Selection_2.part2.rar

            if($NextRar.Contains("$CurrentRarBase.part$j.rar")){
                Write-Host "Test Hit" -ForegroundColor Green
                # Never fires, and I have no idea why
                # [void] $RarGroup.Add($NextRar)
            }
        }

        $RarGroups.Add($RarGroup)
    }

if($NextRar.Contains("$CurrentRarBase.part$j.rar")) is the line that I can't get to fire.

If I shorten it to if($NextRar.Contains("$CurrentRarBase.part")), it fires true. But as soon as I add the inline $j it always triggers false. I've tried casting $j to string but it still doesn't work. Am I missing something stupid?

Appreciate any help.

CodePudding user response:

The issue seems to be your for statement and the fact that an array / list is zero-indexed (means they start with 0).
In your case, the index 0 of $AllRarfiles is probably the part1 and your for statement starts with 1, but the file name of index 1 does not contain part1 ($NextRar.Contains("$CurrentRarBase.part$j.rar"), but part2 ($j 1).

As table comparison

Index / $j Value Built string for comparison (with Index)
0 Factory_Selection_2.part1.rar Factory_Selection_2.part0.rar
1 Factory_Selection_2.part2.rar Factory_Selection_2.part1.rar
2 Factory_Selection_2.part3.rar Factory_Selection_2.part2.rar
3 Factory_Selection_2.part4.rar Factory_Selection_2.part3.rar

Another simpler approach

Since it seems you want to group split RAR files which belong together, you could also use a simpler approach with Group-Object

# collect and group all RAR files.
$rarGroups = Get-ChildItem -LiteralPath 'C:\somewhere\' -Filter '*.rar' | Group-Object -Property { $_.Name -replace '\.part\d \.rar$' } 


# do some stuff afterwards
foreach($rarGroup in $rarGroups){
    Write-Verbose -Verbose "Processing RAR group: $($rarGroup.Name)"

    foreach($rarFile in $rarGroup.Group) {
        Write-Verbose -Verbose "`tCurrent RAR file: $($rarFile.Name)"
        # do some stuff per file
    }
}
  • Related