Skip to content

Instantly share code, notes, and snippets.

@indented-automation
Last active August 11, 2023 23:07
Show Gist options
  • Save indented-automation/82848a6717a05b57e7c973fd66ac55f6 to your computer and use it in GitHub Desktop.
Save indented-automation/82848a6717a05b57e7c973fd66ac55f6 to your computer and use it in GitHub Desktop.
filter Write-String {
<#
.SYNOPSIS
Write a string representation of an object.
.DESCRIPTION
Write-String creates formatted string representations of an input object.
.INPUTS
System.Object
.EXAMPLE
Get-Process | Write-String
Write each process object using the ToString method.
.EXAMPLE
Get-Process | Write-String { "$($_.Name): $($_.ID)" }
Write each process object using the script block.
.EXAMPLE
Get-Process | Write-String -Format '{0}: {1}' -Property Name, ID
Write each process object using the specified format.
#>
[CmdletBinding(DefaultParameterSetName = 'ToString')]
[OutputType([String])]
param (
# The input object to write.
[Parameter(ValueFromPipeline = $true)]
[Object[]]$InputObject,
# Write the string using a script block. The script block may include the pipeline variable, $_, to reference the input object.
[Parameter(Position = 1, ParameterSetName = 'FromScriptBlock')]
[ScriptBlock]$ScriptFormat,
# Write a string using the defined format using the "-f" operator.
[Parameter(Mandatory = $true, ParameterSetName = 'ToFormat')]
[String]$Format,
# A list of properties from the object which will be used to satisfy a format string.
[Parameter(Mandatory = $true, ParameterSetName = 'ToFormat')]
[String[]]$Property
)
if (($InputObject | Measure-Object).Count -gt 1) {
$psboundparameters.Remove('InputObject')
$InputObject | Write-String @psboundparameters
} else {
if ($pscmdlet.ParameterSetName -eq 'FromScriptBlock') {
& $ScriptFormat
} elseif ($pscmdlet.ParameterSetName -eq 'ToFormat') {
try {
$Format -f (foreach ($name in $Property) { $_.$name })
} catch {
$pscmdlet.ThrowTerminatingError($_)
}
} else {
$_.ToString()
}
}
}
@asheroto
Copy link

image

I fixed it by changing line 51 to this

$Format -f ($Property | ForEach-Object { $_.$name })

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment