MacMartin
MacMartin

Reputation: 2866

Powershells write-verbose creates no outputvariable (-ov)

Not critical but gave me a headache... I wanted the output of write-verbose into a variable for documentation/debugging.
Its nice, powershel has an own parameter for the output of commands (see help about_commonparameters).
But whats not stated in the help is: what write-* output goes to what variable so i tried and tried and found out:

BUT where goes the write-verbose output? The help says

This cmdlet supports the common parameters: -Verbose, -Debug, -ErrorAction, -ErrorVariable, -OutBuffer, and -OutVariable.

For Example: write-verbose "test" -verbose -outvariable $a Nothings in $a

(same for write-warning "test" -ev $b... nothing) any ideas? thanks in advance

Upvotes: 2

Views: 301

Answers (3)

mjolinor
mjolinor

Reputation: 68263

One option:

$VerbosePreference = 'continue'
Write-Verbose ($a = 'foo')
$a

VERBOSE: foo
foo

Upvotes: 1

Ansgar Wiechers
Ansgar Wiechers

Reputation: 200233

If you want just the output of Write-Verbose in a variable you could use redirection:

$var = Write-Verbose 'something' 4>&1

That will merge the verbose stream with the success output stream, which can be captured in a variable.

This won't work if you need regular and verbose output in separate variables, though. As far as I'm aware you must redirect verbose output to a file and read the file into a variable for that.

PS C:\> function Foo { Write-Verbose 'foo'; Write-Output 'bar' }
PS C:\> $VerbosePreference = 'Continue'
PS C:\> Foo
VERBOSE: foo
bar
PS C:\> $o = Foo 4>'C:\temp\verbose.txt'
PS C:\> $v = Get-Content 'C:\temp\verbose.txt'
PS C:\> $o
bar
PS C:\> $v
foo

Same goes for warnings, only that warnings go to stream number 3.

PS C:\> function Bar { Write-Warning 'foo'; Write-Output 'bar' }
PS C:\> $WarningPreference = 'Continue'
PS C:\> Bar
WARNING: foo
bar
PS C:\> $o = Bar 3>'C:\temp\warning.txt'
PS C:\> $w = Get-Content 'C:\temp\warning.txt'
PS C:\> $o
bar
PS C:\> $w
foo

Redirection of the warning, verbose, and debug streams was introduced with PowerShell version 3.

Upvotes: 1

Mike Shepard
Mike Shepard

Reputation: 18156

Write-Verbose has no "output" to write to an OutVariable. It does write things to the verbose stream, though.

OutVariable contains all objects that were output to the output stream.

Upvotes: 2

Related Questions