使用 powershell ; 从给定位置的文件夹,我想验证并显示特定文件类型的数量相应的文件夹

使用 powershell ; 从给定位置的文件夹,我想验证并显示特定文件类型的数量相应的文件夹

使用 powershell 从给定位置的文件夹,我想验证并显示各个文件夹中特定文件类型的数量。我尝试使用命令来计算文件夹中的文件数量,我能够获得指定位置可用的文件总数。我试过这个:

Write-Host ( Get-ChildItem -filter '*cab' 'C:\Users\praveen\Desktop\Package _Sprint04\Sprint04\lfp\Niagara\hpgl2\win2k_xp_vista').Count

if (Get-Process | ?{ $Count  -eq "13"})
{
    Write-Host "Number of CAB files are right!"
}
else
{ 
    Write-Host "Incorrect!! number of CAB file"
}

答案1

Get-Process不会给你带来任何结果。将 分配Count给一个变量并测试该变量的值是否为 13:

$cabFileCount = (Get-ChildItem -Filter "*.cab" "C:\path\to\folder").Count
Write-Host $cabFileCount

if($cabFileCount -eq 13){
    # Success!
    Write-Host "$cabFileCount files found, perfect!"
} else {
    # Failure!
    Write-Host "$cabFileCount files found, incorrect!"
}

答案2

试试这个。你可以将任意数量的文件夹、文件类型和文件计数添加到变量中$FoldersToCheck

# File to store log
$LogFile = '.\FileCount.log'

$FoldersToCheck = @(
    @{
        Path =  'C:\path\to\folder'
        FileType = '*.cab'
        FileCount = 13
    },
    @{
        Path =  'C:\path\to\folder\subfolder'
        FileType = '*.txt'
        FileCount = 14
    },
    @{
        Path =  'D:\path\to\some\other\folder'
        FileType = '*.log'
        FileCount = 15
    }
    # ... etc, add more hashtables for other folders
)

$FoldersToCheck | ForEach-Object {
    $FileCount = (Get-ChildItem -LiteralPath $_.Path -Filter $_.FileType | Where-Object {!($_.PSIsContainer)}).Count
    if ($FileCount -eq $_.FileCount)
    {
        $Result = "Success! Expected $($_.FileCount) file(s) of type $($_.FileType) in folder $($_.Path), found $FileCount files"
    }
    else
    {
       $Result = "Failure! Expected $($_.FileCount) file(s) of type $($_.FileType) in folder $($_.Path), found $FileCount files"
    }

    # Output result to file and pipeline
    $Result | Tee-Object -LiteralPath $LogFile
}

示例输出:

Success! Expected 13 file(s) of type *.cab in folder C:\path\to\folder, found 13 files
Failure! Expected 14 file(s) of type *.txt in folder C:\path\to\folder\subfolder, found 10 files
Failure! Expected 15 file(s) of type *.log in folder D:\path\to\some\other\folder, found 18 files

相关内容