gpt4 book ai didi

powershell - 转义序列问题-批处理

转载 作者:行者123 更新时间:2023-12-03 00:00:25 29 4
gpt4 key购买 nike

我想在批处理文件中使用PowerShell命令发送电子邮件。为此,我实现了一个名为 sendMail 的函数。我这样称呼它:

setlocal enabledelayedexpansion
call:sendMail
powershell -command "!_mailCommand!"
endlocal
pause&goto:eof

我的 sendMail 函数:
:sendMail

set "_mailCommand=&{$filenameAndPath = '!resultFile!';"
set "_mailCommand=%_mailCommand%$SMTPMessage = New-Object System.Net.Mail.MailMessage('%_mailFrom%', '%_mailTo%', '%_mailSubject%', '%_mailBody%');"
set "_mailCommand=%_mailCommand%$attachment = New-Object System.Net.Mail.Attachment($filenameAndPath);"
set "_mailCommand=%_mailCommand%$SMTPMessage.Attachments.Add($attachment);"
set "_mailCommand=%_mailCommand%$SMTPClient = New-Object Net.Mail.SmtpClient('%_mailHost%', %_mailPort%);"
set "_mailCommand=%_mailCommand%$SMTPClient.EnableSsl = $true;"
set "_mailCommand=%_mailCommand%$SMTPClient.Credentials = New-Object System.Net.NetworkCredential('%_mailFrom%','%_mailSenderPassword%');"
set "_mailCommand=%_mailCommand%$SMTPClient.Send($SMTPMessage)}"
echo %_mailSenderPassword%

出乎意料的是,我得到这样的输出:

12345Aa!

Exception calling "Send" with "1" argument(s): "Failure sending mail."

At line:1 char:499 ... m','12345Aa^');$SMTPClient.Send($SMTPMessage)}

CategoryInfo : NotSpecified: (:) [], MethodInvocationException

FullyQualifiedErrorId : SmtpException



您可以猜到,我的密码是12345Aa!我在代码的开头将其定义为 set "_mailSenderPassword=12345Aa^^!"
那我想念什么呢?提前致谢!

最佳答案

当使用延迟扩展时,应避免扩展百分比,否则会出现尖号^和感叹号!以及有时带有引号的问题。

在扩展百分比之后,将对内容进行特殊字符解析,但在延迟扩展之后,将按原样使用它。

setlocal EnableDelayedExpansion
set "_mailSenderPassword=12345Aa^!"
call :sendMail
powershell -command "!_mailCommand!"
exit /b

:sendMail
set "_mailCommand=&{$filenameAndPath = '!resultFile!';"
set "_mailCommand=!_mailCommand!$SMTPMessage = New-Object System.Net.Mail.MailMessage('!_mailFrom!', '!_mailTo!', '!_mailSubject!', '!_mailBody!');"
set "_mailCommand=!_mailCommand!$attachment = New-Object System.Net.Mail.Attachment($filenameAndPath);"
set "_mailCommand=!_mailCommand!$SMTPMessage.Attachments.Add($attachment);"
set "_mailCommand=!_mailCommand!$SMTPClient = New-Object Net.Mail.SmtpClient('!_mailHost!', !_mailPort!);"
set "_mailCommand=!_mailCommand!$SMTPClient.EnableSsl = $true;"
set "_mailCommand=!_mailCommand!$SMTPClient.Credentials = New-Object System.Net.NetworkCredential('!_mailFrom!','!_mailSenderPassword!');"
set "_mailCommand=!_mailCommand!$SMTPClient.Send($SMTPMessage)}"
echo !_mailSenderPassword!
exit /b

关于powershell - 转义序列问题-批处理,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31320705/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com