【发布时间】:2020-12-22 20:35:12
【问题描述】:
这是我在 Powershell 中编写的第一件事(我更喜欢 VBA 人),如果您发现它有很多问题,请原谅。我真的只是在即兴发挥,所以非常感谢任何帮助。
我为我的工作制作了这个,基本上是抓取主要的子文件夹并吐出它们的大小、文件数和文件夹数。它工作得很好,输出日志按照我想要的方式出现。我希望它在控制台和输出日志中更新,因为我们经常检查大文件夹,所以它可能需要一些时间,所以我想让人们看到它在每个文件夹中更新。但是,我想不通。
我看到也许Tee-Object 可以/应该使用,但我不太清楚如何将它与我想要输出的所有行合并。我想输出的每一行都带有echo 命令。 Write-Host 似乎只有在我禁用日志时才有效。
这是我的代码:
While ($true){
$startDirectory = Read-Host "Enter path/directory"
if (Test-Path -Path $startDirectory) { break }
Write-Host "Wrong path. Please try again" -ForegroundColor Red
}
Write-Host ""
Write-Host "Getting information..." -ForegroundColor Green
Write-Host "This can take a while if the selected directory is large and/or contains a lot of files. An output log will be created at the end."
Write-Host ""
$directoryItems = Get-ChildItem $startDirectory | Where-Object {$_.PSIsContainer -eq $true} | Sort-Object
$ParentFileSize = 0
$TotalFiles = 0
$TotalFolders = 0
$SubFileCount = 0
$SubFolderCount = 0
$SubFileSize = 0
$TotalSize = 0
$Tab = [char]9
$(
echo "Output file generated to: $env:USERPROFILE\Desktop\Output.txt" " "
echo "List of Folders in '$startDirectory'" " "
echo "Size (GB): $Tab Files: $Tab Folders: $Tab Folder Name:" " "
$ParentFileCount = (Get-ChildItem $startDirectory -File).Count
$ParentFolderCount = (Get-ChildItem $startDirectory -Directory).Count
$ParentFileSize = Get-ChildItem $startDirectory -File | Measure-Object -property Length -sum | Select-Object Sum
$ParentFileSize = "{0:N2}" -f ($ParentFileSize.sum / 1GB)
foreach ($i in $directoryItems)
{
$subFolderItems = Get-ChildItem $i.FullName -recurse -force | Where-Object {$_.PSIsContainer -eq $false} | Measure-Object -property Length -sum | Select-Object Sum
$FolderSize = "{0:N2}" -f ($subFolderItems.sum / 1GB)
$FileCount = Get-ChildItem $i.FullName -Recurse -File | Measure-Object | %{$_.Count}
$FolderCount = Get-ChildItem $i.FullName -Recurse -Directory | Measure-Object | %{$_.Count}
echo "$FolderSize $Tab $Tab $FileCount $Tab $Tab $FolderCount $Tab $Tab $i"
$SubFileCount = $SubFileCount + $FileCount
$SubFolderCount = $SubFolderCount + $FolderCount
$SubFileSize = $SubFileSize + $FolderSize
}
$TotalFolders = $SubFolderCount + $ParentFolderCount
$TotalFiles = $SubFileCount + $ParentFileCount
$TotalSize = $SubFileSize + $ParentFileSize
$TotalSize = "{0:N2}" -f ($TotalSize)
$SubFileSize = "{0:N2}" -f ($SubFileSize)
echo " " " " "Total in '$startdirectory':" " "
echo "Size: $TotalSize GB ($SubFileSize GB in sub-folders)" "Files: $TotalFiles ($SubFileCount in sub-folders)" "Folders: $TotalFolders ($SubFolderCount in sub-folders)"
) *>&1 > $env:USERPROFILE\Desktop\Output.txt
Invoke-Item $env:USERPROFILE\Desktop\Output.txt
【问题讨论】:
-
Write-Host不写入控制台的原因是因为在 Windows PowerShell v5+ 中它使用信息流。这意味着*>&1将write-host重定向到成功流,该成功流将重定向到您的文件。如果您只想捕获成功和错误,那么2>&1将在控制台显示write-host输出时这样做。
标签: powershell