我正在编写一个脚本,它将检查文件夹并返回最后一个文件日期修改时间戳。然后它将比较当前系统时间并找出两者之间的差异,如果时间大于20分钟,则发送电子邮件通知。
调试/运行时,我收到以下错误:
New-TimeSpan:找不到接受参数'$ null'的位置参数。 在C:\ Users \ jalden \ Desktop \ CalderaMonitoring-Part1.ps1:7 char:14 + $ dtdiff = New-TimeSpan($ _。LastWriteTime)$(获取日期) + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + CategoryInfo:InvalidArgument:(:) [New-TimeSpan],ParameterBindingException + FullyQualifiedErrorId:PositionalParameterNotFound,Microsoft.PowerShell.Commands.NewTimeSpanCommand
这是我的剧本:
$src="c:\test\"
$sendmail=$false
Get-Item -path $src | Foreach {$_.LastWriteTime}
Foreach-Object
{
#write-host $_.fullname
$dtdiff = New-TimeSpan ($_.LastWriteTime) $(Get-Date)
if ($dtdiff.minutes -gt 20)
{
$strbody=$strbody +$_.fullname+ " - Created Time: " +$_.LastWriteTime +"`r`n"
$sendmail=$true
}
}
#$strbody
if($sendmail -eq $true)
{
# Email components
$strFromAddress = "abc@xyz.net"
$strToAddress = "abc@xyz.net"
$strMessageSubject = "Files not uploaded in the last 20 minutes"
$strMessageBody = $strbody
$strSendingServer = "smtp.gmail.com"
$SMTPPort = "587"
$emailSmtpUser = "abc@xyz.net"
$emailSmtpPass = "testasfasdfa"
# Email objects
$objSMTPMessage = New-Object System.Net.Mail.MailMessage $strFromAddress, $strToAddress, $strMessageSubject, $strMessageBody
$objSMTPClient = New-Object System.Net.Mail.SMTPClient( $strSendingServer, $SMTPPort )
$objSMTPClient.EnableSsl = $true
$objSMTPClient.Credentials = New-Object System.Net.NetworkCredential( $emailSmtpUser , $emailSmtpPass );
$objSMTPClient.Send($objSMTPMessage)
}
有什么建议吗?
答案 0 :(得分:5)
下面的第二行,您没有向ForEach-Object
提供任何输入,因此$_
为$null
Get-Item -path $src | Foreach {$_.LastWriteTime}
Foreach-Object {
#write-host $_.fullname
$dtdiff = New-TimeSpan ($_.LastWriteTime) $(Get-Date)
if ($dtdiff.minutes -gt 20){
$strbody=$strbody +$_.fullname+ " - Created Time: " +$_.LastWriteTime +"`r`n"
$sendmail=$true
}
}
将其更改为:
Get-Item -path $src | ForEach-Object {
#write-host $_.fullname
$dtdiff = New-TimeSpan ($_.LastWriteTime) $(Get-Date)
if ($dtdiff.TotalMinutes -gt 20){
$strbody=$strbody +$_.fullname+ " - Created Time: " +$_.LastWriteTime +"`r`n"
$sendmail=$true
}
}
作为@gravity notes,如果$dtdiff.TotalMinutes
声明
$dtdiff.Minutes
而不是if