SPJLee
SPJLee

Reputation: 47

Powershell Get-Item / Get-ChildItem

Quite new to Powershell and scripting/programming and have a pretty basic problem I'm stuck with.

If I have a structure such as this:

File stucture piccy

Set-Location $PSScriptRoot

And do the following, I get the folders within the Logfiles folder:

 $folders = Get-ChildItem -Directory -Path .\Logfiles -Recurse

If I then do the following I can see the first subfolder in "Logfiles"

$folders[0]

But now if I do the following, it seems to be using the "Scripts" folder instead of "Logfiles" as a root folder:

Get-ChildItem $folders[0]

or

Get-ChildItem .\Logfiles\$folders[0]

...(gives a null result)

Does anyone have any information on how directories work within powershell commands? I'm guessing I'm making a very basic mistake with handling the commands!!

Upvotes: 2

Views: 982

Answers (2)

Mathias R. Jessen
Mathias R. Jessen

Reputation: 174465

PowerShell takes $folders[0] - which resolves to a [DirectoryInfo] object - and attempts to convert it to a string that it can bind to Get-ChildItem's -Path parameter.

But converting the directory object to a string results in just its name, the information about its location gets lost in the process.

Instead, you'll want to either do:

$folders[0] |Get-ChildItem

... which will cause PowerShell to correctly bind the full path of the directory object - or you can pass the full path as the argument to -Path:

Get-ChildItem $folders[0].FullName

Upvotes: 0

Hashbrown
Hashbrown

Reputation: 13013

Try

Get-ChildItem ".\Logfiles\$($folders[0].Name)"

Or

Get-ChildItem $folders[0].FullName

Or my favourite

$folders[0] | Get-ChildItem

Upvotes: 1

Related Questions