0

C#を使用してコマンドを実行しようとするとPowershell、次のエラーが発生します。「「select」という用語はcmdlet、関数、スクリプトファイル、または操作可能なプログラムの名前として認識されません。名前のスペルを確認するか、パスを確認してください。含まれている場合は、パスが正しいことを確認して、再試行してください。」

コマンドが直接実行された場合、Powershell(.exe)すべてが正常に機能します!

私が実行しようとしているコマンドは、igのようになります: "Get-Mailbox -Organization 'CoolOrganizationNameGoesHere'| select ServerName"

「パイプ」に問題があるようです|、最もワイルドなキーワードの組み合わせで主要な検索エンジンを検索するのに何時間も無駄にしていますが、うまくいくものは何も見つかりませんでした。

私が最後に試したのは、の公開のプロパティを設定することPSLanguageModeです。結果は以前と同じです。IIS-ApplicationPowershell

たぶんWinRM間違った設定がありますか?または、ローカルPowershell構成が破損していますか?Powershellリモートアクセスとパイプの使用を使用したC#(またはその他の.Net言語)に関する適切に記述されたドキュメントはありますか?"指図"?

誰かが何が悪いのか教えてもらえますか、それは干し草の山で針を見つけるようなものです!

ありがとう!

4

1 に答える 1

2

コマンドを作成する方法にトリックが含まれている可能性があります。スクリプトを文字列として実行している場合は、次を使用する必要があります。

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;
}
于 2011-11-03T08:57:57.307 に答える