Reputation: 1932
How can I pass an array from C# to PowerShell that can be foreach
ed?
Right now I have this script:
[Cmdlet(VerbsCommon.Get, "Numbers")]
public class GetNumbersCmdlet: Cmdlet
{
protected override void BeginProcessing()
{
var list = new List<string>();
list.Add("1");
list.Add("2");
list.Add("3");
list.Add("4");
list.Add("5");
WriteObject(results.ToArray());
}
}
And this PowerShell script:
foreach ($number in Get-Numbers) {
Write-Output "Output is $number"
}
Instead of:
Output is 1
Output is 2
Output is 3
Output is 4
Output is 5
I would get:
Output is 1 2 3 4 5
Upvotes: 1
Views: 474
Reputation: 22122
PowerShell do not automatically enumerate output of commands. That means if command write collection into pipeline, then that collection will be passed to the next command as single object.
WriteObject
also do not enumerate objects unless explicitly asked.
So to solve your problem, you can write objects as you go instead of collecting them:
[Cmdlet(VerbsCommon.Get, "Numbers")]
public class GetNumbersCmdlet: Cmdlet
{
protected override void BeginProcessing()
{
WriteObject("1");
WriteObject("2");
WriteObject("3");
WriteObject("4");
WriteObject("5");
}
}
Or you can ask WriteObject
to enumerate your collection:
[Cmdlet(VerbsCommon.Get, "Numbers")]
public class GetNumbersCmdlet: Cmdlet
{
protected override void BeginProcessing()
{
var list = new List<string>();
list.Add("1");
list.Add("2");
list.Add("3");
list.Add("4");
list.Add("5");
WriteObject(results, true);
}
}
Note that in both cases you are not writing array anymore, but individual items of it.
Upvotes: 1