Implementing -WhatIf in to a custom function

This topic contains 2 replies, has 3 voices, and was last updated by  Don Jones 1 month, 1 week ago.

  • Author
    Posts
  • #89201

    John Steele
    Participant

    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
    }
    
  • #89206

    Shihan Pietersz
    Participant

    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

  • #89228

    Don Jones
    Keymaster

    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.

You must be logged in to reply to this topic.