More improvement of get-childitem powershell

Dear expert

The script below works very good, but I would like to improve it more, now I seen that when I search under c:\ and it loaded alot error messages of c:\windows\system32 folder cannot be accessed because the permission is not set, well its correct due to the win10 security, now I don't like it to show me those error messages so I put in -ErrorAction SilentlyContinue and then the red message disappeared, great I thought, well then I thought... nope, its not that great, why? now users(me) who run this script for finding the string, if it find some subfolder that didn't have permission and it just jumped over that folder without users noticing it, the result will be not right, it will show, the search complete with no string found but it actually passed those non-permit folders without notice... Now I want it to show the error message, but not very long messages, just one line red text output: Cannot access to path.

Any idea? Thanks

Function FindPattern {
Param(
	[Parameter(Position=0, Mandatory=$True)][ValidateNotNullOrEmpty()]
	[String]$Path,
	[Parameter(Position=1, Mandatory=$True)][ValidateNotNullOrEmpty()]
	[String]$Pattern
)
	$Script:Results = $false
	$AllItems = Get-ChildItem -Path $Path -Recurse -File -ErrorAction SilentlyContinue | Select-Object -Property Fullname, LastWriteTime 
	$Index = 0
	$AllItems | ForEach-Object {
		$item = $_
		Write-Progress -Activity "Searching '$($Pattern)'" -Status $item.FullName -PercentComplete ((100 * $Index++) / $AllItems.Count)
		Select-String -Path $item.FullName -Pattern $Pattern |
			Select-Object -Property Path, LineNumber, @{n='LWT'; e={
				$item.LastWriteTime
				$Script:Results = $true
			}}
	}
	If (-not $Script:Results) {
		Write-Host "Cannot find $($Pattern) under $($Path)" -ForegroundColor Red
	}
	Write-Progress -Activity 'Finished' -Status 'Finished' -Completed
}

Do {
	$Path = Read-Host 'Path'
	If (-not [string]::IsNullOrEmpty($Path)) {
		If (Test-Path -Path $Path) {
			$Pattern = Read-Host 'String'
			If (-not [string]::IsNullOrEmpty($Pattern)) {
				FindPattern -Path $Path -Pattern $Pattern
                Write-Host "Searching done." -ForegroundColor Green
			} Else {
				Write-Host "Path or String cannot be empty" -ForegroundColor Red
			}
		} Else {
			Write-Host "Path '$($Path)' cant find" -ForegroundColor Red
		}
	} Else {
		Write-Host "Path cannot be empty!" -ForegroundColor Red
	}
	$response = Read-Host 'Search again?'
} Until ($response -ne 'Yes') 

Open in new window

LVL 1
WeTiAsked:
Who is Participating?
 
oBdAConnect With a Mentor Commented:
Note: I will continue to rename the function to meet PowerShell standards. If you're trying to learn PowerShell, get used to best practices right from the beginning.
On a side note: I was now able to reproduce the issue you came across earlier where the output was swallowed by the Read-Host, and only appeared after responding. That is fixed by the " | Out-Host" at the end of line 37 (but prevents redirecting the output to a file).
On a side note: you can replace the "Out-Host" there with "Out-GridView", which will present the results in a GUI table.
Function Find-Pattern {
Param(
	[Parameter(Position=0, Mandatory=$True)][ValidateNotNullOrEmpty()]
	[String]$Path,
	[Parameter(Position=1, Mandatory=$True)][ValidateNotNullOrEmpty()]
	[String]$Pattern
)
	$Script:Results = $false
	$Skipped = $Null
	Write-Host "Scanning '$($Path)' ..."
	$AllItems = Get-ChildItem -Path $Path -Recurse -File -ErrorAction SilentlyContinue -ErrorVariable Skipped | Select-Object -Property Fullname, LastWriteTime 
	$Skipped | ForEach-Object {
		Write-Host $_.Exception.Message -ForegroundColor Red
	}
	$Index = 0
	$AllItems | ForEach-Object {
		$item = $_
		Write-Progress -Activity "Searching '$($Pattern)'" -Status $item.FullName -PercentComplete ((100 * $Index++) / $AllItems.Count)
		Select-String -Path $item.FullName -Pattern $Pattern |
			Select-Object -Property Path, LineNumber, @{n='LWT'; e={
				$item.LastWriteTime
				$Script:Results = $true
			}}
	}
	If (-not $Script:Results) {
		Write-Host "Cannot find $($Pattern) under $($Path)" -ForegroundColor Red
	}
	Write-Progress -Activity 'Finished' -Status 'Finished' -Completed
}

Do {
	$Path = Read-Host 'Path'
	If (-not [string]::IsNullOrEmpty($Path)) {
		If (Test-Path -Path $Path) {
			$Pattern = Read-Host 'String'
			If (-not [string]::IsNullOrEmpty($Pattern)) {
				Find-Pattern -Path $Path -Pattern $Pattern | Out-Host
				Write-Host "Searching done." -ForegroundColor Green
			} Else {
				Write-Host "Pattern cannot be empty." -ForegroundColor Red
			}
		} Else {
			Write-Host "Path '$($Path)' cannot be found." -ForegroundColor Red
		}
	} Else {
		Write-Host "Path cannot be empty." -ForegroundColor Red
	}
	$response = Read-Host 'Search again?'
} Until ($response -ne 'Yes')

Open in new window

1
 
WeTiAuthor Commented:
Hi oBdA, thanks again! Its not a problem if you wanna change the variable name to standard one. But the result is still the same, red standard error messages... Instead showing this red standard warning text, i wanna shorten it to one line: path permission denied?
0
 
WeTiAuthor Commented:
+ CategoryInfo          : PermissionDenied: (C:\Windows\System32\sru:String) [Get-ChildItem], UnauthorizedAccessException
    + FullyQualifiedErrorId : DirUnauthorizedAccessError,Microsoft.PowerShell.Commands.GetChildItemCommand

This is the error.
0
 
WeTiAuthor Commented:
I want to catch it and reformat it with simple error line: Permission Denied of "Path" without stopping the do loop.
0
 
WeTiAuthor Commented:
it works, i missed the $Skipped variable line, thanks again oBdA, and your -ErrorVariable Skipped and the Write-Host $Skipped.Exception.Message -ForegroundColor Red line...
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.