Powershell, look through all drives

坚强是说给别人听的谎言 提交于 2021-02-05 09:03:53

问题


I'm new to Powershell and I've tried finding a solution to my problem online but I can't seem to find one. Basically I need to write something that will let powershell look through all drives and directories to find the following:

total number of files (exclude folders), largest file size, average file size, total file size

Here's what I've written so far:

$source = "get-psdrive"

#attempt at looking through all drives/directories which didn't work
foreach($a in $source) {

    #counts files in given directory
    Get-ChildItem -Recurse -File -ErrorAction SilentlyContinue -Force |
        Measure-Object |
        ForEach-Object { $_.Count }

    #select largest file in given directory
    Get-ChildItem -Recurse -File -ErrorAction SilentlyContinue -Force |
        Sort-Object Length -Descending |
        Select-Object -First 1

    #get average file size in a given directory
    Get-ChildItem -Recurse -File -ErrorAction SilentlyContinue -Force |
        Measure-Object -Property Length -Average

    #sum of file sizes in given directory
    (Get-ChildItem -Recurse -File -ErrorAction SilentlyContinue -Force |
        Measure-Object -Sum Length).Sum
}

The issue is that it only looks in the C drive. I don't know if there's a way to look through my computer instead of specific drives but I couldn't seem to find a way. Any help is appreciated.


回答1:


With "..." you define a string, so in your example you try to loop over a string.

Try it like this:

$Drives = Get-PSDrive -PSProvider 'FileSystem'

foreach($Drive in $drives) {

    #counts files in given directory
    Get-ChildItem -Path $Drive.Root -Recurse -File -ErrorAction SilentlyContinue -Force |
        Measure-Object |
        ForEach-Object { $_.Count }

    #select largest file in given directory
    Get-ChildItem -Path $Drive.Root -Recurse -File -ErrorAction SilentlyContinue -Force |
        Sort-Object Length -Descending |
        Select-Object -First 1

    #get average file size in a given directory
    Get-ChildItem -Path $Drive.Root -Recurse -File -ErrorAction SilentlyContinue -Force |
        Measure-Object -Property Length -Average

    #sum of file sizes in given directory 
    (Get-ChildItem -Path $Drive.Root -Recurse -File -ErrorAction SilentlyContinue -Force |
        Measure-Object -Sum Length).Sum

}

Note! I didn't chang your Get-ChildItem code (except the path where it will search). I only wrote the foreach loop.



来源:https://stackoverflow.com/questions/44911486/powershell-look-through-all-drives

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!