简体   繁体   English

在CMD中设置和使用PowerShell变量

[英]Set and use PowerShell variable in CMD

I'd like to send an Email from within my (existing) .bat using Send-MailMessage . 我想使用Send-MailMessage从(现有) .bat内部发送电子邮件。 Since it should be automated I stored the secured password to MailPW.txt already. 由于应该自动进行,因此我已经将安全密码存储到MailPW.txt In the script I'd like to use it, but unfortunately the $cred variable is empty (I assume the $pw as well). 在脚本中,我想使用它,但是不幸的是$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

I also tried 我也试过

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

as suggested here without any success. 这里建议的那样没有任何成功。

Basically I want to set a $cred var and use it in the next command, is that even possible with this approach? 基本上,我想设置一个$cred var并在下一个命令中使用它,使用这种方法是否有可能?

You are opening three different powershell sessions. 您将打开三个不同的Powershell会话。 (your problem) (你的问题)

Just merge all commands into a single .ps1 file 只需将所有命令合并到一个.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

And call the powershell script inside your .bat file 并在.bat文件中调用powershell脚本

powershell -File Script.ps1

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

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