1

I am trying to delete contents of few folders. What I have:

$Config = @{
    InstallPath = 'C:\Program Files\App'
    SubPaths = @('www\app1', 'www\app2', 'www\app3')
}

And here is the code to get contents:

$Config.SubPaths | Select-Object { Join-Path $Config.InstallPath $_ } | Get-ChildItem

But it doesn't work, because Get-ChildItem receives object like below:

@{ Join-Path $Config.InstallPath $_ =C:\Program Files\App\www\app1}

Error:

Get-ChildItem : Cannot find drive. A drive with the name '@{ Join-Path $Config.InstallPath $_ =C' does not exist.
At line:1 char:85
+ ... elect-Object { Join-Path $Config.InstallPath $_ } | Get-ChildItem
+                                                             ~~~~~~~~~~~~~
    + CategoryInfo          : ObjectNotFound: (@{ Join-Path $C...stallPath $_ =D:String) [Get-ChildItem], DriveNotFoun
   dException
    + FullyQualifiedErrorId : DriveNotFound,Microsoft.PowerShell.Commands.GetChildItemCommand

How can I convert result of Select-Object to simple array of strings? Or any other approach to make code better?

1
  • $Config.SubPaths | ForEach-Object { Join-Path $Config.InstallPath $_ } | Get-ChildItem Commented Oct 6, 2017 at 13:30

1 Answer 1

1

The results you are getting are because you made a new object with the the literal property Join-Path $Config.InstallPath $_. Instead...

$Config.SubPaths | ForEach-Object { Join-Path $Config.InstallPath $_ } | Get-ChildItem

You are not trying to select a property of a single subpath but generate a string from each of the SubPaths. Using Foreach-object instead to iterate over the collection should get you the results you are looking for.

While you could create custom objects and properties using calculated properties I figure this is not the direction you are going for. But to answer the question in the title you could have done this:

$Config.SubPaths | 
    Select-Object @{Name="Path";Expression={Join-Path $Config.InstallPath $_}} | 
    Get-ChildItem

Get-ChildItem should bind to the path property of the new object were are making

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks, that's exacly what I looking for.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.