使用 c# 中的文字和代码块与 powershell 2.0 交互时出现问题

发布于 2024-12-06 16:22:10 字数 725 浏览 2 评论 0原文

如果我尝试通过 c# 运行 Powershell 命令,则会收到以下错误: “术语‘select’未被识别为 cmdlet、函数、脚本文件或可操作程序的名称。请检查名称的拼写,或者如果包含路径,请验证该路径是否正确是正确的,然后再试一次。”

如果直接使用 Powershell(.exe) 执行命令,一切正常!

我尝试运行的命令看起来像 ig: “Get-Mailbox -Organization 'CoolOrganizationNameGoesHere' | select ServerName

看来“管道”有问题|, 我浪费了很多时间在主要搜索引擎上使用最疯狂的关键字组合进行搜索, 但我没有发现任何有效的方法。

我尝试的最后一件事是为Powershell设置已发布的IIS-ApplicationPSLanguageMode属性,结果仍然与之前编写的相同。

也许 WinRM 配置错误?或者我的本地 Powershell 配置已损坏? 是否有关于使用 Powershell 进行远程访问的 C#(或任何其他 .Net 语言)的编写良好的文档 并使用管道| “命令”?

谁能告诉我出了什么问题,这就像大海捞针一样!

谢谢!

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 published 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!

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

夜雨飘雪 2024-12-13 16:22:10

技巧可能在于您创建命令的方式。如果您将脚本作为字符串运行,则应该使用:

Command myCommand = new Command(script, true);

但如果您想将其作为文件名运行 - 您应该使用:

Command myCommand = new Command(script, false);

所以:

Command myCommand = new Command("Get-Date", true);
Command myCommand = new Command("c:\test.ps1", false);

如果您需要完整的方法:

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;
}

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;
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文