Go Premium for a chance to win a PS4. Enter to Win

x
  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 566
  • Last Modified:

Powershell Script Return Integer for IF Statement

I need to write a script that will return an exit code (preferrably a 1 or a 0) on the success or failure of a cmdlet.  Then, I need to write an IF statement that takes certain actions based on the success or failure of the first cmdlet.  For example, if the cmdlet completes successfully, I want to delete a certain file.  If it encounters an error, I want it to write an entry in a log.
0
marrj
Asked:
marrj
  • 2
3 Solutions
 
sirbountyCommented:
Use LastExitCode variable...
#your code...
#if success, $result=0
#else $result=1
exit $result

if ($lastexitcode -eq 0) {
#code to run for success
} else {
#code to run for failure
} 

Open in new window

0
 
SubsunCommented:
Better try with $?
if ($?) {
#code to run for success
} else {
#code to run for failure
}

Open in new window

If I am not wrong, $LastExitCode returns exit code of native applications. If you use $?, then it returns True or False based on last command result. It works for both CMDlet and native applications..
0
 
paultomasiCommented:
This should do the trick nicely

@echo off

set logfile=logfile.txt
set filetodelete=filetodelete.txt

if "%~1" equ "/?" goto :help

if not "%~1" equ "" (
  set cmdlet=%*
) else (
  set /p cmdlet="Enter name of CMDlet to run: "
)

call %cmdlet% 2>nul
set errorcode=%errorlevel%

if %errorcode% equ 0 (
  del "%filetodelete%" 2>nul
) else (
  echo %date% %time% Error executing %cmdlet%>>"%logfile%"
)

exit /b %errorcode%

:help
echo.
echo Syntax: %0 command
echo Where 'command' is the CMDlet to execute.
echo.
echo If CMDlet runs successfully, file %filetodelete% is deleted
echo If CMDlet does not run successfully, log written to %logfile%
echo.

Open in new window

0
 
paultomasiCommented:
Thank you
0

Featured Post

New feature and membership benefit!

New feature! Upgrade and increase expert visibility of your issues with Priority Questions.

  • 2
Tackle projects and never again get stuck behind a technical roadblock.
Join Now