Question : Powershell if statement ending

I have written a script which uses and if statement and a "foreach" statement.  In that process I sending output to a file.  At the end of the script I want to delete the file but the script says the file is still in use and cannot be deleted.
I am new to powershell (I have worked with perl in the past) and would like to know how to end the foreach process and close output to the file so that it can be deleted.  I am including a snipit? of the code so you can see where I am at and tell me how to close the output file.
The last line is where the file open error occurs.

I am emailing that .txt file to a group first and then I need to delete it.  I only included the attachment part of the email scripting.
Code Snippet:
1:
2:
3:
4:
5:
6:
7:
8:
9:
10:
11:
12:
13:
14:
15:
16:
17:
18:
"Starting PowerLogRoll @ $(get-date)" | out-file "C:\Log Rollup\rollup-log.txt"
 
$logs = get-childitem C:\VoiceNet\Log
 
$year = get-date -f "yyyy"
$month = get-date -f "MM"
$day = get-date -f "dd"
 
foreach ($file in $logs) {
    $file | out-file "C:\Log Rollup\rollup-log.txt" -append
    if ($file.CreationTime -lt ($(Get-Date).AddMonths(-1))) {
    c:\7z\7za a "c:\log rollup\$month-$day-$year.zip" $file
    remove-item -force $file
}
}
$mailmessage.Attachments.Add('C:\Log Rollup\rollup-log.txt')
 
remove-item -force "C:\Log Rollup\rollup-log.txt"
Open in New Window Select All

Answer : Powershell if statement ending

I changed it a little and I get no errors that the file is loched:
1:
2:
3:
4:
5:
6:
7:
8:
9:
10:
11:
12:
13:
14:
15:
16:
17:
18:
19:
20:
21:
22:
23:
24:
25:
26:
27:
28:
29:
30:
31:
"Starting PowerLogRoll @ $(get-date)" | out-file "C:\Test\Powershell\XX_03\Log Rollup\rollup-log.txt"
 
$logs = get-childitem "C:\Test\Powershell\XX_03\Logs"
 
$year = get-date -f "yyyy"
$month = get-date -f "MM"
$day = get-date -f "dd"
 
function out-zip {
  Param([string]$path)
 
  if (-not $path.EndsWith('.zip')) {$path += '.zip'}
 
  if (-not (test-path $path)) {
    set-content $path ("PK" + [char]5 + [char]6 + ("$([char]0)" * 18))
  }
  $ZipFile = (new-object -com shell.application).NameSpace($path)
  $input | foreach {$zipfile.CopyHere($_.fullname)}
} 
 
foreach ($file in $logs) {
    $file | out-file "C:\Test\Powershell\XX_03\Log Rollup\rollup-log.txt" -append
    if ($file.CreationTime -lt ($(Get-Date).AddMonths(-1))) {
    	$file | out-zip "C:\Test\Powershell\XX_03\Log Rollup\$month-$day-$year.zip"
    	remove-item $file -force 
	}
}
 
$mailmessage.Attachments.Add('C:\Test\Powershell\XX_03\Log Rollup\rollup-log.txt')
 
remove-item -force "C:\Test\Powershell\XX_03\Log Rollup\rollup-log.txt"
Open in New Window Select All
Random Solutions  
 
programming4us programming4us