在前面博客中的Cmdlet中添加两个变量:
[Cmdlet(VerbsCommon.Get, "AddTwo")]
public class GetProduct : PSCmdlet
{
private static int numOfExecution1 = 0;
private int numOfExecution2 = 0;
private int num1 = 0;
private int num2 = 0;
[Parameter(Mandatory = true, Position = 1, ValueFromPipelineByPropertyName = true)]
public int Num1
{
get { return num1; }
set { num1 = value; }
}
[Parameter(Mandatory = true, Position = 2, ValueFromPipelineByPropertyName = true)]
public int Num2
{
get { return num2; }
set { num2 = value; }
}
protected override void ProcessRecord()
{
int result = Num1 + Num2;
WriteObject(result);
numOfExecution1++;
WriteObject(numOfExecution1);
numOfExecution2++;
WriteObject(numOfExecution2);
}
}
如果连续执行AddTwo四次,将得到如下结果:
PS C:\Users\harryh\Documents\visual studio 2012\Projects\TestCmdlet\Cmdlet2\bin\Debug> AddTwo 3 7
10
1
1
PS C:\Users\harryh\Documents\visual studio 2012\Projects\TestCmdlet\Cmdlet2\bin\Debug> AddTwo 3 7
10
2
1
PS C:\Users\harryh\Documents\visual studio 2012\Projects\TestCmdlet\Cmdlet2\bin\Debug> AddTwo 3 7
10
3
1
PS C:\Users\harryh\Documents\visual studio 2012\Projects\TestCmdlet\Cmdlet2\bin\Debug> AddTwo 3 7
10
4
1
我们注意到static变量numOfExecution1的状态在多次执行命令时得以保存,但非static变量numOfExecution2没有。