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?

[Product update] Infrastructure Analysis Tool is now available with Business Accounts.Learn More

x
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

oBdACommented:
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

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
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
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
Powershell

From novice to tech pro — start learning today.