Bengt Nilsson
Bengt Nilsson

Reputation: 1

How to add a string to the output from powershell

I use this to get a list of folders containing .h files. **

$type = "*.h"
$HDIRS = dir .\$type -Recurse |
Select-Object Directory -Unique |
Format-Table -HideTableHeaders

** It gives me a list of folders. Now I want "-I " before every foldername. Common string manipulation doesn't seem to work

Upvotes: 0

Views: 355

Answers (2)

Maximilian Burszley
Maximilian Burszley

Reputation: 19644

The mantra goes filter left, format right.

Our data:

$type = '.\*.h'
Get-ChildItem -Path $type -Recurse

The manipulation (filter):

Select-Object { "-I $($_.Directory)" } -Unique

And the format:

Format-Table -HideTableHeaders

In many cases, PowerShell cmdlets allow you to pass scriptblocks (closures) to evaluate to values and that's what I'm doing above with the Select-Object call.

Upvotes: 0

Steven
Steven

Reputation: 7057

You still have rich objects after the select so to manipulate the strings you have to reference the one property you've selected "Directory"

$type = "*.h"
$HDIRS = Dir .\$type -Recurse |
Select-Object Directory -Unique |
ForEach-Object{
    $_.Directory = "-I" + $_.Directory
    $_
} |
Format-Table -HideTableHeaders

This will result in $HDIRS looking like a list of folder paths like -IC:\temp\something\something...

However, the format output objects are generally not suitable for further consumption. It looks like you're interested in the strings you could simply make this a flat array of strings like:

$type = "*.h"
$HDIRS = Dir .\$type" -Recurse |
Select-Object -ExpandProperty Directory -Unique |
ForEach-Object{ "-I" + $_ } 

Upvotes: 1

Related Questions