Search code examples
powershelldirectoryget-childitem

variable outputs duplicates


Here is the situation I'm running in to.

I have a shared folder with user profiles. Some profiles have a folder like so username.text1.v2 others have username.text2.v2

I'm trying to write a powershell script that is able to distinguish the difference between both folders... Here is my code

$ParentDir = Get-ChildItem "\\blah\profiles" | Where-Object {$_.PSIsContainer -eq $True}

ForEach ($SubDir in $ParentDir)
{
    #$SubDirName = $SubDir.Name
    If ($SubDir.Name -like "*text1*")
    {
        $firstFolder = $SubDir.Name
    }
    If ($SubDir.Name -like "*text2*")
    {
        $secondFolder = $SubDir.Name
    }

    $secondFolder
}

When I output the code, I get all the folders, but there are several duplicates, triples and even quadruples of the same folder, and it's random. Some folders show up one, others multiple times. I'm not sure why it's outputting this way because there aren't any duplicates in the actual directory.

I can't seem to figure out why that's happening? Thank you in advance!


Solution

  • Take a look at what is happening in your loop. Let's assume following Folder structure:

    • Text1
    • Text2
    • Text3

    using your script following will happen in your loop:

    1. Loop run, Folder Text1
      $firstfolder gets the string "Text1"
      $secondfolder is not initializied Output is nothing as $secondfolder is "empty"
    2. Loop run, Folder Text2
      $firstfolder still contains the string "Text1" from the first loop run
      $secondfolder gets the string "Text2" Output will be Text2
    3. Loop run, Folder Text3
      $firstfolder still contains the string "Text1" from the first loop run
      $secondfolder still contains the string "Text2" from the second loop run
      Output will be Text2

    To get rid of this behavior you should initialize/clear your variables, some ways to do this:

    $firstfolder = ""
    $secondfolder = $null
    Clear-Variable -Name $thirdfolder