【问题标题】:Powershell, look through all drivesPowershell,查看所有驱动器
【发布时间】:2021-04-06 16:54:36
【问题描述】:

我是 Powershell 新手,我尝试在网上找到解决问题的方法,但似乎找不到。基本上我需要写一些东西,让 powershell 查看所有驱动器和目录以找到以下内容:

文件总数(不包括文件夹)、最大文件大小、平均文件大小、总文件大小

这是我目前所写的:

$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
}

问题是它只在 C 盘中查找。我不知道是否有办法查看我的计算机而不是特定的驱动器,但我似乎找不到办法。任何帮助表示赞赏。

【问题讨论】:

  • foreach($a in $source) -> foreach($a in & $source);要执行名称存储在字符串中的命令,您必须使用调用运算符&。此外,您的 Get-ChildItem 命令实际上并未引用手头的驱动器 $a

标签: powershell recursion


【解决方案1】:

使用"...",您定义了一个字符串,因此在您的示例中,您尝试循环遍历一个字符串。

试试这样:

$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

}

注意!我没有更改您的Get-ChildItem 代码(搜索路径除外)。我只写了foreach 循环。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-10-07
    • 2012-08-07
    • 1970-01-01
    • 2014-12-01
    相关资源
    最近更新 更多