我是一个powershell的新手,为什么下面的代码也在“要删除的文件”循环的末尾输出表呢?
$stopwatch = [System.Diagnostics.Stopwatch]::StartNew()
# use partial hashes for files larger than 100KB:
# see documentation at: https://powershell.one/tricks/filesystem/finding-duplicate-files#finding-duplicate-files-fast
$result = Find-PSOneDuplicateFileFast -Path '\\READYNAS\Pictures\2020\10' #-Debug -Verbose
$stopwatch.Stop()
# output duplicates
$allFilesToDelete = @(foreach($key in $result.Keys)
{
#filters out the LAST item in the array of duplicates, because a file name of xxxx (0) comes before one without the (0)
$filesToDelete = $result[$key][0..($result[$key].count - 2)]
#add each remaining duplicate file to table
foreach($file in $filesToDelete)
{
$file |
Add-Member -MemberType NoteProperty -Name Hash -Value $key -PassThru |
Select-Object Hash, Length, FullName
}
}
)
$allFilesToDelete | Format-Table -GroupBy Hash -Property FullName | Out-String | Write-Host
$allFilesToDelete | Sort-Object -Property FullName -OutVariable allFilesToDelete
$allFilesToDelete | Format-Table -Property FullName | Out-String | Write-Host
$confirmation = Read-Host "Are you Sure You Want To Delete $($allFilesToDelete.count) files? (y/n)"
if ($confirmation -eq 'y') {
$i = 0
foreach($fileToDelete in $allFilesToDelete)
{
$i++
Write-Host "$i File to Delete: $($fileToDelete.FullName)"
#Remove-Item $file.FullName -Force -Verbose 4>&1 | % { $x = $_; Write-Host "Deleted file ($i) $x" }
}
} else {
Write-Host "User chose NOT to delete files!"
}
1条答案
按热度按时间zbdgwd5y1#
$allFilesToDelete | Sort-Object -Property FullName -OutVariable allFilesToDelete
产生output(按请求的排序顺序的输入对象),由于您没有捕获或重定向它,因此默认情况下它打印到 host(显示器、终端)。$allFilesToDelete
中的对象进行排序,您的命令确实如此,但它 * 还 * 产生输出(公共-OutVariable
参数 * 不 * 影响cmdlet的输出行为,它只是 * 还 * 将输出对象存储在给定变量中);你可以简单地把输出赋值回原来的变量,这样就不会产生任何输出:$null = ...
**是最简单的解决方案:*由于输出结果是 * 隐式 *
Format-Table
的显示模式(对于没有预定义格式数据的自定义对象),后续的Read-Host
和Write-Host
语句令人惊讶地打印出 first。Format-Table
的这种隐式使用会导致 * 异步 * 行为:输出对象收集300毫秒,以确定合适的列宽,并且在此期间可以打印输出到 otheroutput streams。Out-Host
强制管道输出 * 同步 * 打印到主机(显示器)。