I have written my own Powershell logging function Log
with parameters stream
(on which stream to write the message) and message
(the message to write).
The idea is that i can write the outputs both to the console and to a log-file. What I do in the function is basically determine on which stream to publish the message (with a 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 now, is it possible to check if the -Verbose argument was given?
The goal is to write the message to the log-file only if the -Verbose was given.
I looked already in the following help docs but didn't find anything helpful:
- help about_Parameters
- help about_commonparameters
Also, the -WhatIf parameter does not work with Write-Verbose.
Thanks a lot for your answers!
$args. Contains an array of values for undeclared parameters that are passed to a function, script, or script block. When you create a function, you can declare the parameters by using the param keyword or by adding a comma-separated list of parameters in parentheses after the function name.
The Get-Variable cmdlet gets the PowerShell variables in the current console. You can retrieve just the values of the variables by specifying the ValueOnly parameter, and you can filter the variables returned by name.
Use param to Pass an Argument to a PowerShell Script We can define arguments using the param statement. It also allows us to use the default values. Here, the variable $address has a default value. And the default value will be used if the user does not provide any value.
To make sure PowerShell executes what you want, navigate in the command line to the same directory where you will save your scripts. Name the script Unnamed_Arguments_Example_1. ps1 and run it with the argument FOO. It will echo back FOO.
Inside your script check this:
$PSCmdlet.MyInvocation.BoundParameters["Verbose"].IsPresent
Also available: Check the parameter '$VerbosePreference'. If it is set to 'SilentlyContinue' then $Verbose was not given at the command line. If it is set to '$Continue' then you can assume it was set.
Also applies to the following other common parameters:
Name Value ---- ----- DebugPreference SilentlyContinue VerbosePreference SilentlyContinue ProgressPreference Continue ErrorActionPreference Continue WhatIfPreference 0 WarningPreference Continue ConfirmPreference High
Taken from an MSDN blog page from long ago... so it should be relevant with relatively old versions of Powershell. Also see "Get-Help about_CommonParameters" in Powershell v4.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With