3

次の PowerShell スクリプトを検討してください。

Write-Host "Foo"

if($true)
{
    Write-Host "Bar"
    throw ("the matrix has a bug")
}

c:\test.ps1 に保存されたファイル

これは、結果を伴う cmd ウィンドウでの呼び出しです。

C:\>powershell.exe -NonInteractive -Command - <c:\test.ps1
Foo

C:\>

}ただし、結果の後に 2 つの改行を追加すると、期待どおりになります。

Write-Host "Foo"

if($true)
{
    Write-Host "Bar"
    throw ("the matrix has a bug")
}
<linebreak here>
<linebreak here>

同じ呼び出しで、結果は次のとおりです。

C:\>powershell.exe -NonInteractive -Command - <c:\test.ps1
Foo
Bar
the matrix has a bug
At line:4 char:7
+     throw <<<<  ("the matrix has a bug")
    + CategoryInfo          : OperationStopped: (the matrix has a bug:String)
   [], RuntimeException
    + FullyQualifiedErrorId : the matrix has a bug


C:\>

予想通り

コマンドラインの the<は、1行ごとにpowershellのコンソールに書き込むようです。CMD がすべての行を読み取るわけではないのではないかと考えましたが、コンソールを読み取って出力する小さな C# アプリを作成し、行を問題なく読み取ることができました。

これは C# コードです。

using System;

namespace PrintArgs
{
    internal class Program
    {
        private static void Main(string[] args)
        {
            foreach (string arg in args)
            {
                Console.WriteLine("----- ARG start");
                Console.WriteLine(arg);
                Console.WriteLine("----- ARG stop");
            }


            string line;
            do
            {
                line = Console.ReadLine();
                if (line != null)
                {
                    Console.WriteLine(line);
                }
            }
            while (line != null);
        }
    }
}

これを呼び出すと (つまり、基本的に PrintArgs.exe を C ドライブに置き、改行なしで test.ps1 を使用して同じコマンドで呼び出す) 、次の結果が得られます。

C:\>printargs.exe -NonInteractive -Command - <c:\test.ps1
----- ARG start
-NonInteractive
----- ARG stop
----- ARG start
-Command
----- ARG stop
----- ARG start
-
----- ARG stop
Write-Host "Foo"

if($true)
{
        Write-Host "Bar"
        throw ("the matrix has a bug")
}

C:\>

誰かがこれについて私を助けることができますか? (長い投稿で申し訳ありません)。

4

1 に答える 1

1

「<」I/Oリダイレクトを省略している場合は機能します。

C:\>powershell.exe -NonInteractive c:\test.ps1
于 2012-09-06T11:53:11.857 に答える