使用命令行参数,您不能将数组这样传递给外部程序,例如node,通过其CLI,因为没有内置这样的构造。
有两种解决方法:
(a)的简单演示:
# Construct a PowerShell array and pass its elements as individual
# arguments to an ad-hoc Node.js script:
PS> $arr = 'one', 'two'; node -pe 'process.argv.slice(1)' $arr
[ 'one', 'two' ]
注意:如果你传递一个脚本的路径文件,使用2而不是1作为偏移量,因为argv的元素1是那么脚本的路径。
请注意简单地传递 PowerShell $arr 是如何使 PowerShell 将其元素作为单独的参数传递的。
(b)的简单演示:
# Pass the array as a single string containing the space-separated
# elements, and convert that string to an array in JavaScript.
PS> $arr = 'one', 'two'; node -pe 'process.argv[1].split(/ /)' "$arr"
[ 'one', 'two' ]
如果您需要支持带有嵌入空格的数组元素,甚至可能需要字符串以外的数据类型,则需要一种更复杂的方法。
正如Lee Dailey 建议的那样,您可以使用 JSON:
# Construct a PowerShell array and pass it as a single argument
# in JSON form, which JavaScript can easily parse:
PS> $arr = 'one', 2; node -pe 'JSON.parse(process.argv[1])' (ConvertTo-Json $arr).Replace('"', '\"')
[ 'one', 2 ] # Note that the numeric element was preserved as such.
请注意,不幸的是需要在ConvertTo-Json 的输出上调用.Replace('"', '\"'),以便手动\-转义" 字符。在 JSON 文本中,应该没有必要,但从 PowerShell Core 7.1 开始,仍然是由于 PowerShell 将参数传递给外部程序的问题 - 请参阅 this answer。
如果您通过管道传递 JSON 文本,您可以避免逃避问题,Node.js 脚本可以通过 标准输入:
# Construct a PowerShell array, convert it to JSON, and send it
# via the *pipeline* to the Node.js script.
# NOTE: On *Windows PowerShell*, run
# $OutputEncoding = [Text.Utf8Encoding]::new($false)
# first, to ensure that non-ASCII characters are properly encoded.
# PowerShell [Core] v6+ already defaults to BOM-less UTF-8.
$arr = 'one', 2
ConvertTo-Json $arr |
node -pe "JSON.parse(require('fs').readFileSync(0).toString())"
结果同上。
(请注意,Node.js 命令参数(传递给 -pe 的字符串)也容易出现转义问题,在这种情况下,通过使用 "..." 作为外部引用和 '...' 作为内部引用,因为 ' 字符。不需要转义)。