我在C#中有一个定制的Powershell Cmdlet,一切都很好。
其中一个参数是HashTable。如何在该参数中使用ScriptBlock?当我将参数设置为@{file={$_.Identity}}时,我希望在ProcessRecord方法中获得一个具有Identity属性的管道对象。我怎么能这么做?
现在,我简单地将哈希表的键/值转换为Dictionary<string, string>,但我希望获得一个管道对象属性(string)。
现在,我得到了一个ScriptBlock无法转换为字符串的错误。
发布于 2019-03-05 10:33:16
为此,您可以使用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
}
}https://stackoverflow.com/questions/54985556
复制相似问题