Author Posts

December 9, 2013 at 11:06 am

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

December 9, 2013 at 11:22 am

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 }
    }
}

December 9, 2013 at 11:29 am

thank you very much