2

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

Mathias R. Jessen
  • 157,619
  • 12
  • 148
  • 206
SPJLee
  • 35
  • 3

2 Answers2

1

Try

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

Or

Get-ChildItem $folders[0].FullName

Or my favourite

$folders[0] | Get-ChildItem
Hashbrown
  • 12,091
  • 8
  • 72
  • 95
0

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
mklement0
  • 382,024
  • 64
  • 607
  • 775
Mathias R. Jessen
  • 157,619
  • 12
  • 148
  • 206
  • Cheers for the explanation Mathias, still getting to grips with structuring commands in Powershell. Thanks for the the reputation bump too! – SPJLee Nov 17 '20 at 00:07
  • The learning curve is a bit steep, thankfully the feedback loop is tight :) – Mathias R. Jessen Nov 17 '20 at 00:09
  • Note that in PowerShel [Core] v6.1+ `$folders[0]`, or, more generally, _all_ objects output by `Get-ChildItem`, irrespective of what arguments were used, always stringify to their _full path_ (`.FullName`) - see [this answer](https://stackoverflow.com/a/53400031/45375). – mklement0 Nov 17 '20 at 01:46