0

I am creating a basic script that should access my NetApp, run two commands and output the results to a csv file, and then email that csv file to me. Finally, the file should be deleted.

From what I have learned while reading, shouldn't powershell wait until the previous step was completed and then automatically close the file after it was sent? I can still delete the file up until the Send-MailMessage command. The very next command is to delete the file, and the error is generated. This also happens if I highlight each line in the script and run them manually, waiting several minutes between commands. The only way I have found, so far, to unlock the file is to close Powershell.

How can I force Powershell to delete this open file? No other process is using it, I have received the email, and am no longer interested in keeping the file. I would prefer not to use a third party tool to do this

I am getting an error when I try to delete the file.

The delete command:

If (Test-Path $attachment){
    Remove-Item $attachment -Force
}

The error:

Remove-Item : Cannot remove item C:\perfstat\NcVol.csv: The process cannot access the file 'C:\perfstat\NcVol.csv' because it is being used by another process.
At line:1 char:1
+ Remove-Item $attachment -Force
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : WriteError: (C:\perfstat\NcVol.csv:FileInfo) [Remove-Item], IOException
    + FullyQualifiedErrorId : RemoveFileSystemItemIOError,Microsoft.PowerShell.Commands.RemoveItemCommand

Other bits:

$attachment = "c:\perfstat\NcVol.csv"
# Get the stats from the NetApp
Get-NcVol | Export-Csv -LiteralPath $attachment -Force -NoTypeInformation -Verbose  
Get-NcAggr | Export-Csv -LiteralPath $attachment -Force -NoTypeInformation -Verbose -Append
#Send the message
Send-MailMessage -To $emailTo -From $emailFrom -Subject $emailSubject -Body $emailBody -BodyAsHTML -Attachments $attachment -SmtpServer $emailSmtpServer
#Now delete the file
user3788019
  • 15
  • 1
  • 6

1 Answers1

0

i dont know how large this files are, but i may think that it needs some time while the email is send.

Just try to integrate a wait after you send mail:

Start-Sleep -s 10

Start-Sleep -s(for seconds) <seconds>

Please let me know if this works.

chrs04
  • 41
  • 7