RafaelGP
RafaelGP

Reputation: 1889

Get "parent folder + file name" from a Select-String output

I'm writing a simple script to list all the files recursively within a folder "fullscreen" containing the word 'plugin'. Because the path is too long, and unnecessary, I decided to get the jut the FileName. The problem is that all the files are called "index.xml" so it would be very helpful get: "containing folder + file name". So the output would look something like this:

on\index.xml
off\index.xml

Instead of:

C:\this\is\a\very\long\path\fullscreen\on\index.xml
C:\this\is\a\very\long\path\fullscreen\off\index.xml

This is what I have:

dir .\fullscreen | sls plugin | foreach { write-host $($_).path }

I am getting this error:

Cannot bind argument to parameter 'Path' because it is null.

Upvotes: 4

Views: 2996

Answers (2)

zdan
zdan

Reputation: 29450

The Directory property of the FileInfo class tells you the parent directory, you just have to grab the base of that and join with the name of your file. Note the extra foreach that turns the item back into a FileInfo object:

dir .\fullscreen | sls plugin | foreach{ get-item $_.Path } | foreach { write-output (join-path $_.Directory.BaseName $_.Name)}

If you want to avoid the extra pipeline:

dir .\fullscreen | sls plugin | foreach{ $file = get-item $_.Path; write-output (join-path $file.Directory.BaseName $file.Name)}

Upvotes: 1

Keith Hill
Keith Hill

Reputation: 201662

You're close: :-)

dir .\fullscreen | sls plugin | foreach { write-host $_.path }

This would have also worked:

dir .\fullscreen | sls plugin | foreach { write-host "$($_.path)" }

BTW I would generally avoid Write-Host unless you're really just displaying info only for someone to see who is sitting at the console. If you later wanted to capture this output to a variable, it wouldn't work as-is:

$files = dir .\fullscreen | sls plugin | foreach { write-host $_.path } # doesn't work

Most of the time you can achieve the same output and enable capture to a variable by just using the standard output stream e.g.:

dir .\fullscreen | sls plugin | foreach { $_.path }

And if you are on PowerShell v3 you can simplify to:

dir .\fullscreen | sls plugin | % Path

Update: to get just the containing folder name, do this:

dir .\fullscreen | sls plugin | % {"$(split-path (split-path $_ -parent) -leaf)\$($_.Filename)"}

Upvotes: 9

Related Questions