Implementing -WhatIf in to a custom function

Welcome Forums General PowerShell Q&A Implementing -WhatIf in to a custom function

This topic contains 2 replies, has 3 voices, and was last updated by

1 year ago.

  • Author
  • #89201

    Points: 23
    Rank: Member

    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 {
        param (
            [string] $Name
        $latestModule = Get-InstalledModule $Name
        $oldModules = Get-InstalledModule $Name -AllVersions | Where-Object {$_.Version -ne $latestModule.Version}
        Uninstall-Module -InputObject $oldModules
  • #89206

    Points: 1
    Rank: Member

    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


  • #89228

    Points: 1,704
    Helping HandTeam Member
    Rank: Community Hero

    You need


    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.

The topic ‘Implementing -WhatIf in to a custom function’ is closed to new replies.