【问题标题】:Weird command line behavior in PowershellPowershell 中奇怪的命令行行为
【发布时间】:2012-08-31 01:32:21
【问题描述】:

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

如预期的那样

似乎命令行中的&lt; 将每行写入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:\>

有人可以帮我解决这个问题吗? (抱歉,帖子太长了)。

【问题讨论】:

  • 我也遇到了这个问题。很奇怪,很想知道为什么。 @Snake:我不确定您的 c# 测试应用程序的来源是否特别相关;我认为这会影响手头的问题。

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


【解决方案1】:

如果您省略了“

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

【讨论】:

    猜你喜欢
    • 2012-04-05
    • 2015-03-28
    • 1970-01-01
    • 2012-06-21
    • 2022-01-05
    • 2015-12-07
    • 2015-01-11
    • 2012-10-22
    • 2019-01-18
    相关资源
    最近更新 更多