繁体   English   中英

在CMD中设置和使用PowerShell变量

[英]Set and use PowerShell variable in CMD

我想使用Send-MailMessage从(现有) .bat内部发送电子邮件。 由于应该自动进行,因此我已经将安全密码存储到MailPW.txt 在脚本中,我想使用它,但是不幸的是$cred变量为空(我也假定$pw )。

...Rest of .bat Script (ROBOCOPY Commands)...

powershell -ExecutionPolicy ByPass -Command " & {$pw = Get-Content .\MailPW.txt | ConvertTo-SecureString}"
powershell -ExecutionPolicy ByPass -Command " & {$cred = New-Object System.Management.Automation.PSCredential "zyx@othermail.com", $pw} "
powershell -ExecutionPolicy ByPass -Command Send-MailMessage ^
    -SmtpServer "smtp.office365.com" ^
    -UseSsl ^
    -To "xyz@mail.com" ^
    -From "zyx@othermail.com" ^
    -Subject "Testing" ^
    -Body "Hello" ^
    -Port "587" ^
    -Encoding ([System.Text.Encoding]::UTF8) ^
    -Credential $cred

我也试过

-Credential "& {New-Object System.Management.Automation.PSCredential "zyx@othermail.com", Get-Content .\\MailPW.txt | ConvertTo-SecureString}"

这里建议的那样没有任何成功。

基本上,我想设置一个$cred var并在下一个命令中使用它,使用这种方法是否有可能?

您将打开三个不同的Powershell会话。 (你的问题)

只需将所有命令合并到一个.ps1文件中

$pw = Get-Content .\MailPW.txt | ConvertTo-SecureString
$cred = New-Object System.Management.Automation.PSCredential "zyx@othermail.com", $pw
Send-MailMessage ^
    -SmtpServer "smtp.office365.com" ^
    -UseSsl ^
    -To "xyz@mail.com" ^
    -From "zyx@othermail.com" ^
    -Subject "Testing" ^
    -Body "Hello" ^
    -Port "587" ^
    -Encoding ([System.Text.Encoding]::UTF8) ^
    -Credential $cred

并在.bat文件中调用powershell脚本

powershell -File Script.ps1

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM