Jonathan Alden
Jonathan Alden

Reputation: 25

Powershell Script Troubleshooting

I am working on a script that will check a folder and return the last file date modified time stamp. It will then compare the Current System Time and find the difference between the two and if time is greater than 20 minutes if will send out an email notification.

When debugging/running it I get the following error:

New-TimeSpan : A positional parameter cannot be found that accepts argument '$null'. At C:\Users\jalden\Desktop\CalderaMonitoring-Part1.ps1:7 char:14 + $dtdiff = New-TimeSpan ($_.LastWriteTime) $(Get-Date) + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + CategoryInfo : InvalidArgument: (:) [New-TimeSpan], ParameterBindingException + FullyQualifiedErrorId : PositionalParameterNotFound,Microsoft.PowerShell.Commands.NewTimeSpanCommand

Here is my Script:

$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 = "[email protected]"
    $strToAddress = "[email protected]"
    $strMessageSubject = "Files not uploaded in the last 20 minutes"
    $strMessageBody = $strbody
    $strSendingServer = "smtp.gmail.com"
    $SMTPPort = "587"
    $emailSmtpUser = "[email protected]"
    $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)
}

Any suggestions?

Upvotes: 0

Views: 1207

Answers (1)

Mathias R. Jessen
Mathias R. Jessen

Reputation: 174485

One the second line below, you don't provide any input to ForEach-Object, so $_ is $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
    }       
}

Change it to:

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
    }       
}

As @gravity notes, you should use $dtdiff.TotalMinutes rather than $dtdiff.Minutes if the if statement

Upvotes: 5

Related Questions