Home > Software design >  Composing PowerShell's Out-String within another function
Composing PowerShell's Out-String within another function

Time:10-26

I'd like to be able to write a version of PowerShell's Out-String that doesn't pad or truncate the resulting output. I can achieve something like this using the following code:

Write-Host (Get-ChildItem env: | Out-String -Stream -Width 9999 | ForEach-Object { "$($_.Trim())`n" })

Resulting in the desired output:

 Name                           Value
 ----                           -----
 ALLUSERSPROFILE                C:\ProgramData
 APPDATA                        C:\Users\Me\AppData\Roaming
... etc ...

I'd like to capture this functionality into a new version of Out-String, but can't work out how to accomplish this. This is as close as I've got:

filter Out-String2 {
  $_ | Out-String -Stream -Width 9999 | ForEach-Object { "$($_.Trim())`n" }
}

Write-Host (Get-ChildItem env: | Out-String2)

But this results in the undesirable effect of having each element of Get-ChildItem being rendered independently in the filter resulting in output like:

 Name                           Value
 ----                           -----
 ALLUSERSPROFILE                C:\ProgramData

 Name                           Value
 ----                           -----
 APPDATA                        C:\Users\Me\AppData\Roaming

...etc...

Is this kind of composition of pipeline elements possible in PowerShell, and if so - how?

CodePudding user response:

This doesn't work on a filter, but you can make use of the Automatic variable $input if you make a function out of this:

function Out-String2 {
    Param(
        [Parameter(Mandatory = $true, Position = 0, ValueFromPipeline = $true)]
        $Data
    )
    # if the data is sent through the pipeline, use $input to collect is as array
    if ($PSCmdlet.MyInvocation.ExpectingInput) { $Data = @($input) }
    $Data | Out-String -Stream -Width 9999 | ForEach-Object { "$($_.Trim())`r`n" }
}

Call it using

Write-Host (Out-String2 (Get-ChildItem env:))

or

Write-Host (Get-ChildItem env: | Out-String2)
  • Related