[英]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.