2016-08-10 30 views
-1

我錯過了某些東西,當我嘗試將下面的單行命令轉換爲多行時。我搜索,發現並試圖在Powershell -Command over multiple line錯誤引用和/或轉義,cmd運行Powershell

之後建模此更改我缺少什麼?我試圖讓測試變得很容易。只需將前兩(2)行更改爲適合您系統的內容即可。

=== emailtest.bat

@ECHO OFF 
SET "[email protected]" 
SET "SMTPHOST=imr2.nowhere.org" 
SET "FN=C:\Windows\win.ini" 
@ECHO ON 

powershell -Command "& send-mailmessage -to "%RECIPIENT%" -from '[email protected]' -subject 'test file transfer' -SmtpServer '%SMTPHOST%' -BodyAsHTML 'The file is <a href="%FN">here</a> for you.' 

powershell -noprofile -Command "&{"^ 
send-mailmessage -to "%RECIPIENT%"^
-from '[email protected]'^
-subject 'test file transfer'^
-SmtpServer '%SMTPHOST%'^
-BodyAsHTML 'The file is <a href="%FN%">here</a> for you.'^ 
"}" 

===輸出是

C:>call emailtest.bat 

12:17:24.75 C:\Users\me\t 
C:>powershell -Command "& send-mailmessage -to "[email protected]" -from '[email protected]' -subject 'test file transfer' -SmtpServer 'imr2.nowhere.org' -BodyAsHTML 'The file is <a href="C:\Windows\win.ini">here</a> for you.' 

12:17:27.28 C:\Users\me\t 
C:>powershell -noprofile -Command "&{" send-mailmessage -to "[email protected]" -from '[email protected]' -subject 'test file transfer' -SmtpServer 'imr2.nowhere.org' -BodyAsHTML 'The file is href="C:\Windows\win.ini""}" 0</a 1>for 
The system cannot find the file specified. 
+1

如果您直接使用PowerShell而不是嘗試在cmd.exe外殼腳本(批處理文件)中打包PowerShell命令,事情會變得更簡單和更簡單。 –

回答

0

相信示例只能是因爲它仍然是每行多個命令。如果你嘗試在多行上執行一條命令,那麼你需要在powershell中將它們轉義出來,這裏使用splatting是一個更好的解決方案。

powershell -NoProfile -Command "&{"^
    "$message = @{};"^
    "$message.Subject = 'test file transfer';"^
    "$message.From = '[email protected]';"^
    "$message.To = '%RECIPIENT%';"^
    "$message.SmtpServer = '%SMTPHOST%';"^
    "$message.Body = 'The file is <a href="%FN%">here</a> for you.';"^
    "$message.BodyAsHTML = $true; "^
    "Send-MailMessage @message"^
}" 

這就是說,你應該考慮把這個ps1文件,如果可能的話。可讀性遠非如此。另外BodyAsHTML是一面旗幟。你仍然需要設置身體。您的代碼在技術上仍然可以工作,因爲Body是一個位置參數,只是闡明瞭它在splat中添加的原因。

+0

非常感謝。這是行得通的。 – lit

相關問題