[英]Custom PowerShell cmdlet with a ScriptBlock in a hashtable
I have a custom Powershell Cmdlet in C#, all works fine. 我在C#中有一个自定义Powershell Cmdlet,一切正常。
The one parameter is a HashTable
. 一个参数是HashTable
。 How can I use a ScriptBlock
in that parameter? 如何在该参数中使用ScriptBlock
? When I set the parameter to @{file={$_.Identity}}
, I want to get a pipeline object with Identity
property in the ProcessRecord
method. 当我将参数设置为@{file={$_.Identity}}
,我想在ProcessRecord
方法中获取具有Identity
属性的管道对象。 How can I do that? 我怎样才能做到这一点?
Now I simple convert the keys/values of the hash table to Dictionary<string, string>
, but I want to get a pipelined object property (string). 现在,我简单地将哈希表的键/值转换为Dictionary<string, string>
,但是我想获得一个流水线对象属性(string)。
Now I get an error that ScriptBlock
can't convert to string. 现在,我收到一个错误,表明ScriptBlock
无法转换为字符串。
You could use ForEach-Object
for this: 您可以为此使用ForEach-Object
:
function Invoke-WithUnderScore {
param(
[Parameter(ValueFromPipeline)]
[object[]]$InputObject,
[scriptblock]$Property
)
process {
$InputObject |ForEach-Object $Property
}
}
Then use like: 然后使用像:
PS C:\> "Hello","World!","This is a longer string" |Invoke-WithUnderscore -Property {$_.Length}
5
6
23
Or in a C# cmdlet: 或在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
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.