You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

PowerShell末尾ForEach循环无输出,求代码重构及按哈希降序排序方案

问题根源

  • 变量作用域错误:函数内赋值的$FileListOriginal、$FileListDestination为局部变量,函数外部的全局数组未被更新,最终遍历空数组无输出
  • 数组+=操作性能损耗大,文件数量多的场景下会严重拖慢执行速度
  • 自定义类声明冗余,PowerShell内置自定义对象可直接满足需求

重构后代码

$Source1 = 'C:\'
$Temp1 = 'H:\'

function Get-FileList {
    param(
        [string]$Path,
        [string]$Destination
    )
    # 收集源路径文件哈希信息
    $sourceFiles = Get-ChildItem -Recurse -File -Path $Path -ErrorAction SilentlyContinue | ForEach-Object {
        $hash = Get-FileHash $_.FullName
        [PSCustomObject]@{
            hash = $hash.Hash
            fullName = $hash.Path
        }
    }
    # 收集目标路径文件哈希信息
    $destFiles = Get-ChildItem -Recurse -File -Path $Destination -ErrorAction SilentlyContinue | ForEach-Object {
        $hash = Get-FileHash $_.FullName
        [PSCustomObject]@{
            hash = $hash.Hash
            fullName = $hash.Path
        }
    }
    # 直接返回两个数组,无需依赖全局变量
    return $sourceFiles, $destFiles
}

# 接收函数返回的两个数组
$FileListOriginal, $FileListDestination = Get-FileList -Path $Source1 -Destination $Temp1

# 按哈希值降序排序后输出
$sortedFileList = $FileListOriginal | Sort-Object hash -Descending
foreach ($object in $sortedFileList){
    Write-Output $object.hash
    Write-Output $object.fullName
}

修改说明

  • 取消冗余的自定义类声明,直接使用[PSCustomObject]生成结构化对象
  • 移除效率低下的+=数组追加操作,直接通过管道遍历输出结果自动生成数组
  • 调整变量作用域逻辑,函数直接返回结果数组,外部接收避免全局变量污染
  • 新增-ErrorAction SilentlyContinue参数跳过无权限访问的路径,避免脚本异常中断
  • 新增Sort-Object hash -Descending实现按哈希值降序排序的需求
  • 修正原脚本中大小写不统一的变量引用,规范写法更易维护

内容的提问来源于stack exchange,提问作者Syzard

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.30 09:36:04