Mlanda T
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:
The error I get is: Script block literals are not allowed in restricted language mode or a Data section.
Get-Mailbox -ResultSize Unlimited | Select-Object DisplayName,Alias,Database,ServerName,PrimarySmtpAddress, @{Name=""EmailAddresses"";Expression={$_.EmailAddresses |Where-Object {$_.PrefixString -ceq ""smtp""} | ForEach-Object {$_.SmtpAddress}}}
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.
ASKER
Michael, thanks for you input :) I am using the code below (I have only included the relevant snippet):
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#.
//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;
What's interesting is that the call to command.AddScript("Invoke-ASKER CERTIFIED SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Have you tries using ProcessStart
http://www.dotnetperls.com/process
https://msdn.microsoft.com/en-us/library/system.diagnostics.process.start(v=vs.110).aspx
Another option would be to use the Powershell class
https://msdn.microsoft.com/en-us/library/system.management.automation.powershell(v=vs.85).aspx
http://blogs.msdn.com/b/kebab/archive/2014/04/28/executing-powershell-scripts-from-c.aspx