0

我在 C# 中有一个自定义的 Powershell Cmdlet,一切正常。

一个参数是 a HashTable。如何ScriptBlock在该参数中使用 a ?当我将参数设置为 时@{file={$_.Identity}},我想Identity在方法中获取一个具有属性的管道对象ProcessRecord。我怎样才能做到这一点?

现在我简单地将哈希表的键/值转换为Dictionary<string, string>,但我想获得一个流水线对象属性(字符串)。

现在我收到一个ScriptBlock无法转换为字符串的错误。

4

1 回答 1

0

你可以用ForEach-Object这个:

function Invoke-WithUnderScore {
  param(
    [Parameter(ValueFromPipeline)]
    [object[]]$InputObject,
    [scriptblock]$Property
  )

  process {
    $InputObject |ForEach-Object $Property
  }
}

然后像这样使用:

PS C:\> "Hello","World!","This is a longer string" |Invoke-WithUnderscore -Property {$_.Length}
5
6
23

或者在 C# cmdlet 中:

[Cmdlet(VerbsCommon.Select, "Stuff")]
public class SelectStuffCommand : PSCmdlet
{
    [Parameter(Mandatory = true, ValueFromPipeline = true)]
    public object[] InputObject;

    [Parameter()]
    public Hashtable Property;

    private List<string> _files;

    protected override void ProcessRecord()
    {
        string fileValue = string.Empty;
        foreach (var obj in InputObject)
        {
            if (!Property.ContainsKey("file"))
                continue;

            if (Property["file"] is ScriptBlock)
            {
                using (PowerShell ps = PowerShell.Create(InitialSessionState.CreateDefault2()))
                {
                    var result = ps.AddCommand("ForEach-Object").AddParameter("process", Property["file"]).Invoke(new[] { obj });
                    if (result.Count > 0)
                    {
                        fileValue = result[0].ToString();
                    }
                }
            }
            else
            {
                fileValue = Property["file"].ToString();
            }

            _files.Add(fileValue);
        }
    }

    protected override void EndProcessing()
    {
        // process _files
    }
}
于 2019-03-05T10:33:16.593 回答