powershell - Powershell 比较两个 List 和 foreach
问题描述
我正在尝试比较使用Get-ChildItem
cmdlet 获得的两个列表。
我阅读了有关Compare-Object
cmdlet 的信息,但在这种情况下,我更喜欢使用 foreach,因为它对访问$file
变量很有用。
$StartingFolderPath = "C:\---\StartingFolder"
$EndingFolderPath = "C:\---\EndingFolder"
$AllStartingFiles = Get-ChildItem $StartingFolderPath
$AllEndingFiles = Get-ChildItem $EndingFolderPath
Write-Host "First folder content:"$AllStartingFiles
Write-Host "Second folder content:" $AllEndingFiles
foreach($file in $AllEndingFiles){
write-Host "Element :" $file.Name
$result = $AllStartingFiles.Contains($file.Name)
write-host $result
if($AllStartingFiles.Contains($file.Name)){
Write-Host "You are here"
Write-Host $file.Name
}
}
但似乎我无法通过if($AllStartingFiles.Contains($file.Name))
返回 false 的 if 控件。
输出
First folder content: 1_one.txt 2_two.txt 3_three.txt 5_five.txt
Second folder content: 1_one.txt 2_two.txt 3_three.txt 4_four.txt 5_five.txt
6_six.txt
Element : 1_one.txt
False
Element : 2_two.txt
False
Element : 3_three.txt
False
Element : 4_four.txt
False
Element : 5_five.txt
False
Element : 6_six.txt
False
我也尝试过-Contains
操作员,但没有任何运气。
解决方案
您在期间没有解决该Name
属性
$result = $AllStartingFiles.Contains($file.Name)
正确的方法是:
$result = $AllStartingFiles.Name.Contains($file.Name)
如果只是不想使用Compare-Object
,因为你害怕你会丢失文件属性,但事实并非如此。
Compare-Object -ReferenceObject $AllEndingFiles -DifferenceObject $AllStartingFiles -IncludeEqual -ExcludeDifferent | Select-Object -ExpandProperty InputObject
这将为您提供出现在列表及其属性中的所有文件。
推荐阅读
- html - 如何删除中间的空白
- s,使用 list-group-horizontal (boostrap 4)?
- javascript - 如何检查管道的变化?角文本区域
- dart - 导航器弹出错误直到:“!_debugLocked':不正确。”
- azure-active-directory - AAD:防止帐户选择器
- reactjs - 如何将 fontSize 应用于 MUI 中的 CardHeader 标题?
- swift - 斯威夫特,如何让完成处理程序按我的意愿工作?
- javascript - 如何在chartjs的替代列表中使用alpha vantage api?
- php - 登录表单准备好的语句不起作用
- php - Laravel 搜索查询分页 - 第 2 页返回错误“localhost 重定向太多次”
- c# - 为什么此项目需要程序集绑定重定向?