How to save a Boolean switch for a function call

26 views Asked by At

I have a script that has everything wired up to be -Verbose. The script needs to be changed to have a single variable at top $verbose = $true or $false

With out rewriting every single line in the script like this

if ($verbose) {
   Remove-Item -LiteralPath "$.\blah" -Force -recurse -EA SilentlyContinue -Verbose
} else {
   Remove-Item -LiteralPath "$.\blah" -Force -recurse -EA SilentlyContinue
}

The few things I've tried give some awful errors. How does one go about something like the following

Remove-Item -LiteralPath "$.\blah" -Force -recurse -EA SilentlyContinue $verbose

There is a possibility this is a duplicate, but I don't know what I'm searching for.

Edit: Looking through the suggested duplicate Passing through -Verbose status to module cmdlets

I don't think its a duplicate as it show how to check in a script / module if -Verbose was passed.

I'm specifically looking for a way to pass -Verbose based on a bool (or what was passed into my script) to existing commands.

Based on this code, which is my best understanding of how to capture the above link 'Passing through -Verbose' I cant pass off the verbose state to Remove-Item

[CmdletBinding()]
PARAM()
    
$TempFile = New-TemporaryFile
Remove-Item $TempFile
1

There are 1 answers

0
Gauthier On

This can be solved in 2 ways.
Ether grabbing what is passed into the script,
or having your own local boolean defined in the script.

# these are needed to bind to whats passed to this script/function
# .\your_script.ps1 -Versbose
[CmdletBinding()]
PARAM()
    
$TempFile = New-TemporaryFile

# $VerbosePreference is the magic variable set with CmdletBinding & PARAM

# then you have to pass the value to the -Verbose boolean (i havent seen this in any documentation, but im new
Remove-Item $TempFile -Verbose:$VerbosePreference