amazing result logical construct

This topic contains 2 replies, has 2 voices, and was last updated by Profile photo of Bin Ary Bin Ary 3 years, 4 months ago.

  • Author
    Posts
  • #11875
    Profile photo of Bin Ary
    Bin Ary
    Participant

    hello
    i am trying to grap all folders with "paris" in the name string in the c:\RootFolder, the problem is that sometimes it retrive all folders sometimes only one occurence...i do not know why.

    # my portion of script
    $path="c:\RootFolder"
    $Dest="c:\Dest"
    $Dest="c:\OtherDest"

    $Allfolders=gci c:\$path | where { $_.psiscontainer }
    foreach ($folder in $Allfolders)
    {
    if ($folder.name -like "Paris*")
    {
    $list = @(
    @{source = "C:\$path\$($folder.name)"; dest=$Dest}
    )
    }

    else {

    $list += @(
    @{source = "C:\$path\$($folder.name)"; dest=$OtherDest}
    )
    }
    }
    thank you in advance

  • #11878
    Profile photo of Bin Ary
    Bin Ary
    Participant

    thank you very much

  • #11877
    Profile photo of Dave Wyatt
    Dave Wyatt
    Moderator

    When the name starts with Paris, you're overwriting the value of $list with a new array. When it doesn't start with Paris, you're adding to the variable.

    Personally, I don't like this approach anyway. Use the Pipeline, and let PowerShell convert it to an array for you if there are multiple results. The performance will be better. For example:

    
    # my portion of script
    $path = 'c:\RootFolder'
    $Dest = 'c:\Dest'
    $OtherDest = 'c:\OtherDest'
    
    $list = Get-ChildItem -Path $path |
    Where-Object { $_.PSIsContainer } |
    ForEach-Object {
        $folder = $_
        if ($folder.name -like '*Paris*')
        {
            New-Object psobject -Property @{source = $folder.FullName; dest = $Dest}
        }
        else
        {
            New-Object psobject -Property @{source = $folder.FullName; dest = $OtherDest }
        }
    }
    

You must be logged in to reply to this topic.