Skip to content

Instantly share code, notes, and snippets.

@jessitron
Last active March 17, 2021 20:28
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jessitron/c44df7957d2087b49d9fb4bf0b385ef7 to your computer and use it in GitHub Desktop.
Save jessitron/c44df7957d2087b49d9fb4bf0b385ef7 to your computer and use it in GitHub Desktop.
Unwrapping STDERR in Powershell
<#
.Synopsis
STDERR strings get wrapped in an ErrorRecord. Unwrap those back into strings.
#>
function Convert-StderrString {
# Why can this not be an advanced function with [CmdletBinding()] ?
# Somehow it doesn't work if I put that in.
begin {
}
process {
if ($PSItem -is [System.Management.Automation.ErrorRecord]) {
# yeah OK I haven't figured out how to say 'and' yet
if ($PSItem.FullyQualifiedErrorId -eq "NativeCommandError") {
if ($PSItem.TargetObject -is [string]) {
$PSItem.TargetObject
return;
}
}
}
$PSItem
}
end {
}
}
Set-Alias -Name fix-stderr -Value Convert-StderrString
@KacperMucha
Copy link

$PSItem -is [System.Management.Automation.ErrorRecord] -and $PSItem.FullyQualifiedErrorId -eq "NativeCommandError" -and $PSItem.TargetObject -is [string]

:)

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