c# - PowerShell custom Cmdlet using SwitchParameter -
i have following code, try create custom cmdlet powershell using c#. want custom cmdlet that, user should call 2 parameters, first 1 should -text or -file or -dir, , next 1 should value, string specifies value text, or file, or directory. works fine long can see. i'm curious whether there simple method or more elegant method can use achieve want. or solution simplest can get? way, sha256text, sha256file, , sha256directory, custom functions have written, don't worry them.
using system; using system.io; using system.text; using system.security.cryptography; using system.management.automation; namespace pssl { [cmdlet(verbscommon.get, "sha256")] public class getsha256 : pscmdlet { #region members private bool text; private bool file; private bool directory; private string argument; #endregion #region parameters [parameter(mandatory = true, position = 0, parametersetname = "text")] public switchparameter text { { return text; } set { text = value; } } [parameter(mandatory = true, position = 0, parametersetname = "file")] public switchparameter file { { return file; } set { file = value; } } [parameter(mandatory = true, position = 0, parametersetname = "directory")] public switchparameter dir { { return directory; } set { directory = value; } } [parameter(mandatory = true, position = 1)] [validatenotnullorempty] public string argument { { return argument; } set { argument = value; } } #endregion #region override methods protected override void processrecord() { switch(parametersetname) { case "text": sha256text(argument); break; case "file": sha256file(argument); break; case "directory": sha256directory(argument); break; default: throw new argumentexception("error: bad parameter name."); } } #endregion } }
you use parameter sets ensure user able specify 1 of -text
, -file
, or -dir
in conjunction -argument
. should make switches (and argument) mandatory rather optional. mean processrecord
method know switch has been specified , argument has been provided. therefore, remove usage output, available via powershell's built-in get-help
cmdlet.
Comments
Post a Comment