From a4cdb806f429facda1dee6f41647f5722c5d611b Mon Sep 17 00:00:00 2001 From: Ilya Date: Fri, 15 Sep 2017 01:57:17 +0400 Subject: [PATCH] Exclude directories discovered from '-Path' in Select-String (#4829) Select-String can search in files only so we should skip directories. --- .../commands/utility/MatchString.cs | 5 +++++ .../Microsoft.PowerShell.Utility/string.tests.ps1 | 13 +++++++++++++ 2 files changed, 18 insertions(+) diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/MatchString.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/MatchString.cs index 5cc6d26738..88fac123a4 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/MatchString.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/MatchString.cs @@ -1347,6 +1347,11 @@ namespace Microsoft.PowerShell.Commands { foreach (string filename in expandedPaths) { + if (Directory.Exists(filename)) + { + continue; + } + bool foundMatch = ProcessFile(filename); if (_quiet && foundMatch) return; diff --git a/test/powershell/Modules/Microsoft.PowerShell.Utility/string.tests.ps1 b/test/powershell/Modules/Microsoft.PowerShell.Utility/string.tests.ps1 index f31b2d1fdc..4d3eb7df81 100644 --- a/test/powershell/Modules/Microsoft.PowerShell.Utility/string.tests.ps1 +++ b/test/powershell/Modules/Microsoft.PowerShell.Utility/string.tests.ps1 @@ -9,6 +9,11 @@ $fileNameWithDots = $fileName.FullName.Replace("\", "\.\") + $subDirName = Join-Path $TestDrive 'selectSubDir' + New-Item -Path $subDirName -ItemType Directory -Force > $null + $pathWithoutWildcard = $TestDrive + $pathWithWildcard = Join-Path $TestDrive '*' + $tempFile = New-TemporaryFile "abc" | Out-File -LiteralPath $tempFile.fullname "bcd" | Out-File -LiteralPath $tempFile.fullname -Append @@ -24,6 +29,14 @@ Pop-Location } + It "Select-String does not throw on subdirectory (path without wildcard)" { + { select-string -Path $pathWithoutWildcard "noExists" -ErrorAction Stop } | Should Not Throw + } + + It "Select-String does not throw on subdirectory (path with wildcard)" { + { select-string -Path $pathWithWildcard "noExists" -ErrorAction Stop } | Should Not Throw + } + It "LiteralPath with relative path" { (select-string -LiteralPath (Get-Item -LiteralPath $fileName).Name "b").count | Should Be 2 }