I have powrshell script that check for .xml files, if founds – exit with 5, else exit with 0:
# Ensure the script is run as administrator
if (-not ([Security.Principal.WindowsPrincipal] [Security.Principal.WindowsIdentity]::GetCurrent()).IsInRole([Security.Principal.WindowsBuiltInRole] "Administrator"))
{
Write-Host "You need to run this script as an administrator."
exit 6
}
# Define the directories
$xmlRoot = "D:myFolder"
# Count xml files in all subdirectories
$xmlFiles = Get-ChildItem -Path $xmlRoot -Recurse -Filter *.xml
$xmlCount = $xmlFiles.Count
Write-Host "Total xml files found: $xmlCount"
if ($xmlCount -gt 0) {
exit 5
} else {
exit 0
}
in powershell, when i check the $LASTEXITCODE i do see 5,
but when I try to catch it in outer application (.bat for example) I don’t get error code:
@echo off powersheel "c:UserslocationcountXML.ps1" echo exit code is %LASTEXITCODE% pause
(I get “exit code is ” without any error code)
I tried:
- use “try–catch” and “throw” instead of exit
- use “return”
- run it without the “check admin” part
- use %ERRORLEVEL% in the bat (I get “exit code is 1”)
but nothing seems to help.
Thank you.
New contributor
user3170556 is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.