简体   繁体   中英

Set and use PowerShell variable in CMD

I'd like to send an Email from within my (existing) .bat using Send-MailMessage . Since it should be automated I stored the secured password to MailPW.txt already. In the script I'd like to use it, but unfortunately the $cred variable is empty (I assume the $pw as well).

...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?

You are opening three different powershell sessions. (your problem)

Just merge all commands into a single .ps1 file

$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

powershell -File Script.ps1

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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