Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Powershell script support for -verbose

Tags:

I'm creating a .ps1 script which invokes Write-Verbose. I would like to be able to enable/disable these.

I was hoping that I could pass the -Verbose flag when invoking the script and everything would just work. Unfortunately this doesn't seem to be the case.

The verbose messages are not written out to the host. I looked around a bit and found Supporting -Whatif, -Confirm, -Verbose – In SCRIPTS!

But this is from 2007 and the PS team member stated that they were looking for built in support in PS v2.

Anybody have any updates on this or do we have to use the same technique described in that blog post?

Here is an example of the current behavior.

I created a simple script,ex01.ps1, with the following.

Write-Host "line 1" Write-Verbose "line 2" Write-Host "line 3" 

I first executed the script with .\ex01.ps1, and only 1 & 2 were printed as expected. Then I executed it with .\ex01.ps1 -verbose, and got the same result. I was expecting all 3 lines to be printed the second time.

Powershell example result

like image 203
Sayed Ibrahim Hashimi Avatar asked Dec 12 '11 04:12

Sayed Ibrahim Hashimi


People also ask

What can you use PowerShell scripts for?

As a scripting language, PowerShell is commonly used for automating the management of systems. It is also used to build, test, and deploy solutions, often in CI/CD environments.

Why do hackers use PowerShell?

PowerShell was used to carry out the critical piece of the attack. The PowerShell script was used to disable Windows Defender's antivirus prevention capabilities like real-time detection, script and file scanning and a host-based intrusion prevention system.


1 Answers

In order to have the Verbose switch you need to specify the CmdletBinding attribute in your script. To add support for the Confirm and WhatIf switches, add the SupportsShouldProcess attribute and call the ShouldProcess method in the script:

## content of .\ex01.ps1 ## [CmdletBinding(SupportsShouldProcess=$true)] Param() Write-Host "line 1" Write-Verbose "line 2" Write-Host "line 3"  if($PSCmdlet.ShouldProcess($env:COMPUTERNAME,'Remove X')) {     "do something" }   ###########################   PS > .\ex01.ps1 line 1 line 3  PS > .\ex01.ps1 -Verbose line 1 VERBOSE: line 2 line 3  PS > .\ex01.ps1 -WhatIf line 1 line 3 What if: Performing operation "Remove X" on Target "PC1". 
like image 146
Shay Levy Avatar answered Oct 02 '22 03:10

Shay Levy