Archdeacon
Archdeacon

Reputation: 213

PowerShell VB.NET cmdlet. Change -DEBUG switch

The trying to prevent the (apparently default) Inquire mode in WriteDebug and this does not work (See earlier post). As I do not yet know how to detect if -DEBUG is set on the command line I am trying this:

(<Cmdlet(VerbsDiagnostic.Test, "MyCmdlet", SupportsShouldProcess:=False)> _

Protected Overrides Sub BeginProcessing()          
  setting = SessionState.PSVariable                                    
  dbPref = setting.Get("DebugPreference").Value
  vbPref = setting.Get("VerbosePreference").Value
  WriteObject("VBpref: " & vbPref.ToString)
  WriteObject("DBpref: " & dbPref.ToString)
  setting.Set("VerbosePreference", ActionPreference.Continue)
  setting.Set("DebugPreference", ActionPreference.Continue)
  dbPref = setting.Get("DebugPreference").Value
  vbPref = setting.Get("VerbosePreference").Value
  WriteObject("VBpref: " & vbPref.ToString)
  WriteObject("DBpref: " & dbPref.ToString)
  WriteDebug("TEST")

The ouput is as follows:

PS> Test-MyCmdlet -d
VBpref: SilentlyContinue
DBpref: SilentlyContinue
VBpref: Continue
DBpref: Continue
DEBUG: TEST

Confirm
Continue with this operation?
[Y] Yes  [A] Yes to All  [H] Halt Command  [S] Suspend  [?] Help
(default is "Y"):

And this is the output without the -D switch (no Inquire):

PS> Test-MyCmdlet
VBpref: SilentlyContinue
DBpref: SilentlyContinue
VBpref: Continue
DBpref: Continue
DEBUG: TEST

So why, if the reset above has worked, am I still in Inquire mode? And how can I change it?

Upvotes: 1

Views: 214

Answers (2)

Lars Truijens
Lars Truijens

Reputation: 43595

The default of $DebugPreference is not Inquire, but SilentContinue as you can read here. And your own output proves it.

Properly detecting why WriteDebug knows when to write is explained here.

The reason WriteDebug still asks questions is because you called your cmdlet with -Debug. I don't see why setting $DebugPreference would change that. I also see no way of changing the -Debug parameter while your cmdlet is executing.

I doubt that really is what you want and if it is I do not understand why. Maybe we can help you better if you explain why you would want to.

Upvotes: 0

Frode F.
Frode F.

Reputation: 54881

public PSVariableIntrinsics PSVariable { get; }

Source: MSDN

I'm not developer, but I guess that means that any changes you do to you settings will not be applied to the users session, but only in the local copyin you stored in your variable.

As for detecting the debug-setting, you could try something like this which is from an earlier SO-answer:

bool debug = MyInvocation.BoundParameters.ContainsKey("Debug") &&
             ((SwitchParameter)MyInvocation.BoundParameters["Debug"]).ToBool();

Upvotes: 1

Related Questions