'enable Write-Verbose behavior in powershell script
In a powershell script file.ps1, I have
Write-Host "here is a host message"
Write-Verbose "here is a verbose message"
When file.ps1 is run in Windows Terminal using Powershell 7, not all messages are written to the console.
PS> .\file.ps1
here is a host message
I would like to be able to pass -Verbose so Write-Verbose is seen:
PS> .\file.ps1 -Verbose
here is a host message
here is a verbose message
What does script file.ps1 need to enable verbose messages?
Solution 1:[1]
You would need to add [cmdletbinding()] to your script to enable CommonParameters:
script.ps1
[cmdletbinding()]
param()
Write-Host "here is a host message"
Write-Verbose "here is a verbose message"
From host:
PS /> ./script.ps1 -Verbose
here is a host message
VERBOSE: here is a verbose message
Solution 2:[2]
If you can't edit the script, you can also user set the VerbosePrefrence to Continue in the shell that calls the script.
$VerbosePreference = "Continue"
This will enable Verbose output on all function you are goint to execute. Check out Microsofts Help about Prefences. There are many usefull more.
If you ike to enable Verbose Output for only a specific CmdLet, you can use $PSDefaultParameterValues to assign a default Parameter to this function:
$PSDefaultParameterValues.Add("MyCmdLet:Verbose",$true)
this would enable Verbose Output for "MyCmdLet". However, be carefull when using $PSDefaultParameterValues, since you can really mess things up, especially if you call other script, since the default parameter values will there be affected aswell.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Santiago Squarzon |
| Solution 2 | Evilcat |
