PowerShell 2.0与5.0数据数组为空问题及修复求助
PowerShell 2.0中PSCustomObject数组筛选后无内容的解决办法
问题根源
PowerShell 2.0对[PSCustomObject]的支持不完善,用它创建的对象在通过Select-Object提取属性时,无法正确识别和传递属性值,导致生成的数组仅显示表头但无实际数据。此外,原代码中判断数组是否为空的方式$deletefiles -ne $null在PS2.0中不可靠——空数组仍会被判定为非null,可能导致后续逻辑执行异常。
解决方法
方法1:改用New-Object创建PSObject
在PS2.0中,New-Object PSObject是创建自定义对象的标准兼容方式,替换所有[PSCustomObject]的创建逻辑:
修改后的关键代码片段:
# 替换原$logEntry的创建 $logEntry = New-Object PSObject -Property @{ Filename = $file.name SourcefilePath = $sourceFilePath } $allsrcfiles += $logEntry # 替换原$deletelog的创建 $deletelog = New-Object PSObject -Property @{ Filename = $filetoremove SourceDirectory = $srcdir Filepath = $removepathfile Deleted = "Yes" } $deletelogs += $deletelog
方法2:跳过多余的Select-Object步骤
原代码中$deletefiles = $allsrcfiles | Select-Object Filename, SourcefilePath完全冗余,因为$allsrcfiles已经包含所需属性,直接使用原始数组即可:
# 移除Select-Object,直接赋值 $deletefiles = $allsrcfiles
补充:修正数组为空的判断逻辑
将原代码中的If ($deletefiles -ne $null)替换为判断数组元素数量,避免空数组误判:
If ($deletefiles.Count -gt 0)
完整修改后的代码示例
结合以上修改,适配PS2.0的完整代码如下:
$allowedExtensions = @("*.JPEG", "*.JPG", "*.PDF", "*.PPT", "*.DOCX", "*.XLSX", "*.XLS", "*.RTF", "*.PPTX", "*.DOC", "*.BMP", "*.PNG", "*.TXT", "*.ZIP", "*.XLSM") $filteredfiles = @() $sourcefiles = @() $allsrcfiles = @() $deletelogs = @() # PS2.0中Get-ChildItem无-File参数,用Where-Object过滤非文件夹 $sourcefiles = Get-ChildItem -Path $projectFolder.FullName -Recurse -Include $allowedExtensions | Where-Object {!$_.PSIsContainer} $filteredfiles = $sourcefiles | Select-Object Name, FullName If ($filteredfiles.Count -gt 0) { $filteredfiles | Export-Csv -Path $csvfilteredfiles -NoTypeInformation } foreach ($file in $filteredfiles) { if ($file.FullName.Length -gt 1) { $sourceFilePath = $file.FullName # 用New-Object创建兼容PS2.0的自定义对象 $logEntry = New-Object PSObject -Property @{ Filename = $file.name SourcefilePath = $sourceFilePath } $allsrcfiles += $logEntry } } # 直接使用原始数组,无需额外筛选 $deletefiles = $allsrcfiles If ($deletefiles.Count -gt 0) { Write-Host "Now removing copied file from: $sourcefolder" ForEach ($filedel in $deletefiles) { $filetoremove = $filedel.Filename $removepathfile = $filedel.SourcefilePath $srcdir = Split-Path -Parent $removepathfile try { Write-Host "Removing: $filetoremove from $srcdir ........" Remove-Item -Path $removepathfile -Force -WhatIf Write-Host "Removed file name: $removepathfile" -BackgroundColor Green $deletelog = New-Object PSObject -Property @{ Filename = $filetoremove SourceDirectory = $srcdir Filepath = $removepathfile Deleted = "Yes" } $deletelogs += $deletelog } catch { Write-Host "Problem Deleting file: $removepathfile" -BackgroundColor Red $errorcatch = $_.Exception.ToString() Write-Host "$errorcatch" } } }
内容的提问来源于stack exchange,提问作者Iain Howard
相关产品推荐
相关产品推荐

