archcutbank
archcutbank

Reputation: 479

Combine Get-Item with Get-ChildItem?

I thought I was getting all the containers with $containers = Get-ChildItem -path $Path -recurse | ? {$_.psIscontainer -eq $true}, but it appears to return back just subdirectories of my $Path. I really want $containers to contain $Path and its sub-directories. I tried this:

$containers = Get-Item -path $Path | ? {$_.psIscontainer -eq $true}
$containers += Get-ChildItem -path $Path -recurse | ? {$_.psIscontainer -eq $true}

But it does not let me do this. Am I using Get-ChildItem wrong, or how do I get $containers to include the $Path and its $subdirectories by combining a Get-Item and Get-ChildItem with -recurse?

Upvotes: 4

Views: 5324

Answers (5)

KSHA
KSHA

Reputation: 1

Try below one,

Get-ChildItem -Path "master:" -ID $Id -Recurse -WithParent | ForEach-Object { $_.Paths.FullPath }

Upvotes: 0

XP1
XP1

Reputation: 7183

You can try a dot source with a script block:

$containers = . {
    get-item $path | where-object { $_.psIsContainer -eq $true }
    get-childItem $path -recurse | where-object { $_.psIsContainer -eq $true }
}

Upvotes: 0

Shay Levy
Shay Levy

Reputation: 126742

Use Get-Item to get the parent path and Get-ChildItem to get the parent childrens:

$parent = Get-Item -Path $Path
$child = Get-ChildItem -Path $parent -Recurse | Where-Object {$_.PSIsContainer}
$parent,$child

Upvotes: 1

zdan
zdan

Reputation: 29450

In your first call to get-item you are not storing the results in an array (because it's only 1 item). This means you can't append the array to it in your get-childitem line. Simply force your containers variable to be an array by wrapping the result in an @() like this:

$containers = @(Get-Item -path $Path | ? {$_.psIscontainer})
$containers += Get-ChildItem -path $Path -recurse | ? {$_.psIscontainer}

Upvotes: 5

Nick
Nick

Reputation: 4362

The following worked for me:

$containers = Get-ChildItem -path $Path -recurse | Where-object {$_.psIscontainer}

What I end up with is the $path and all sub-directories of $path.

In your example, you have $.psIscontainer but it should be $_.psIscontainer. That might have also been the problem with your command.

Upvotes: 0

Related Questions