在常用参数中有几个例子,如ErrorVariable、InformationVariable;
get-item foad: -ev foo
$foo"get-item“将创建$foo的值并将其设置为ErrorRecord的一个实例。我如何创建自己的参数来做类似的事情?
基本上,我正在创建一个cmdlet,该cmdlet使用WriteObject()将数据写入管道,但我还想提供一些附加信息,允许用户访问--基本上是带外数据--这不是管道的一部分。
C#中的out参数示例:
public class ExampleCode
{
public int GetMyStuff(int param1, out string someVar)
{
someVar = "My out-of-band result";
return param1 + 1;
}
public static void RunMe()
{
ExampleCode ex = new ExampleCode();
string value;
int result = ex.GetMyStuff(41, out value);
Console.WriteLine($"result is {result}, OOB Data is {value}");
}
}我正在寻找如何将"GetMyStuff()“转换为powershell cmdlet。
[Cmdlet(VerbsCommon.Get, "MyStuff")]
public class ExampleCmdLet : PSCmdlet
{
[Parameter(Mandatory = false)] int param1;
[Parameter(Mandatory = false)] string someVar; // How to make this [out] ?
protected override void ProcessRecord()
{
someVar = "My out-of-band result";
WriteObject(param1 + 1);
}
}发布于 2020-02-11 03:38:59
您希望设置一个PowerShell变量,而不是一个.NET变量。
访问PowerShell变量需要通过调用方的会话状态访问它们。
在System.Management.Automation.PSCmdlet-derived cmdlet中,可以通过this.SessionState.PSVariable.Set(<varName>, <value>)设置变量。
# Compile a Get-MyStuff cmdlet and import it into the current session.
Add-Type -TypeDefinition @'
using System.Management.Automation;
[Cmdlet(VerbsCommon.Get, "MyStuff")]
public class ExampleCmdLet : PSCmdlet
{
[Parameter()] public int Param1 { get; set; }
[Parameter()] public string SomeVar { get; set; }
protected override void ProcessRecord()
{
// Assign to the $SomeVar variable in the caller's context.
this.SessionState.PSVariable.Set(SomeVar, 42);
WriteObject(Param1 + 1);
}
}
'@ -PassThru | % Assembly | Import-Module #'
# Call Get-MyStuff and pass the *name* of the
# variable to assign to, "targetVariable", which sets
# $targetVariable:
Get-MyStuff -Param1 666 -SomeVar targetVariable
# Output the value of $targetVariable
$targetVariable上述收益率:
667 # Output from the cmdlet, via WriteObject()
42 # Value of $targetVariable, set by Get-MyStuffhttps://stackoverflow.com/questions/60160338
复制相似问题