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