0

我正在创建一个应该访问我的 NetApp、运行两个命令并将结果输出到 csv 文件的基本脚本,然后将该 csv 文件通过电子邮件发送给我。最后,该文件应该被删除。

根据我在阅读时了解到的情况,powershell不应该等到上一步完成然后在文件发送后自动关闭文件吗?在 Send-MailMessage 命令之前,我仍然可以删除该文件。下一个命令是删除文件,并生成错误。如果我突出显示脚本中的每一行并手动运行它们,在命令之间等待几分钟,也会发生这种情况。到目前为止,我发现解锁文件的唯一方法是关闭 Powershell。

如何强制 Powershell 删除这个打开的文件?没有其他进程正在使用它,我已收到电子邮件,并且不再对保留文件感兴趣。我不希望使用第三方工具来执行此操作

当我尝试删除文件时出现错误。

删除命令:

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

错误:

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

其他位:

$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
4

1 回答 1

0

我不知道这个文件有多大,但我可能认为发送电子邮件需要一些时间。

发送邮件后尝试集成等待:

Start-Sleep -s 10

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

请让我知道这是否有效。

于 2016-11-22T11:54:29.420 回答