diff --git a/ProcessWin32.c b/ProcessWin32.c
index 77c57c074815009ae00707c3009c7fc845eb6af7..5d5c680a54fb6ab5a5ae21bb8636d008781792a9 100644
--- a/ProcessWin32.c
+++ b/ProcessWin32.c
@@ -1237,9 +1237,42 @@ void kwsysProcessCleanup(kwsysProcess* cp, int error)
   /* If this is an error case, report the error.  */
   if(error)
     {
-    FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS,
-                  0, GetLastError(), MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
-                  cp->ErrorMessage, CMPE_PIPE_BUFFER_SIZE, 0); 
+    /* Format the error message.  */
+    DWORD original = GetLastError();
+    DWORD length = FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM |
+                                 FORMAT_MESSAGE_IGNORE_INSERTS, 0, original,
+                                 MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
+                                 cp->ErrorMessage, CMPE_PIPE_BUFFER_SIZE, 0);
+    
+    if(length > 0)
+      {
+      /* Remove trailing period and newline, if any.  */
+      if(cp->ErrorMessage[length-1] == '\n')
+        {
+        cp->ErrorMessage[length-1] = 0;
+        --length;
+        if(length > 0 && cp->ErrorMessage[length-1] == '\r')
+          {
+          cp->ErrorMessage[length-1] = 0;
+          --length;
+          }
+        }
+      if(cp->ErrorMessage[length-1] == '.')
+        {
+        cp->ErrorMessage[length-1] = 0;
+        --length;
+        }
+      }
+    else
+      {
+      /* FormatMessage failed.  Use a default message.  */
+      _snprintf(cp->ErrorMessage, CMPE_PIPE_BUFFER_SIZE,
+                "Process execution failed with error 0x%X.  "
+                "FormatMessage failed with error 0x%X.",
+                original, GetLastError());
+      }
+    
+    /* Set the error state.  */
     cp->State = kwsysProcess_State_Error;
     }