>我试图在select-string -pattern
中使用变量,但它什么也没返回。如果我将变量的内容复制并粘贴到语法中,它可以工作。
拥有的是我之前记录的一些哈希,并希望再次获取同一目录的哈希,看看它们是否与以前记录的哈希相同,因此我尝试使用 select-string。
用于获取原始哈希:
$data2hash = "C:usersblueDesktop*.txt"
$hash = Get-FileHash $data2hash -Algorithm md5
$h_hash = $hash.hash
PS C:Users> get-filehash c:usersbobdesktop* -Algorithm md5 | export-csv c:usersbobdesktophashes.csv
Algorithm Hash Path
--------- ---- ----
MD5 E081EAAA07EC3CBC71DBC374E85B3031 c:usersbobdesktop1.txt
MD5 78D85AB09077BA9BE641C5AFC1EDFEE9 c:usersbobdesktop2.txt
MD5 69B8789ED87248AB5B69C0421ADF6E54 c:usersbobdesktop3.txt
MD5 34DF279CA08B79238246787321939C60 c:usersbobdesktop4.txt
验证阶段
$db = 'C:usersbobDesktophashes.csv'
$db2 = Get-Content $db
$some_data = "C:usersbobDesktop*"
$new_hashes = Get-FileHash $data2hash -Algorithm md5
$h_hashes = $hash.hash
foreach($h in $h_hash)
{
$format_hash = "'" + $h + "',"
$d += $format_hash
}
$d = $d.substring(0,$d.length-1)
PS C:Usersbobdesktop> $d.GetType()
IsPublic IsSerial Name BaseType
-------- -------- ---- --------
True True String System.Object
$db2 | select-string -pattern $d
期望输出:
PS C:Users> $db2 | select-string -pattern $d
"MD5","3C535413A18289E8CEEF69ED15479515","C:usersblueDesktopcomputers.txt"
"MD5","60E6B4CF0E9A1E99E5861ECE1001DB3D","C:usersblueDesktopfilecheck.txt"
"MD5","BC36FF295E4A68EE9C8E04B1D833E836","C:usersblueDesktopFilesCheck_02-08-14.txt
要么
将哈希作为字符串数组直接传递给-Pattern
,不要尝试连接它们:
$db2 | select-string -pattern $h_hashed
或者,如果要提供单个正则表达式模式,请使用|
(逻辑或正则表达式)构造它:
$pattern = '(?:{0})' -f ($h_hashed -join '|')
$db2 |Select-String -Pattern $pattern
我还建议Select-String
直接指向文件,不要使用Get-Content
:
Select-String -Path 'C:usersbobDesktophashes.csv' -Pattern $pattern
如果你想将哈希和文件比较到同一个目录中,你可以像这样比较你的csv文件
#Get-FileHash "c:temp*.txt" -Algorithm md5 | export-csv "c:tempLastAnalyse.csv" -NoTypeInformation
Get-FileHash "c:temp*.txt" -Algorithm md5 | export-csv "c:tempNewAnalyse.csv" -NoTypeInformation
$LastAnalyse=import-csv "c:tempLastAnalyse.csv"
$NewAnalyse=import-csv "c:tempNewAnalyse.csv"
Compare-Object $LastAnalyse $NewAnalyse -Property Hash, Path
如果你想看看所有的差异:
Get-FileHash "c:temp*.txt" -Algorithm md5 | export-csv "c:tempNewAnalyse.csv" -NoTypeInformation
$LastAnalyse=import-csv "c:tempLastAnalyse.csv"
$NewAnalyse=import-csv "c:tempNewAnalyse.csv"
$lst=Compare-Object $LastAnalyse $NewAnalyse -Property Hash, Path
$lst | %{
$element=$_
$ListSameElement=$lst | where { $_.Path -eq $element.Path -and $_.Hash -ne $element.Hash} | select -First 1
if ($_.SideIndicator -eq '=>')
{
if ($ListSameElement.Count -eq 0)
{
$Explain="New File Created"
$OldHash=""
}
else
{
$Explain="Hash Modified"
$OldHash=$ListSameElement.Hash
}
[pscustomobject]@{Hash=$element.hash;File=$element.Path;OldHAsh=$OldHash; Explain=$Explain}
}
elseif ($_.SideIndicator -eq '<=' -and $ListSameElement.Count -eq 0)
{
[pscustomobject]@{Hash="";File=$element.Path;OldHAsh=$element.hash; Explain="File Deleted"}
}
}