哈希表中带有 ScriptBlock 的自定义 PowerShell cmdlet

Custom PowerShell cmdlet with a ScriptBlock in a hashtable

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

一个参数是HashTable。如何在该参数中使用 ScriptBlock?当我设置参数为@{file={$_.Identity}}时,我想在ProcessRecord方法中得到一个带有Identity属性的管道对象。我该怎么做?

现在我简单地将散列 table 的 keys/values 转换为 Dictionary<string, string>,但我想获得一个管道对象 属性(字符串)。

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

您可以为此使用 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
    }
}