Link to home
Start Free TrialLog in
Avatar of Mlanda T
Mlanda TFlag for South Africa

asked on

Implement a PowerShell pipeline with a script parameter in C#

I have a powershell script that I am trying to execute from C#. However, I get an error:
Get-Mailbox -ResultSize Unlimited | Select-Object DisplayName,Alias,Database,ServerName,PrimarySmtpAddress, @{Name=""EmailAddresses"";Expression={$_.EmailAddresses |Where-Object {$_.PrefixString -ceq ""smtp""} | ForEach-Object {$_.SmtpAddress}}}

Open in new window

Just running Get-Mailbox -Resultsize Unlimited works, but I need greater control over the email addresses, hence the script parameter.

The error I get is:  Script block literals are not allowed in restricted language mode or a Data section.
Avatar of Michael Fowler
Michael Fowler
Flag of Australia image

Avatar of Mlanda T

ASKER

Michael, thanks for you input :) I am using the code below (I have only included the relevant snippet):
//After we have done this, we can now do the remote calls that will be executed on the server side as script blocks.
powershell = PowerShell.Create();
command = new PSCommand();
command.AddScript("Invoke-Command -ScriptBlock { Get-Mailbox -ResultSize Unlimited } -Session $ra");
//command.AddScript("Invoke-Command -ScriptBlock { Get-Mailbox -ResultSize Unlimited |Select-Object DisplayName,Alias,Database,ServerName,PrimarySmtpAddress, @{Name=\"EmailAddresses\";Expression={$_.EmailAddresses |Where-Object {$_.PrefixString -ceq \"smtp\"} | ForEach-Object {$_.SmtpAddress}}} } -Session $ra");
powershell.Commands = command;
powershell.Runspace = myRunSpace;

Open in new window

What's interesting is that the call to command.AddScript("Invoke-Command -ScriptBlock { Get-Mailbox -ResultSize Unlimited } -Session $ra"); works and I get results. It's just when I try to execute the more complex PowerShell script which get more refined data back that I get the issues. the EmailAddress column returned by this working version includes multiple SMTP address alternatives and other detail which I do not need. The more complex PowerShell script strips out these other details. The complex PowerShell script works when I run it from PowerShell ISE. I only get issues when I run it from C#, but I am not sure how one constructs that pipeline from C#.
ASKER CERTIFIED SOLUTION
Avatar of Michael Fowler
Michael Fowler
Flag of Australia image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial