使用PowerShell比较本地文本文件是否相同通常有两种方式:1.通过Get-FileHash这个命令,比较两个文件的哈希是否相同;2.通过Compare-Object这个命令,逐行比较两个文件的内容是否相同。

比较本地文本文件与Web上的文本文件也是同样的2种思路,只不过要首先处理好web上的文件。处理web上的文件也显然有两种思路:1.得到web文件的内容(Invoke-WebRequest),直接在内存中比较;2.得到web文件的内容,再把文件存到本地,转化为本地文件之间的比较。这种方法只需要在得到web文件的内容后,加一步文件写入操作(New-Item, Add-Content)即可,没什么可说的,本文主要讲第1种方式的两种比较方式,为了易于辨识程序的正确性,此处两个文件的内容是相同的。

1.比较两个文件的哈希是否相同

  #获取本地文件的hash(采用MD5)
$path = "C:\local.txt"
$hashLocal = Get-FileHash -Path $path -Algorithm MD5
Write-Output $hashLocal $url = "XXX"
#设置"-ExpandProperty"才能完全返回文本内容
$cotent = Invoke-WebRequest -Uri $url | select -ExpandProperty Content
#转化为Char数组,放到MemoryStream中
$charArray = $cotent.ToCharArray()
$stream = [System.IO.MemoryStream]::new($charArray)
#Get-FileHash还可以通过Stream的方式获取hash
$hashWeb = Get-FileHash -InputStream ($stream) -Algorithm MD5
#注意关闭MemoryStream
$stream.Close()
Write-Output $hashWeb $hashLocal.Hash -eq $hashWeb.Hash

2.逐行比较两个文件的内容是否相同

 $path = "C:\local.txt"
$url = "XXX"
$contentLocal = Get-Content $path
$cotentWeb = Invoke-WebRequest -Uri $url | select -ExpandProperty Content
$diff = Compare-Object -ReferenceObject $($contentLocal) -DifferenceObject $($cotentWeb)
if($diff) {
Write-Output "The content is not the same!"
}

发现运行结果不正确,调试发现 Get-Content(cat)返回值类型是System.Array ,而Invoke-WebRequest 返回值类型是 String

 PS C:\> $item1.GetType()

IsPublic IsSerial Name BaseType
-------- -------- ---- --------
True True Object[] System.Array

PS C:\> $item2.GetType()

IsPublic IsSerial Name BaseType
-------- -------- ---- --------
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!"
}

最新文章

  1. chpasswd命令
  2. 【转】算法杂货铺——k均值聚类(K-means)
  3. jquery 通过ajax FormData 对象上传附件
  4. Arduino学习经验(一)之解决舵机库和pwm输出冲突
  5. centos PIL 安装
  6. 22.访问者模式(Vistor Pattern)
  7. String类方法
  8. 一次PostgreSql数据迁移,使用nodejs来完成
  9. linux上配置subversion服务器端安装配置并使用svn,windows本地检出,设置同步更新服务器的钩子
  10. hdu-4833-Best-Financing(DP)
  11. CSS3的基础知识点
  12. Shopex如何清理缓存
  13. Oracle中的4大空值处理函数用法举例
  14. jsonp和CORS跨域实现
  15. android的listview以及画线--to thi tha
  16. window.onresize监听事件
  17. android编写测试类
  18. Android - Base64
  19. hadoop伪分布式环境搭建之linux系统安装教程
  20. CSS 鼠标样式

热门文章

  1. 芯片超Intel,盈利比肩Apple,三星成科技界"全民公敌"
  2. MVC EF 导航属性
  3. C# WindowsPrincipal(Windows规则)的使用
  4. HTTP、FTP状态码 汇总
  5. Qt4可以使用trUtf8函数,其内容可以是中文,也可以是\F硬编码
  6. 使用IntelliJ IDEA开发SpringMVC网站(五)博客文章管理
  7. C# TIFF图像开发
  8. 把BitmapSource图片数据保存到文件
  9. Windows 8各种流之间的转换
  10. seq2seq和Transformer