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!
Take a look at what is happening in your loop. Let's assume following Folder structure:
using your script following will happen in your loop:
To get rid of this behavior you should initialize/clear your variables, some ways to do this:
$firstfolder = ""
$secondfolder = $null
Clear-Variable -Name $thirdfolder