kamilk
kamilk

Reputation: 4039

Combining results from two calls to Select-Object

As part of a PowerShell script, I want to generate a list of subfolders of two different folders. I approached this by calling Get-ChildItem twice, using Select-Object to transform the paths, and trying to combine the results. However, this is the combining step where I got stuck. I have tried this:

$cur = Get-Location
$mainDirs = Get-ChildItem -Directory -Name | Select-Object {"$cur\$_"}
$appDirs = Get-ChildItem -Directory -Name Applications\Programs |
           Select-Object {"$cur\Applications\Programs\$_"}
$dirs = $mainDirs,$appDirs      #Doesn't work!

But $dirs ends up consisting of the entries from $mainDirs followed by as many null items as many items there are in $appDirs.

How can I combine these in PowerShell?

Edit: The output of mainDirs[0]:

"$cur\$_"                
---------                
D:\somefolder\somesubfolder

The output of appDirs[0]:

"$cur\Applications\Programs\$_"                        
-------------------------------                        
D:\somefolder\Applications\Programs\othersubfolder

Upvotes: 2

Views: 237

Answers (1)

Ansgar Wiechers
Ansgar Wiechers

Reputation: 200203

Get-ChildItem accepts a string array as input. Simply pass both folders whose subfolders you want listed as an array. Expand the FullName property to get the paths of subfolders:

$folders = '.', '.\Applications\Programs'
$dirs    = Get-ChildItem $folders -Directory | Select-Object -Expand FullName

If you want the relative rather than the absolute path remove the current directory from the beginning of the path strings:

$pattern = '^{0}\\' -f [regex]::Escape($PWD.Path)
$folders = '.', '.\Applications\Programs'
$dirs    = Get-ChildItem $folders -Directory |
           ForEach-Object { $_.FullName -replace $pattern }

Upvotes: 3

Related Questions