强制关闭脚本运行时正在使用的文件 [英] Force close files that are in use when the script runs

查看:46
本文介绍了强制关闭脚本运行时正在使用的文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下脚本,可以获取早于指定日期的文件并将它们保存为不同文件夹中的存档.该脚本适用于大多数文件,但对于某些文件,它会出现此错误并且未将这些文件包含在存档中.

I have following script that take files older than specified day and saves them as archive in a different folder. The script works fine with most of the files but for some files it gives this error and doesn’t include those file in the archive.

Move-Item : The process cannot access the file because it is being used by another process.
At C:\SRS\SRSLogArchieveScript.ps1:49 char:13
+             Move-Item <<<<  $item.FullName $destPathController -force;
    + CategoryInfo          : WriteError: (C:\SRS\Controll...apter0611-1.log:FileInfo) [Move-Item], IOException
    + FullyQualifiedErrorId : MoveFileInfoItemIOError,Microsoft.PowerShell.Commands.MoveItemCommand

但是我使用 -force-move item 但它仍然有这个问题.有没有一种方法可以强制关闭所有正在使用的文件,以确保所有文件都作为存档的一部分包含在内.

However I am using -force with -move item but it still have this issue. Is there a way I can actually force close all the files in use to make sure all files are included as a part of archive.

try
{
foreach( $item in (Get-ChildItem $sourcePath -recurse | Where-Object { $_.CreationTime -le $archiveTillDate }) )
{
$item.FullName;
Move-Item $item.FullName $destPath -force;
}
}
catch
{
$_.Exception.Message;
}
Finally
{
#Executing Zip Command to Archieve:
& $pathTo7ZipExe $arguments;

#Delete temporary log archieve directory
Remove-Item $logArchieve -recurse;

}

推荐答案

此行为是设计使然.考虑保持打开文件的原始应用程序尝试写入其中.如果您窃取"了底层文件,会发生什么?从崩溃到意外行为的任何事情.为了防止这种情况发生,所有现代操作系统都禁止非特权用户进行此类操作.

This behavior is by design. Consider that the original application keeping an open file tries to write into it. If you have "stolen" the underlying file, what'll happen? Anything from a crash to unexpected behavior. To prevent such a thing, all modern OS prevent such an operation from non-priviledged users.

话虽如此,您可以使用像 Sysinternals' 这样的工具Handle.exe 检查文件是否打开了句柄.如果您有足够的权限,同样的工具可以关闭句柄.

That being said, you could use a tool like Sysinternals' Handle.exe to check if a file has got open a handle. The same tool can close handles if you have sufficient permissions.

另一种解决方案是尝试以读写访问打开文件.这将允许您过滤掉保留的文件 - 假设在您释放自己的锁之后没有进程会打开文件.唯一可以确定的方法是将文件内容复制到您获得独占写锁的存档位置并最终删除文件.

Another a solution would be to try and open the file with read-write access. This would allow you to filter out files that are reserved - assuming no process is going to open the file just after you release your own lock. The only way to be sure is to copy the file contents into archive location whlist you got the exclusive write lock and finally deleting the file.

这篇关于强制关闭脚本运行时正在使用的文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆