我想通过校验和检查文件是否完整。为了使更容易,我将哈希人放入文件的替代数据流中。当某人改变文件时,我可以使用校验和验证此文件。
但是,当我添加数据流时,文件的持久时间会更新,因此我添加了功能以逆转它。
它的工作就像魅力一样 - 主要是。但是一些文件失败了,约为5%。我不知道为什么。看起来它失败了,其中包含空格或额外点的文件名,但是许多其他在文件名中的空格和多个点的功能都可以正常工作。
有谁知道发生了什么,如何防止这些失败或如何改进代码?
谢谢!
代码:
$filenames = Get-ChildItem *.xl* -Recurse | % { $_.FullName }
foreach( $filename in $filenames ) { ForEach-Object { $timelwt = Get-ItemProperty $filename | select -expand LastWriteTime | select -expand ticks } {add-content -stream MD5 -value (Get-FileHash -a md5 $filename).hash $filename } { Set-ItemProperty $filename -Name LastWriteTime -Value $timelwt}}```
I want to check files for integrity with a checksum. To make it easier I put the hash into an alternate data stream of the file. When someone alters the file I can verify this with the checksum.
However, when I add a data stream the file's LastWriteTime gets updated, so I added functionality to reverse it.
It works like a charm - mostly. But it fails with some files, about 5%. I have no idea why. It looks like it fails with file names that contain spaces or extra dots, but many other that have spaces and multiple dots in the file name work just fine.
Does anyone know what's going on, how to prevent these failures or how to improve the code?
Thanks!
The code:
$filenames = Get-ChildItem *.xl* -Recurse | % { $_.FullName }
foreach( $filename in $filenames ) { ForEach-Object { $timelwt = Get-ItemProperty $filename | select -expand LastWriteTime | select -expand ticks } {add-content -stream MD5 -value (Get-FileHash -a md5 $filename).hash $filename } { Set-ItemProperty $filename -Name LastWriteTime -Value $timelwt}}```
发布评论
评论(1)
您的代码可以简化为:
get-childitem
使用-filter
您已经准备就绪的代码将返回fileInfo
具有设置 属性,没有理由使用get-itemproperty
norset-itemproperty
在它们上。至于,为什么您的代码可能会失败,讨人喜欢的解释是您有一些文件路径,野卡元时间,并且由于您不使用
-literalPath
,因此cmdlets违约到>
-Path
参数(允许通配符元听筒)。顺便说一句,我个人建议您为文件创建一个单独的校验和文件,而不是添加替代数据流。
Your code can be reduced to this:
Get-ChildItem
with the-Filter
you have in place will returnFileInfo
objects, which have a settableLastWriteTime
property, there is no reason for usingGet-ItemProperty
norSet-ItemProperty
over them.As for, why your code could be failing, the likeable explanation is that you have some file paths with wildcard metacharacters, and since you're not using
-LiteralPath
, the cmdlets are defaulting to the-Path
parameter (which allows wildcard metacharacters).As aside, I would personally recommend you to create a separate checksum file for the files instead of adding an alternative data stream.