If I try to run a Powershell
Command through c# I get the following error:
"The term 'select' is not recognized as the name of a cmdlet
, function, script file, or operable program. Check the spelling of the name, or if a path was included, verify that the path is correct and try again."
If the Command was executed directly with Powershell(.exe)
all works fine!
The command I try to run looks like i.g:
"Get-Mailbox -Organization 'CoolOrganizationNameGoesHere'
| select ServerName
"
It seems that there is a problem with the "Pipe" |, I have wasted hours on searching at major search engines with the wildest keyword combinations, but I've found nothing that works.
The last thing I have tried is setting the PSLanguageMode
property of the publis开发者_开发问答hed IIS-Application
for Powershell
, The result is still the same as written before.
Maybe there is WinRM
wrong configured? Or my local Powershell
configuration is corrupted?
Is there any well written documentation on C# (or any other .Net language) using Powershell
with remote access
and using the Pipe | "command"?
Can anybody tell me what is wrong, that's like to find the needle in a haystack!
Thanks!
Trick could be in the way you create your command. If you are running script as a string, you should use:
Command myCommand = new Command(script, true);
But if you want to run it as a filename - you should use:
Command myCommand = new Command(script, false);
So:
Command myCommand = new Command("Get-Date", true);
Command myCommand = new Command("c:\test.ps1", false);
In case you need full method:
private static IEnumerable<PSObject> ExecutePowerShellScript(string script, bool isScript = false, IEnumerable<KeyValuePair<string, object>> parameters = null)
{
RunspaceConfiguration runspaceConfiguration = RunspaceConfiguration.Create();
Runspace runspace = RunspaceFactory.CreateRunspace(runspaceConfiguration);
runspace.Open();
Command myCommand = new Command(script, isScript);
if (parameters != null)
{
foreach (var parameter in parameters)
{
myCommand.Parameters.Add(new CommandParameter(parameter.Key, parameter.Value));
}
}
Pipeline pipeline = runspace.CreatePipeline();
pipeline.Commands.Add(myCommand);
var result = pipeline.Invoke();
// Check for errors
if (pipeline.Error.Count > 0)
{
StringBuilder builder = new StringBuilder();
//iterate over Error PipeLine until end
while (!pipeline.Error.EndOfPipeline)
{
//read one PSObject off the pipeline
var value = pipeline.Error.Read() as PSObject;
if (value != null)
{
//get the ErrorRecord
var r = value.BaseObject as ErrorRecord;
if (r != null)
{
//build whatever kind of message your want
builder.AppendLine(r.InvocationInfo.MyCommand.Name + " : " + r.Exception.Message);
builder.AppendLine(r.InvocationInfo.PositionMessage);
builder.AppendLine(string.Format("+ CategoryInfo: {0}", r.CategoryInfo));
builder.AppendLine(string.Format("+ FullyQualifiedErrorId: {0}", r.FullyQualifiedErrorId));
}
}
}
throw new Exception(builder.ToString());
}
return result;
}
精彩评论