简体   繁体   English

强制关闭脚本运行时正在使用的文件

[英]Force close files that are in use when the script runs

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

However I am using -force with -move item but it still have this issue. 但是,我将-force-move item一起使用,但仍然存在此问题。 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. 为了避免这种情况,所有现代OS都会阻止非特权用户进行此类操作。

That being said, you could use a tool like Sysinternals' Handle.exe to check if a file has got open a handle. 话虽如此,您可以使用Sysinternals的 Handle.exe类的工具来检查文件是否已打开句柄。 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. 确保唯一的方法是将文件内容复制到存档位置(如果您获得了独占写入锁),最后删除该文件。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM