首页 > 解决方案 > 如何更改我的代码以输出到控制台和 Powershell 中的输出日志?

问题描述

这是我在 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

标签: powershell

解决方案


"some text" | Tee-Object -Variable consoleOutput | Out-File "d:\logFileName.log"
Write-Host $consoleOutput

推荐阅读