You could use parameter sets to ensure that the user is only able to specify one of -Text
, -File
, or -Dir
in conjunction with -Argument
. You should then make your switches (and argument) mandatory rather than optional. This would mean your ProcessRecord
method would know that a switch has been specified and that an argument has been provided. Therefore, you could remove your usage output, which will be available via Powershell's built-in Get-Help
cmdlet.
PowerShell custom Cmdlet using SwitchParameter
-
14-04-2022 - |
Question
I have the following code, where I try to create a custom Cmdlet for PowerShell using C#. What I want to do with my custom cmdlet is that, user should call it with two parameters, from which first one should be -Text or -File or -Dir, and the next one should be a value, a string which specifies the value for text, or file, or directory. It works fine as long as I can see. But I'm just curious whether there is another simple method or more elegant method that I can use to achieve what I want. Or is my solution the simplest that it can get? By the way, SHA256Text, SHA256File, and SHA256Directory, are just custom functions that I have written, so don't worry about 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
{
get { return text; }
set { text = value; }
}
[Parameter(Mandatory = true, Position = 0, ParameterSetName = "File")]
public SwitchParameter File
{
get { return file; }
set { file = value; }
}
[Parameter(Mandatory = true, Position = 0, ParameterSetName = "Directory")]
public SwitchParameter Dir
{
get { return directory; }
set { directory = value; }
}
[Parameter(Mandatory = true, Position = 1)]
[ValidateNotNullOrEmpty]
public string Argument
{
get { 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
}
}
Solution
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow