I have researched this and found the following method works when detecting if a file has been created successfully or not.
Function createexceldoc {
$exceldoc = new-item -path C:\Holding -name ExcelTest3.xlsx -type file #-ea SilentlyContinue
if($? -eq 1 )
{
Write-Host “”
Write-Host " File Succesfully Created "
Write-Host “---------------------------------------------------------------”
}
Else
{
Write-Host “”
Write-Host " Function Failed to Create File"
Write-Host “--------------------------------------------------------------”
}
}
createexceldoc
I am trying to apply the same principle to a different function i have created. However i seem to be getting a false positive. Rather than giving me the appropriate message depending on if the script ran successfully or not, the error capture is returning whatever value i am checking the variable is equal to.
Write message if script has ran succesfully or not.
if($? -eq 0 )
{
Write-Host “”
Write-Host -BackgroundColor Yellow -ForegroundColor Black " Users Succesfully Created "
Write-Host “---------------------------------------------------------------”
}
Else
{
Write-Host “”
Write-Host -BackgroundColor red -ForegroundColor Black " Users Failed to be Created"
Write-Host “--------------------------------------------------------------”
}
I think the $? special variable isn’t passing the success/fail status of the function like i thought it would.
I have also tried placing the function in a variable and then passing that to the if statement wit the $LastExitCode to check the error status. This gives slightly different results in that i get the “Users Failed to be Created” message every time. Even when my script is run and ther users are created.
Any help greatly appreciated as always.