A couple of days ago, I had a random post about _PSDefaultVariablizer _because I thought the name was funny. Well, I did some pretty hardcore refactoring of the class, and am pretty happy with the outcome. Overall, I think it is 100x better. Check it out.
public class PSDefaultVariablizer<t> where T: class
{
T innerValue;
IList<func<t>> defaultValues;
public PSDefaultVariablizer(params Func<t>[] _defaultValues)
{
defaultValues = _defaultValues.ToList();
defaultValues.Insert(0, () => this.innerValue);
}
public T Value
{
get
{
return defaultValues.Select(v => v.Invoke())
.Where(v => v != null)
.FirstOrDefault();
}
set
{
innerValue = value;
}
}
}
//I am using it in a cmdlet similar to this
[Cmdlet("Some", "Command")]
public class SomeCommand : PSCmdlet
{
private PSDefaultVariablizer<string> someParam;
public SomeCommand ()
{
someParam = new PSDefaultVariablizer<string>(() => (string)this.SessionState.PSVariable.GetValue("SomeParam", null));
}
[Parameter()]
public string SomeParam
{
get
{
return someParam.Value;
}
set
{
someParam.Value = value;
}
}
}
Thought it was cool to use Lamba’s to eliminate an entire dependency. I should really call this DefaultVariablizer because it has no dependency to Powershell.