初顧 PowerShell - 用 Powershell + .NET 發信

2014-11-24 PowerShell

PowerShell 在 Windows 2012R2 後已經是未來 Windows script 的主流,加上許多 IT 的推薦使得我步入我的 powershell script 第一步

 

以往都是使用 batch 或是 bash 來執行 script,這回在 Powershell 發現許多指令可以共通,真的是親民不少,網路上看到許多範例都將 .NET元件加入來進行 script 

 

在此篇也使用 Powershell + .NET 來試寫一個發信的 script

$mail = New-Object System.Net.Mail.MailMessage
$sender="eric@shazi.twbbs.org"
$recevier="eric@gmail.com"
$server="shazi.twbbs.org"
$body= "This is Test PowerShell Send Mail"
$msg=New-Object System.Net.Mail.MailMessage $sender,$recevier,$server,$body
$client=New-Object System.Net.Mail.SmtpClient $server
$client.send($msg)

 

存成 TestSendMail.ps1,執行發信測試成功!!

 

 

 

第一次執行 PowerShell script 的時候因為安全性而會拒絕執行 TestSendMail.ps1

TestSendMail.ps1 檔案無法載入,因為這個系統上已停用指令碼執行。如需詳細資訊,請參閱 “get-help about_signing”。 At line:0 char:0

 

執行 get-help about_signing 查到 PowerShell 執行安全性預設為 Restricted,是不允許任何 script 執行的。

所以必須更改為 RemoteSigned

set-executionpolicy remotesigned

 

又再度遇到錯誤!!

Set-ExecutionPolicy : 拒絕存取登錄機碼 ‘HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\PowerShell\1\ShellIds\Microsoft.PowerShell’。
位於 行:1 字元:20
+ set-executionpolicy <<<< remotesigned
+ CategoryInfo : NotSpecified: (:) [Set-ExecutionPolicy], UnauthorizedAccessException
+ FullyQualifiedErrorId : System.UnauthorizedAccessException,Microsoft.PowerShell.Commands.SetExecutionPolicyCommand

 

 

只好自己新增註冊檔來新增機碼

PowershellRemotesigned.reg

Windows Registry Editor Version 5.00

[HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\PowerShell\1\ShellIds\Microsoft.PowerShell]
"Path"="C:\\Windows\\System32\\WindowsPowerShell\\v1.0\\powershell.exe"
"ExecutionPolicy"="RemoteSigned"

 

 

 

 

參考資料

易學易用的 Windows PowerShell

One Reply to “初顧 PowerShell - 用 Powershell + .NET 發信”

  1. RAX表示:

    感謝分享,請問如果我想要夾帶附件,要怎麼寫呢?

給 Mr. 沙先生一點建議

彙整

分類

展開全部 | 收合全部

License

訂閱 Mr. 沙先生 的文章

輸入你的 email 用於訂閱