我的脚本有问题 .
每天晚上,服务器任务调度程序运行一个批处理,创建一个无法更新的PC的日志 . 然后,此PS脚本会提取错误日志并发送电子邮件通知我们PC . 错误日志文件是.txt文件,文件名每天更改以反映日期,例如10172016.txt .
我可以将脚本发送到电子邮件,它用于拉出日志文件并将其放入其正文中;但现在,它是空白的并显示有关“”的错误 .
码:
clear
$smtpserver = "test.test.org"
$from="noreply@test.org"
$to="adamh@test.org"
$subject="Update Error Log for" + " " + (get-date -format d)
$message = (Get-Content -path "\\testserver\Departments\IT\Private\test\logs" + "(get-date -f mmddyyyy)" + ".txt" | Out-String )
$mailer = new-object Net.Mail.SMTPclient($smtpserver)
$msg = new-object Net.Mail.MailMessage($from,$to,$subject,$body)
$msg.IsBodyHTML = $false
$mailer.send($msg)
请帮忙 .
1 回答
您的代码(至少)存在问题,即(命令简化):
它需要(注意括号括号和
get-date
命令周围没有双引号):PowerShell有 two fundamental parsing modes - argument mode 和 expression mode ,以及 understanding which is applied when is important :请参阅Get-Help about_Parsing .
简而言之:如果没有
(...)
,PowerShell会将"\path\to\" + (get-date -f MMddyyyy) + ".txt"
视为5个单独的参数,而不是单个合成字符串 .或者,您可以使用带有 string interpolation 的单个双引号字符串来使用 subexpression operator, $(...) 来嵌入
get-date
调用:补充意见:
自PowerShell版本3起,本机Send-MailMessage可用 .
2位数月份的格式字符串是
MM
,而不是mm
(后者是分钟) .虽然使用伪方法语法
new-object Net.Mail.MailMessage($from,$to,$subject,$body)
恰好起作用,但最好还是避免它,因为它可以掩盖对New-Object
如何工作的误解:正确的形式是New-Object Net.Mail.MailMessage -ArgumentList $from,$to,$subject,$body
;正如您所看到的,因为您正在处理cmdlet,它使用参数模式 .