title: PowerShell End time of script execution
body: <p>I'm trying to write the start and end-date of this script in a logfile. The startdate is not a problem, but the end-date is apparently not written to the log.</p>
  
     
  
  <pre class="lang-powershell prettyprint-override"><code>$Target = "\\share\dir1\dir2"
  
  # Set start time
  $StartTime = (Get-Date).ToShortDateString()+", "+(Get-Date).ToLongTimeString()
  
  Get-ChildItem -Directory -Path $Target | 
      Where-Object { $_.LastWriteTime -lt (Get-Date).AddDays(-60) } | % {
          $folder = $_;
          Remove-Item $folder.FullName -Recurse -Force | Out-Null
          $folder.FullName  
          # Set end time 
          $EndTime = (Get-Date).ToShortDateString()+", "+(Get-Date).ToLongTimeString()   
          } | 
  
  # Write footer to log
  Write-Output ($Footer = @"
  
  $("-"*79)
  
     Start Time          : $StartTime
     End Time            : $EndTime
  
  $("-"*79)
  "@)
  
  Out-File $Target\Auto_Clean.log -Append -InputObject $Footer
  
  # Clean up variables at end of script
  $Target=$StartTime=$EndTime = $null
  </code></pre>
  
  <p>Thanks to the help from the guys here at Stackoverflow, I found the complete answer. </p>
  
  <p><strong>Solution:</strong></p>
  
  <pre class="lang-powershell prettyprint-override"><code>&lt;#  Author: Me@site.com 
      ########## Remove folders older than x days
      2014/05/06 Script born 
      2014/05/07 Add total runtime of the script to the logfile #&gt;
  
  #================= VARIABLES ==================================================
  $Target = "\\Share\dir1\dir2"
  $OlderThanDays = "60"
  $Logfile = "$Target\Auto_Clean.log"
  
  #================= BODY =======================================================
  # Set start time
  $StartTime = (Get-Date).ToShortDateString()+", "+(Get-Date).ToLongTimeString()
  
  Write-Output "`nDeleting folders that are older than $OlderThanDays days:`n"
  
  Get-ChildItem -Directory -Path $Target | 
      Where-Object { $_.LastWriteTime -lt (Get-Date).AddDays(-$OlderThanDays) } | ForEach {
          $Folder = $_;
          Remove-Item $Folder.FullName -Recurse -Force | Out-Null
          $Folder.FullName } | Tee-Object $LogFile -Append # Output folder names to console &amp; logfile at the same time
  
  # Set end time &amp; calculate runtime
  $EndTime = (Get-Date).ToShortDateString()+", "+(Get-Date).ToLongTimeString()
  $TimeTaken = New-TimeSpan -Start $StartTime -End $EndTime
  
  # Write footer to log
  Write-Output ($Footer = @"
  
  $("-"*79)
     Start Time          : $StartTime
     End Time            : $EndTime
     Total runtime       : $TimeTaken
  $("-"*79)
  "@)
  
  # Create logfile
  Out-File $LogFile -Append -InputObject $Footer
  
  # Clean up variables at end of script
  $Target=$StartTime=$EndTime=$OlderThanDays = $null
  </code></pre>