In previous techniques, you can observe that using "-ErrorAction Stop" combined with "Exception Capture Command" can catch an error in a Powershell command, but after using this method, the script will stop after the first error occurs.
Here is an example: Use Powershell to recursively scan folders. It will not complete catching all the exceptions in the middle (for example, some subfolders are access protected).
Copy the codeThe code is as follows:
try
{
Get-ChildItem -Path $env:windir -Filter *.ps1 -Recurse -ErrorAction Stop
}
catch
{
Write-Warning "Error: $_"
}
The code catches the first error, at which point the command will stop and will not continue to scan the remaining subfolders.
If you just suppress the error, you will complete the execution, but the "Exception Catch Command" will not catch any error messages.
Copy the codeThe code is as follows:
try
{
Get-ChildItem -Path $env:windir -Filter *.ps1 -Recurse -ErrorAction SilentlyContinue
}
catch
{
Write-Warning "Error: $_"
}
So if you want to execute continuously and get a directory that has no permissions to access, you don't need to use the "Exception Capture Command", you can specify variables to get all error reports:
Copy the codeThe code is as follows:
Get-ChildItem -Path $env:windir -Filter *.ps1 -Recurse -ErrorAction SilentlyContinue -ErrorVariable myErrors
Foreach ($incidence in $myErrors)
{
Write-Warning ("Unable to access " + $)
}