Deploying Microsoft Outlook

How to return Error codes on Scripts?

Description

Every command or script returns with the status of execution, which is referred as return status or exit codes. A successful command returns a 0 while an unsuccessful one returns a non-zero value that usually can be interpreted as an Error Code. The last command executed in the function or the script determines the exit status. This document provides steps on how to return the error codes on .vb scripts, Powershell scripts and batch files.

Steps

Exit codes for batch files

Use the command EXIT /B %ERRORLEVEL% at the end of the batch file to return the error codes from the batch file

  • EXIT /B at the end of the batch file will stop execution of a batch file.
  • use EXIT /B < exitcodes > at the end of the batch file to return custom return codes.
  • Environment variable %ERRORLEVEL% contains the latest errorlevel in the batch file,which is the latest error codes from the last command executed. To know about Environment variable see the below note.
Note:Environment variables are a set of dynamic named values that can affect the way, running processes will behave on a computer. For example, an environment variable with a standard name can store the location that a particular computer system uses to store user profile this may vary from one computer system to another.

In the batch file , it is always a good practice to use environment variables instead of constant values. Since the same variable get expanded to different values on different computers.

Example:

Batch file for Copying File to a Folder
md "C:manageengine"
copy "\\sharename\foldername\samplefile.txt" "C:\manageengine"
exit /b %ERRORLEVEL%

Exit codes for powershell script

Use the command Exit $LASTEXITCODE at the end of the powershell script to return the error codes from the powershell script.

  • $LASTEXITCODE holds the last error code in the powershell script. It is in form of boolean values, with 0 for success and 1 for failure.
  • Exit <custom error codes> will return custom return codes from the script

Example:

Powershell script for copying file to a folder
$dest ="C: est"
New-Item $dest -type directory -force
$source ="c:samplefile.txt"
Copy-Item $source $dest
exit $LASTEXITCODE

Exit codes for vb script

Use wscript.quit Err.Number at the end of the vb script which will return the last error codes from the script

  • Err.Number holds the last error code in the script.
  • wscript.quit <custom error codes> will return custom return codes from the script

Example:
vb script for Copying File to a Folder

dim filesys
set filesys=CreateObject("Scripting.FileSystemObject")
If filesys.FileExists("c:\samplefile.txt") Then
filesys.CopyFile "c:\samplefile.txt", "C:\manageengine"
End If
wscript.quit Err.number

Remote Desktop & Mobile Device Management Software for MSPs trusted by