Link to home
Start Free TrialLog in
Avatar of WeTi
WeTi

asked on

Powershell scripting improvement Get-Childitem

Dear expert

I would like to improve code below. Right now if I don't write anything inside $Path and $String it will return a error message:
FindPattern : Cannot validate argument on parameter 'Path'. The argument is null or empty. Provide an argument that is not null or empty, and then try the command again.

Now I would like to add a if statement inside like this way: if ($Path -Or $String = $null) {$response}
Simply if variable $Path or $String is empty, go to do statement below or go to variable $response. Now I don't know if Im right about the statement or the execution with $response after but i need help with: where I put this if statement at best? And how will I write?

Thanks.

Function FindPattern {
Param(
	[Parameter(Position=0, Mandatory=$True)][ValidateNotNullOrEmpty()]
	[String]$Path,
	[Parameter(Position=1, Mandatory=$True)][ValidateNotNullOrEmpty()]
	[String]$String
)
	$Script:Results = $false
	Get-ChildItem -Path $Path -Recurse -File |
		Select-String -Pattern $String |
		Select-Object -Property Path, LineNumber, @{n='LWT'; e={
			Write-Progress -Activity "Searching for '$($Path)'" -Status $_.Path
			(Get-Item -Path $_.Path).LastWriteTime
			$Script:Results = $true
		}}
	If (-not $Script:Results) {
		Write-Host "Cannot find '$($String)' under '$($Path)'"
	}
	Write-Progress -Activity 'Done' -Status 'Done' -Completed
}

Do {
	FindPattern
	$response = Read-Host 'Search again?'
} Until ($response -ne 'Yes')

Open in new window

ASKER CERTIFIED SOLUTION
Avatar of oBdA
oBdA

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
SOLUTION
Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of WeTi
WeTi

ASKER

oBdA thanks for the kindly support again, it works as you said, well I got many test version of that code open so I simply picked a wrong one, the write-progress function should be in there.  question about the "::" what does that do?

Rastoi thanks for the effort by adding a text and provide the $ErrorActionPreference='SilentlyContinue'
trap {write-host "empty string is not allowed for parameters"} to me, however I would like the code to loop in cycle when  $response is Yes. So after that $ErrorActionPreference the action of the script seems stopped. But if there is other way for it to continue it would be good too.

Anyway the If ($Path -Or $String is $null) as I tried before it doesn't work that way or what?

Thanks again
The :: is PowerShell's way of invoking a static method ("IsNullOrEmpty") of a class ("string").

Oh, and "Trap" is deprecated. Try/Catch/Finally should be used to handle terminating errors.