Powershell中奇怪的命令行行为

时间:2012-09-06 09:02:31

标签: powershell command-line command-line-arguments

考虑以下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:\>

正如预期的那样

看起来命令行中的<将每行的行写入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驱动器上,并使用相同的命令调用它,使用带有 NO 换行符的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:\>

有人可以帮我这个吗? (对不起,很长的帖子)。

1 个答案:

答案 0 :(得分:1)

如果您省略“&lt;”,它会起作用I / O重定向。

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