Just checking if the -Debug flag is set can be done with the code below, but it is not enough.
bool debug = false;
bool containsDebug = MyInvocation.BoundParameters.ContainsKey("Debug");
if (containsDebug)
debug = ((SwitchParameter)MyInvocation.BoundParameters["Debug"]).ToBool();
PowerShell also allows you to set a global flag called $DebugPreference which the code above does not check. And calling a cmdlet from another cmdlet inherits these common parameters which is not inherited through the Debug flag as the code above checks. The code below will check $DebugPreference and solves those problems.
debug = (ActionPreference)GetVariableValue("DebugPreference") != ActionPreference.SilentlyContinue;
Unfortunately in contrary to a cmdlet in PowerShell you have to check both. So the final C# code is as below. I have also added the code for the Verbose common parameter as bonus. Be sure to inherit from PSCmdlet instead of Cmdlet to get to the GetVariableValue method.
bool debug = false;
bool containsDebug = MyInvocation.BoundParameters.ContainsKey("Debug");
if (containsDebug)
debug = ((SwitchParameter)MyInvocation.BoundParameters["Debug"]).ToBool();
else
debug = (ActionPreference)GetVariableValue("DebugPreference") != ActionPreference.SilentlyContinue;
bool verbose = false;
bool containsVerbose = MyInvocation.BoundParameters.ContainsKey("Verbose");
if (containsVerbose)
verbose = ((SwitchParameter)MyInvocation.BoundParameters["Verbose"]).ToBool();
else
verbose = (ActionPreference)GetVariableValue("VerbosePreference") != ActionPreference.SilentlyContinue;