diff --git a/include/pgAgent.h b/include/pgAgent.h
index 1eef9be..966d212 100644
--- a/include/pgAgent.h
+++ b/include/pgAgent.h
@@ -54,7 +54,7 @@ void MainLoop();
 #ifdef __WIN32__
 #include <windows.h>
 void CheckForInterrupt();
-HANDLE win32_popen_r(const TCHAR *command);
+HANDLE win32_popen_r(const TCHAR *command, HANDLE &handle);
 #endif
 
 #endif // PGAGENT_H
diff --git a/job.cpp b/job.cpp
index a9c0c1b..f6e17ec 100644
--- a/job.cpp
+++ b/job.cpp
@@ -236,11 +236,11 @@ int Job::Execute()
 				// Execute the file and capture the output
 #ifdef __WIN32__
 				// The Windows way
-				HANDLE h_script;
+				HANDLE h_script, h_process;
 				DWORD dwRead;
 				char chBuf[4098];
 
-				h_script = win32_popen_r(filename.wc_str());
+				h_script = win32_popen_r(filename.wc_str(), h_process);
 				if (!h_script)
 				{
 					output.Printf(_("Couldn't execute script: %s, GetLastError() returned %d, errno = %d"), filename.c_str(), GetLastError(), errno);
@@ -264,8 +264,9 @@ int Job::Execute()
 				}
 
 
+				GetExitCodeProcess(h_process, (LPDWORD)&rc);
+				CloseHandle(h_process);
 				CloseHandle(h_script);
-				rc = 1;
 
 #else
 				// The *nix way.
@@ -295,10 +296,12 @@ int Job::Execute()
 				else
 					rc = -1;
 
-				// set success status for batch runs, be pessimistic bt default
+#endif
+
+				// set success status for batch runs, be pessimistic by default
+				LogMessage(wxString::Format(_("Script return code: %d"), rc), LOG_DEBUG);
 				if (rc == 0)
 					succeeded = true;
-#endif
 
 				// Delete the file/directory. If we fail, don't overwrite the script output in the log, just throw warnings.
 				if (!wxRemoveFile(filename))
diff --git a/win32.cpp b/win32.cpp
index a4a89f5..254f818 100644
--- a/win32.cpp
+++ b/win32.cpp
@@ -139,7 +139,7 @@ unsigned int __stdcall threadProcedure(void *unused)
 // _popen doesn't work in Win2K from a service so we have to
 // do it the fun way :-)
 
-HANDLE win32_popen_r(const TCHAR *command)
+HANDLE win32_popen_r(const TCHAR *command, HANDLE &handle)
 {
 	HANDLE hWrite, hRead;
 	SECURITY_ATTRIBUTES saAttr;
@@ -185,16 +185,13 @@ HANDLE win32_popen_r(const TCHAR *command)
 	if (!ret)
 		return NULL;
 	else
-	{
-		CloseHandle(piProcInfo.hProcess);
 		CloseHandle(piProcInfo.hThread);
-	}
-
 
 	// Close the write end of the pipe and return the read end.
 	if (!CloseHandle(hWrite))
 		return NULL;
 
+	handle = piProcInfo.hProcess;
 	return hRead;
 }
 
