public class PSDefaultVariablizer
public PSDefaultVariablizer(string _variableName, PSCmdlet _cmdlet)
: this(_variableName, null, _cmdlet) { }
public PSDefaultVariablizer(string _variableName, T _innerValue, PSCmdlet _cmdlet)
{
variableName = _variableName;
innerValue = _innerValue;
cmdlet = _cmdlet;
}
public T Value
{
get
{
if(innerValue != null)
{
return innerValue;
}
else
{
return (T)cmdlet.SessionState.PSVariable.GetValue(variableName, null);
}
}
set
{
innerValue = value;
}
}
}
Here is the use case for the class. You have a parameter that a user can input, otherwise it attempts to use a value of a variable in the same scope (think how $ErrorActionPreference works). This class allows you to very simply reuse that functionality.
[Cmdlet("Some", "Command")]
public class SomeCommand : PSCmdlet
{
private PSDefaultVariablizer<string> someParam;
public SomeCommand ()
{
someParam = new PSDefaultVariablizer<string>("SomeParam", this);
}
[Parameter()]
public string SomeParam
{
get
{
return someParam.Value;
}
set
{
someParam.Value = value;
}
}
}
And you would use it from Powershell with the following.
Some-Command -SomeParam 'hello'
#or
$SomeParam = 'hello'
Some-Command
Pretty simple really. I just posted it because I thought the name was hilarious, but I didn’t really know what else to call it.
Let me know if anyone knows of an easier way to this. Unfortunately, there aren’t too many people I can talk to about SnapIn development :)