Neko Musume's helpful answer 为您的当前问题提供解决方案。
但是,值得退一步:
要同步执行控制台应用程序或批处理文件,请直接调用它们(ng build ... 或& ng build ...),不要不要使用Start-Process strong> - 请参阅 this answer 和 this GitHub docs issue 详细说明适当与不适当的用例,并请求将指导添加到 Start-Process 帮助主题。
因此:
# Execute ng synchronously, with its output streams connected to PowerShell's
ng build --prod D:\pathToAngularProject
至于你尝试了什么:
添加到 Neko 的答案:
您的第一个命令起作用的原因如下:
Start-Process -FilePath ng build ...
相当于:
Start-Process -FilePath -FilePath ng -ArgumentList build ...
也就是说,build 参数被位置绑定,无需显式命名其目标参数-ArgumentList。
利用这一点,并且 -FilePath 隐含在 first 位置参数中,您的问题的直接解决方案可以简化为:
# The 1st positional argument, 'ng', binds to -FilePath
# The 2nd positional argument, the *array* of arguments to pass to 'ng',
# 'build' and '--prod', binds to -ArgumentList
Start-Process ng build, --prod ...
也就是说,Start-Process 有一个长期存在的错误,导致它错误地传递带有嵌入空格的参数 - 请参阅@987654325 @。
为保持向后兼容性,此错误可能不会得到修复(introducing a new parameter 可能除外)。
因此最好将参数作为单个数组元素传递,有效地作为命令行(没有可执行文件),其中如有必要,可以使用嵌入的"..." 引用正确地表示参数之间的边界:
# Pass the arguments for 'ng' *as a single string*, potentially
# with embedded "..." quoting (not needed here).
Start-Process ng 'build --prod' ...
嵌入引用的示例:
# Project path needs embedded "..." quoting, because it contains spaces.
Start-Process ng 'build --prod "D:\Work Projects\Foo"' ...
使用expandable (double-quoted) string ("...") 来嵌入变量/子表达式的值的示例(嵌入 " 字符。然后必须将其转义为`"(或"") ):
$projDir = 'D:\Work Projects'
Start-Process ng "build --prod `"$projDir\Foo`"" ...
关于引用数组元素的一般说明:
由于PowerShell中的command arguments是使用所谓的argument(解析)模式(类shell)解析的,所以(隐含)的(字符串)元素-ArgumentList不一般需要引用。
也就是说,参数模式中的数组build, --prod等价于表达式模式中的'build', '--prod'(类似于编程语言)。
有关 PowerShell 解析模式的概述,请参阅 this answer。
但是,您也可以在参数模式中使用带引号的形式,并且 - 根据元素值 - 您可能必须引用,例如当元素包含空格或其他 shell 元字符时;此外,如果 first 元素看起来像 PowerShell 参数名称(例如,-prod 而不是 --prod),它也必须被引用。
几个示例:
注意:为简单起见,示例中使用了Write-Output,它只是在自己的行中回显每个数组元素。传递给 any cmdlet 的数组以 参数模式 进行解析。
# No quoting needed.
# Elements contain no PowerShell metacharacters.
Write-Output one, two
# Quoting needed for the 2nd array element, due to containing
# PowerShell metacharacters (space, parentheses)
Write-Output one, 'two (2)'
# Quoting needed for the 1st array element, because it looks
# like a PowerShell parameter name.
# (Of course, you may choose to quote *both* elements in this case,
# for consistency).
Write-Output '-one', two
# If the parameter-like argument isn't the *first* array element,
# the need for quoting goes away
Write-Output one, -two