在CMD中设置和使用PowerShell变量

时间:2019-03-06 09:32:37

标签: powershell batch-file

我想使用.bat从我(现有)Send-MailMessage内部发送电子邮件。由于应该自动进行,因此我已经将安全密码存储到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}"

根据建议的here,没有成功。

基本上我想设置一个$cred var并在下一个命令中使用它,甚至可以用这种方法吗?

1 个答案:

答案 0 :(得分:0)

您要打开三个不同的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