I have the following error in my powershell code and I want to replace it with a warning. Here is the error and my function.
gci : Access to the path 'C:UsersUser1AppDataLocalHistory' is denied.
At line:10 char:18
+ ... $files = gci -File -Rec -Path $path -Force -Exclude *.ps1,*.psm1,* ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : PermissionDenied: (C:UsersUser1...LocalHistory:String) [Get-ChildItem], UnauthorizedAccessException
+ FullyQualifiedErrorId : DirUnauthorizedAccessError,Microsoft.PowerShell.Commands.GetChildItemCommand
Here is my Function:
Function Find-ReplaceAll {
Param(
[string] $path,
[string] $stringFind,
[string] $stringReplace
#[parameter( Mandatory = $false )]
#[string[]] $exclude = "*.ps1,*.psm1,*.psd1,*.cmd,*.vbs"
)
try{
$files = gci -File -Rec -Path $path -Force -Exclude *.ps1,*.psm1,*.psd1,*.cmd,*.vbs
foreach ($file in $files){
$count += $file.count
write-host "Checking file: $($file.fullname)"
(Get-Content -path ($file.FullName) -ReadCount 100) |
ForEach-Object {
$_ -replace $stringFind, $stringReplace} |
Set-Content -path $file.FullName -force
}
}catch{
[DirUnauthorizedAccessExceptionError]
write-warning -Message "Can't access location. Access is denied."
}
}
I’ve tried to catch UnauthorizedAccessException as well but that didn’t work either.
I’m also trying to figure out how to use $exclude as a string param for my function.