使用PowerShell比較本地文本文件是否相同通常有兩種方式:1.通過Get-FileHash這個命令,比較兩個文件的哈希是否相同;2.通過Compare-Object這個命令,逐行比較兩個文件的內容是否相同。
比較本地文本文件與Web上的文本文件也是同樣的2種思路,只不過要首先處理好web上的文件。處理web上的文件也顯然有兩種思路:1.得到web文件的內容(Invoke-WebRequest),直接在內存中比較;2.得到web文件的內容,再把文件存到本地,轉化為本地文件之間的比較。這種方法只需要在得到web文件的內容后,加一步文件寫入操作(New-Item, Add-Content)即可,沒什么可說的,本文主要講第1種方式的兩種比較方式,為了易於辨識程序的正確性,此處兩個文件的內容是相同的。
1.比較兩個文件的哈希是否相同
1 #獲取本地文件的hash(采用MD5) 2 $path = "C:\local.txt" 3 $hashLocal = Get-FileHash -Path $path -Algorithm MD5 4 Write-Output $hashLocal 5 6 $url = "XXX" 7 #設置"-ExpandProperty"才能完全返回文本內容 8 $cotent = Invoke-WebRequest -Uri $url | select -ExpandProperty Content 9 #轉化為Char數組,放到MemoryStream中 10 $charArray = $cotent.ToCharArray() 11 $stream = [System.IO.MemoryStream]::new($charArray) 12 #Get-FileHash還可以通過Stream的方式獲取hash 13 $hashWeb = Get-FileHash -InputStream ($stream) -Algorithm MD5 14 #注意關閉MemoryStream 15 $stream.Close() 16 Write-Output $hashWeb 17 18 $hashLocal.Hash -eq $hashWeb.Hash
2.逐行比較兩個文件的內容是否相同
1 $path = "C:\local.txt" 2 $url = "XXX" 3 $contentLocal = Get-Content $path 4 $cotentWeb = Invoke-WebRequest -Uri $url | select -ExpandProperty Content 5 $diff = Compare-Object -ReferenceObject $($contentLocal) -DifferenceObject $($cotentWeb) 6 if($diff) { 7 Write-Output "The content is not the same!" 8 }
發現運行結果不正確,調試發現 Get-Content
(cat
)返回值類型是System.Array
,而Invoke-WebRequest
返回值類型是 String
1 PS C:\> $item1.GetType() 2 3 IsPublic IsSerial Name BaseType 4 -------- -------- ---- -------- 5 True True Object[] System.Array 6 7 PS C:\> $item2.GetType() 8 9 IsPublic IsSerial Name BaseType 10 -------- -------- ---- -------- 11 True True String System.Object
所以需要對Invoke-WebRequest
的返回值類型進行轉換
$path = "C:\local.txt" $url = "XXX" $contentLocal = Get-Content $path $cotentWeb = Invoke-WebRequest -Uri $url | select -ExpandProperty Content #使用正則表達式"\r?\n"消除換行符差異的影響 $cotentWebArray = $cotentWeb -split '\r?\n' $diff = Compare-Object -ReferenceObject $($contentLocal) -DifferenceObject $($cotentWebArray) if($diff) { Write-Output "The content is not the same!" }