使用PowerShell比较本地文本文件与Web上的文本文件是否相同

使用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!"
}

猜你喜欢

转载自www.cnblogs.com/makesense/p/11184554.html