Question

Simple case, trying to code a cmdlet that will prompt the user to confirm their action. This means I have to put ShouldProcess in the ProcessRecord method call, but it always returns true no matter what (without prompting). Here's a simple case:

using System;
using System.Management.Automation;

[Cmdlet(VerbsDiagnostic.Test, "ShouldProcess",
    SupportsShouldProcess = true)]
public class TestShouldProcessCommand : Cmdlet
{
    [Parameter(Position = 0,
        ParameterSetName = "Force")]
    public SwitchParameter Force;

    protected override void ProcessRecord()
    {
        if (ShouldProcess("ShouldProcess Target"))
        {
            if (Force || ShouldContinue("ShouldContinue Query", 
                "ShouldContinue Caption"))
            {
                WriteObject("Hello");
            }
            else
            {
                ThrowTerminatingError(new ErrorRecord(new Exception(
                    "Error Message"), "Error ID", 
                    ErrorCategory.InvalidData, "Target Object"));
            }
        }
    }
}

When you load up PowerShell and try to run it (after importing the dll using Import-Module) all you get is this:

PS C:\Users\user> Test-ShouldProcess

ShouldContinue Caption
ShouldContinue Query
[Y] Yes  [N] No  [S] Suspend  [?] Help (default is "Y"): Y
Hello

This is the expected output for ShouldContinue, but nothing happens for the ShouldProcess call that comes first. If you just have it print out the return value of the ShouldProcess call, it's always true no matter how I use it. Tested in PowerShell 2 and 3, and on a vanilla machine. Using Visual Studio 2010 Pro.

Was it helpful?

Solution

Try executing the cmdlet with the common parameter -WhatIf. That should cause ShouldProcess() to return false. The idea is to show what the cmdlet would do without actually doing it when -WhatIf is used. So you would want a more descriptive message in the ShouldProcess() call to indicate which pipeline object you're working on (assuming you support pipeline binding).

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top