簡體   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