【问题标题】:How to create powershell cmdlet (C#) output parameters如何创建 powershell cmdlet (C#) 输出参数
【发布时间】:2020-02-11 11:38:59
【问题描述】:

常用参数有几个例子,如ErrorVariable、InformationVariable;

get-item foad: -ev foo
$foo

"get-item" 将创建 $foo 的值并将其设置为 ErrorRecord 的实例。 如何创建自己的参数来做类似的事情?

基本上,我正在创建一个使用 WriteObject() 将数据写入管道的 cmdlet,但是我还希望允许用户访问一些附加信息 - 基本上是带外数据 - 这不是管道的一部分。

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);
    }
}

【问题讨论】:

    标签: c# powershell


    【解决方案1】:

    您希望设置 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-MyStuff
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2020-02-27
      • 2010-12-05
      • 1970-01-01
      • 2016-01-10
      • 1970-01-01
      • 1970-01-01
      • 2020-10-12
      相关资源
      最近更新 更多