write-verbose

Don Jones clearly thinks that write-host is evil (and you are killing pupplies…) but swapping out write-host and write-output is not a great victory.  I admit i get a thrill out of seeing “starting program”, “starting main” and “finished” while working on scripts or debugging, and hate to give that up.

How about write-verbose?  If you are always writing functions i guess that works.  if you use [cmdletbinding] you can toggle the output on and off, which certainly is nice, at the risk of having to type -verbose each time you run it.

I didn’t know, or remember, that you can use write-verbose in a script.  Replace the “write-host” statements with” write-verbose” (and the output comes out in COLOR!!).

How do you evoke verbose output?  Two steps:

$VerbosePreference = "Continue"
# $VerbosePreference = "SilentlyContinue"$VerbosePreference = "Continue"

If VerbosePreference is “silentlyContinue” there is no output when you hit a write-verbose statement.  If it is set to “Continue”, you get output.  Switch it with the comment hash – or just leave in “continue” and comment it off.

PART 2

You, in a function, add [CmdletBinding()] to the top of the function and then can call the function with “-verbose” to get verbose output.  You can’t do that in a scrpt.  Actually, you can as indicated here in a comment to a blog by Steven Murawski. Basically Matt says it doesn’t work, then answers his own question.

If this is your script:

write-output "testing output"
write-verbose "testing verbose"

and you run it from the ISE or from the command interface (.\testverbose), you get “testing output”.  If you run it as (.\testverbose -verbose), you get the same.

What about this?

[CmdletBinding()]
write-output "testing output"
write-verbose "testing verbose"

It doesn’t work and you get output like this

At C:\work\Powershell\testverbose.ps1:18 char:1
+ [CmdletBinding()].
+ ~~~~~~~~~~~~~~~~~
Unexpected attribute 'CmdletBinding'.

but this does

[CmdletBinding()]
param ()
write-output "testing output"
write-verbose "testing verbose"
Advertisements
This entry was posted in Uncategorized. Bookmark the permalink.