如何使用PowerShell进行区分大小写的文件搜索?

时间:2014-10-17 19:26:23

标签: powershell search case-sensitive

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

找到 caps.txt 我想确保它只会找到 CAPS.txt (或<例如 CAPS901918.whatever

我已经尝试找到将Filter传递给表达式的方法:

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

或在收到结果后抑制输出,但我什么也没找到。

4 个答案:

答案 0 :(得分:5)

尝试将Get-Childitem加注到Where-Object,如下所示:

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

这里有类似的语法(谢谢FLGMwt)

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

答案 1 :(得分:3)

FileSystem提供程序的过滤器不区分大小写,但您可以将其传递给:

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

这将找到不包含小写字母的文件。如果你匹配大写字母,它将适用于任何至少有1个大写字母的文件,并且仍然可以包含小写字母。

答案 2 :(得分:1)

您可以为此

使用正则表达式选项
| Where{ $_.BaseName -match "(?-i)^[A-Z]+") }

或者

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

答案 3 :(得分:1)

这是一个很棒的小PowerShell应用程序,如果你感兴趣的话,我写的用于搜索和输出你在桌面上发现的日志文件的项目。

# 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