Friday, 15 April 2011

Pass -WhatIf flag to all cmdlets being called in powershell script -


I have a test-spoken script, which I am trying to get the whatif flag for all the CMDlets in the script. In my script, I am calling 3 cmdlets new item, copy-item and new-custom CMDlet. The last one is custom CMDlet I wrote. I have added:

  [cmdletBinding (SupportsShouldProcess = $ this is true)]  

For both test scripts and custom cmdlet. When I run this proof with concept script - two system CMDlets (new item and copy-item) that run in any manner but do not do custom. I had thought that if one supports CMDletts then what the shield process should do if it is running the script what to do then. This is the case for two systems cmdlets but not mine I have read other articles about viewing the call stack and I understand how to see what is set. For this example, I want the CMdlets to use the -whatif flag that was running with the script.

Here the script is running with whatif flag: PSC:> script.ps1 -WhatIf

  [cmdletBinding (SupportsShouldProcess = $ True]] Ultimate () import-module c: \ mycmdlet.dll new item -ItemType item1.txt copiedItem.txt copy-custom file NewItem.txt copy-item test.txt CopiedTest.txt  

Here is the CMDlet code:

 using the  system; Using System.Collections.Generic; Using System.Management.Automation; Using the system. Namespace poc.whatif.Cmdlet {[Cmdlet (VerbsCommon.Copy, "Custom")] Public Square CopyCustom: PSCmdlet {#region paramaters [Parameters (mandatory = true, ValueFromPipelineByPropertyName = true, ValueFromPipeline = true, condition = 0 , HelpMessage = "source file")] public string srcFile {get; Set; } [Parameter {mandatory = true, ValueFromPipelineByPropertyName = true; ValueFromPipeline = true; condition = 0, helpMessage = "target file"}] get public string targetFile { Set; } #endregion Protected Override Zero Start Process () {WriteVerbose ("Copy-Custom Start"); } Protected Override Zero Process Record () {WriteBugs ("Copying files from here"); } Protected Override Zero EndProcessing () {LPWerbos ("end-copy-custom"); }}  

You are missing the attribute. Apart from this, you are also recalling the call to make sure that you will see and also use a Force parameter as well. See

Repeat ProcessRecord for more information.

  Protected Override Zero ProcessRecord (if (ShouldProcess ("target", "action")) {ifContinue ("Do Stuff", "What to do for this object?") ) {WriteVerbose ("Copying from here"); }}}  

No comments:

Post a Comment