【问题标题】:PowerShell string concatenation gives newlinesPowerShell 字符串连接提供换行符
【发布时间】:2012-08-25 09:01:47
【问题描述】:

注意:Java/Closure Compiler 的实际错误来自 --js-outputfile 中缺少的t

我有这个 PowerShell 脚本:

cls
$jsFiles = @();

Get-ChildItem | Where {$_.PsIsContainer} | Foreach {
    $dir = $_.FullName;
    $jsFile = $dir + "\" + $_.Name + ".js";
    if (Test-Path ($jsFile)) {
        $jsFiles += $jsFile;
    }
}

$wd = [System.IO.Directory]::GetCurrentDirectory();

# Build Closure Compiler command line call
$cmd = @("-jar $wd\..\ClosureCompiler\compiler.jar");

Foreach ($file in $jsFiles) {
    # Both insert a newline!

    $cmd += "--js $file";
    #$cmd = "$cmd --js $file";
}


$cmd = "$cmd --js_ouput_file $wd\all.js";

Invoke-Expression "java.exe $cmd"

问题是每个+=$cmd = "$cmd str" 调用都会插入换行符!

Echoargs 给了我这个输出:

Arg 0 is <-jar>
Arg 1 is <S:\ome\Path\compiler.jar>
Arg 2 is <--js>
Arg 3 is <S:\ome\Path\script1.js>
Arg 4 is <--js>
Arg 5 is <S:\ome\Path\script2.js>
...
Arg 98 is <--js_ouput_file>
Arg 99 is <S:\ome\Path\all.js>

(可能)因此,我从java.exe 收到一些错误:

java.exe : "--js_ouput_file" is not a valid option
At line:1 char:1
+ java.exe -jar ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : NotSpecified: ("--js_ouput_file" is not a valid option:String) [], RemoteException
    + FullyQualifiedErrorId : NativeCommandError

【问题讨论】:

    标签: string powershell jar newline


    【解决方案1】:

    尝试改写成更简单的版本:

    cls
    
    $wd = [System.IO.Directory]::GetCurrentDirectory();
    
    # Build Closure Compiler command line call
    $cmd = "-jar $wd\..\ClosureCompiler\compiler.jar";
    
    $arrayOfJs = Get-ChildItem -Recurse -Include "*.js" | % { "--js $_.FullName" };
    
    $cmd += [string]::Join(" ", $arrayOfJs);
    
    Invoke-Expression "java $cmd --js_ouput_file $wd\all.js"
    

    【讨论】:

    • 感谢您的回答(以及代码缩减!)。但是我仍然遇到错误。请查看我的问题(一开始忘记包含错误消息)。
    • 我刚刚用 Echoargs 测试了它,但仍然有相同的换行符。
    • 同样的错误 :( 但是正如 manojlds 提到的,我没有(想要)将 $cmd 用作数组。我只是在某处误解了数组运算符......
    • 我有更新脚本,$cmd 不是数组。加入数组操作使用$arrayOfJs
    • 感谢您的帮助,但换行符仍然存在。
    【解决方案2】:

    当你这样做时

    $cmd = @(...);
    

    您正在创建一个数组,因此其上的后续+= 将元素附加到数组而不是字符串连接。只需将其作为字符串,或在使用 $cmd 之前。执行以下操作:

    $cmd -join " "
    

    这会将元素连接成一个以空格分隔的字符串。默认情况下,当数组被强制转换为字符串时,您会在元素之间看到新的行。

    【讨论】:

    • 好的,我已将其更改为$cmd = " -jar..."。但我仍然得到所有的换行符!
    • 您的答案都没有解决方案(这是 --js-ouputfie 中缺少的 t),但 akim 还缩短了我的代码。谢谢你们!
    最近更新 更多