Can I check if the -Verbose argument was provided in Powershell?

I wrote my own Powershell Log logging function with the stream parameters (in which stream to record the message) and message (message to record).

The idea is that I can write outputs to both the console and the log file. What I do in the function basically determines which thread to post the message to (using the switch statement), and then write the message to the stream and the log file:

 switch ($stream) { Verbose { Write-Output "$logDate [VERBOSE] $message" | Out-File -FilePath $sgLogFileName -Append Write-Verbose $message break } } 

The question is, can I check if the -Verbose argument was given?

The goal is to write a message to the log file only if -Verbose has been specified.

I already looked in the following reference documents, but did not find anything useful:
- help about_Parameters
- help about_commonparameters

In addition, the -WhatIf parameter does not work with Write-Verbose.

Thanks so much for your answers!

+7
powershell
source share
3 answers

Inside your script check this:

 $PSCmdlet.MyInvocation.BoundParameters["Verbose"].IsPresent 
+16
source share

Also available: Check the $ VerbosePreference parameter. If SilentlyContinue is set to $ Verbose, $ Verbose is not specified on the command line. If it is set to '$ Continue', you can assume that it was installed.

Also applies to the following other general parameters:

 Name Value ---- ----- DebugPreference SilentlyContinue VerbosePreference SilentlyContinue ProgressPreference Continue ErrorActionPreference Continue WhatIfPreference 0 WarningPreference Continue ConfirmPreference High 

Taken from one of the MSDN blog pages a long time ago ... so this should be relevant to the relatively old versions of Powershell. Also see "Get-Help about_CommonParameters" in Powershell v4.

+11
source share

More generally: since you can specify -Verbose: $ false on the command line, the following code handles this case. It also works for any other switch parameter:

 $Verbose = $false if ($PSBoundParameters.ContainsKey('Verbose')) { # Command line specifies -Verbose[:$false] $Verbose = $PsBoundParameters.Get_Item('Verbose') 
0
source share

All Articles