powershell 变量替换不起作用

问题描述 投票:0回答:1

抱歉,如果这是一个愚蠢的问题,但我对 ps 还很陌生..

以这种方式运行curl可以正常工作(mailgun发送带有附件的电子邮件):

 curl -s --user 'api:***' `
   https://api.eu.mailgun.net/v3/***.com/messages `
   -F from='Builder <[email protected]>' `
   -F [email protected] `
   -F subject='Build failed!!!' `
   -F text='Your build has been failed.' -F attachment='1.txt'

现在尝试添加变量替换:

 $attstr="-F attachment='1.txt'"
 curl -s --user 'api:***' `
   https://api.eu.mailgun.net/v3/***.com/messages `
   -F from='Builder <[email protected]>' `
   -F [email protected] `
   -F subject='Build failed!!!' `
   -F text='Your build has been failed.' $attstr

看起来变量被忽略(获取不带附件的邮件)

powershell variables curl
1个回答
1
投票

您实际执行的命令是:

curl -s --user api:*** `
    https://api.eu.mailgun.net/v3/***.com/messages
    ... etc... `
    -F text='Your build has been failed.' `
    "-F attachment='1.txt'"

注意

-F attachment='1.txt'
周围的双引号 - 我不知道curl如何解释它,但它将变量内容视为字符串数据而不是命令参数。

如果您希望它们作为参数传递,请尝试

$cmdargs = @("-F", "attachment='1.txt'")

curl -s --user api:*** `
    https://api.eu.mailgun.net/v3/***.com/messages
    ... etc... `
    -F text='Your build has been failed.' `
    $cmdargs

将执行:

curl -s --user api:*** `
    https://api.eu.mailgun.net/v3/***.com/messages
    ... etc... `
    -F text='Your build has been failed.' `
    -F attachment='1.txt'

没有周围的引号。

请注意,诊断此类参数解析问题的一个好方法是下载并调用

echoargs.exe
而不是您的命令(例如
curl
)并查看它在控制台上回显的内容...

PS> $attstr="-F attachment='1.txt'"

PS> c:\src\so\echoargs.exe -s --user 'api:***' `
>>    https://api.eu.mailgun.net/v3/***.com/messages `
>>    -F from='Builder <[email protected]>' `
>>    -F [email protected] `
>>    -F subject='Build failed!!!' `
>>    -F text='Your build has been failed.' `
>>    $attstr
Arg 0 is <-s>
Arg 1 is <--user>
Arg 2 is <api:***>
Arg 3 is <https://api.eu.mailgun.net/v3/***.com/messages>
Arg 4 is <-F>
Arg 5 is <from=Builder <[email protected]>>
Arg 6 is <-F>
Arg 7 is <[email protected]>
Arg 8 is <-F>
Arg 9 is <subject=Build failed!!!>
Arg 10 is <-F>
Arg 11 is <text=Your build has been failed.>
Arg 12 is <-F attachment='1.txt'>

Command line:
"C:\src\so\echoargs.exe" -s --user api:*** https://api.eu.mailgun.net/v3/***.com/messages -F "from=Builder <[email protected]>" -F [email protected] -F "subject=Build failed!!!" -F "text=Your build has been failed." "-F attachment='1.txt'"

(滚动到行尾查看双引号变量值)。


更新

正如 @MathiasR.Jessen 指出的,使用 splatting 来传递变量数组可能更惯用:

$cmdargs = @("-F", "attachment='1.txt'")

curl -s --user api:*** `
    https://api.eu.mailgun.net/v3/***.com/messages
    ... etc... `
    -F text='Your build has been failed.' `
    @cmdargs

注意

@cmdargs
而不是
$cmdargs

$cmdargs
是字符串数组时,它似乎没有什么不同,但是如果您使用哈希表,您会得到明显不同的结果:

PS> $cmdargs = @{ "-F" = "attachment='1.txt'" }
PS> echoargs ... @cmdargs
...
Arg 12 is <--F:attachment='1.txt'>

PS> $cmdargs = @{ "-F" = "attachment='1.txt'" }
PS> echoargs ... @cmdargs
...
Arg 12 is <System.Collections.Hashtable>
© www.soinside.com 2019 - 2024. All rights reserved.