Implementing -WhatIf in to a custom function

I’ve created a function to remove old installed modules and have added SupportsShouldProcess to cmdletbinding. From my understanding the -WhatIf switch should be passed down to any native cmdlet that already supports -WhatIf with no need to add $PSCmdlet.ShouldProcess(). Uninstall-Module supports -WhatIf but when i run the below function with -WhatIf it still uninstalls the old modules. What gives?

Function Remove-OldModule {

    [cmdletbinding(SupportsShouldProcess=$true)]
    param (
    
        [parameter()]
        [string] $Name
    )

    $latestModule = Get-InstalledModule $Name
    $oldModules = Get-InstalledModule $Name -AllVersions | Where-Object {$_.Version -ne $latestModule.Version}

    Uninstall-Module -InputObject $oldModules
}

Hi John,
I believe you still need to tell the shell that your function supports both -confirm and -whatif. The way you actually implement that support is to write conditional code around whatever dangerous stuff your cmdlet is planning to do

if ($pscmdlet.ShouldProcess($Name)) {
   $latestModule = Get-InstalledModule $Name
    $oldModules = Get-InstalledModule $Name -AllVersions | Where-Object {$_.Version -ne $latestModule.Version}

    Uninstall-Module -InputObject $oldModule
}

-not tested

Advanced Functions Part 2: ShouldProcess() in Your Script Cmdlets

Regards
Shihan

You need

[CmdletBinding(SupportsShouldProcess=$True,ConfirmImpact=High)]

You need to specify the confirm impact. And, while -most- commands that support -whatif will “inherit” it, you may in some cases need to implement ShouldProcess() as indicated in the previous reply.