Powershell:复制文件而不锁定 [英] Powershell: copy file without locking

查看:88
本文介绍了Powershell:复制文件而不锁定的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我创建了简单的 nagios 插件 check_log.ps1检查 Windows 机器上的日志文件.它的工作方式是复制日志内容,并在下次查找日志副本和原始日志文件之间的差异的指定字符串.

I created simple nagios plugin check_log.ps1 to check log file on windows machine. It works in way that make copy content of log and in next time look for specified string in difference between copy of log and original log file.

问题是有时在随机时刻 check_log.ps1 会锁定日志文件,因此会导致创建日志文件的应用程序停止.

The problem is that sometimes in random moments check_log.ps1 locks log file so it cause stop of the application which create log file.

一般插件在两个地方使用原始日志文件

Generally plugin use original log file in two places

# compare content of $Logfile and $Oldlog, save diff to $tempdiff
Compare-Object -ReferenceObject (Get-Content -Path $Logfile) -DifferenceObject (Get-Content -Path $Oldlog) | Select-Object -Property InputObject > $tempdiff

# override file $Oldlog using conetent of $Logfile
Copy-Item $Logfile $Oldlog

我做测试.在一个 PS 会话中,我运行 while($true) { [string]"test" >>C:\test\test.log },在第二个会话中我运行插件 C:\test\check_log.ps1 C:\test\test.log C:\test\Old_log.log test

I make test. In one PS session I run while($true) { [string]"test" >> C:\test\test.log }, in second session I run plugin C:\test\check_log.ps1 C:\test\test.log C:\test\Old_log.log test

我不确定我的测试是否正确,但我认为 Copy-Item 命令会导致问题.当我在脚本中注释这一行时,我在终端中看不到任何错误.我测试了一些自定义函数来复制我在互联网上找到的文件,但我没有找到解决我的问题的方法.

I'm not fully sure if my test is correct but I think that Copy-Item command cause problem. When I comment this line in script I don't see any errors in terminals. I tested some custom functions to copy file which I found in internet but I din't find solution for my problem.

你知道如何让它充分发挥作用吗?

Do you have an idea how to make it work fully?

推荐答案

如果您认为复制项正在锁定文件,请尝试读取内容,然后将其保存到其他位置.像这样:

if you think the copy-item is locking the file, try reading the content and then saving it to another location. Something like this:

获取内容 $Logfile |设置内容 $Oldlog

Get-Content $Logfile | Set-Content $Oldlog

这篇关于Powershell:复制文件而不锁定的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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