How to do a case-sensitive file search with PowerShell?

跟風遠走 提交于 2019-12-13 14:48:58

问题


Get-ChildItem -Path C:\ -Filter CAPS*

finds caps.txt I want to make sure it will only find CAPS.txt (or e.g. CAPS901918.whatever)

I've tried find ways to pipe the Filter to an expression like:

{ $_.What_I_just_said_to_filter_on -like [A-Z] }

or suppress output after receiving results but I have found nothing.


回答1:


try piping Get-Childitem to Where-Object like this:

Get-Childitem -Path C:\ | Where-Object {$_.what_you_want_to_filter -match "REGEX"}

here it is with like syntax (thanks FLGMwt)

Get-Childitem -Path C:\ | Where-Object {$_.Name -clike "CAPS*"}



回答2:


The FileSystem provider's filter is not case sensitive, but you can pipe it to:

Where{-NOT ($_.BaseName -cmatch "[a-z]")}

That will find files that do not contain lower case letters. If you match against upper case it will work for any file that has at least 1 capital letter, and can still include lower case.




回答3:


You can use regex option for this

| Where{ $_.BaseName -match "(?-i)^[A-Z]+") }

Or

| Where{ $_.BaseName -cmatch "^[A-Z]+"}



回答4:


Here's a nice little powershell app I wrote for searching and outputting item's it found to a log file on your desktop if you're interested.

# Creates Log File
function Create-MyLog()
{
    Clear-Host
    New-Item -Path "C:\Users\$env:USERNAME\Desktop\" -Name "MyLogFile.txt" -ItemType file -Force
    Clear-Host
    Smart-Search
}

# Gather Search And Execute
function Smart-Search()
{   
    Clear-Host
    $LogFilePath = "C:\Users\$env:USERNAME\Desktop\"
    $TestInput = Read-Host 'What Would You Like To Search'
    $TestSearch = $TestInput + "*"
    $MyLogFile = ($LogFilePath + "MyLogFile.txt")
    Set-Location "C:\"
    $itemSum = Get-ChildItem -Recurse -ErrorAction SilentlyContinue
        Foreach($itemInst in $itemSum)
            {
                if(($itemInst.Name -clike $TestSearch) -eq $true)
                    {
                        $itemInst.FullName | Out-File -LiteralPath $MyLogFile -Append
                    }
                elseif($itemInst -eq $null)
                    {
                        Write-Host "Search Error On searchInst Is Null"
                    }
            }
        Search-Again
}

# Ask If User Wants To Search Again
function Search-Again()
{
    $userAnswer = Read-Host 'Would You Like To Search Again? y/n'
        switch($true)
            {
                ($userAnswer -eq "y"){Smart-Search};
                ($userAnswer -eq "n"){};
                default{Write-Host "Invalid Response"; Search-Again};
            }
}
Create-MyLog


来源:https://stackoverflow.com/questions/26432076/how-to-do-a-case-sensitive-file-search-with-powershell

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