John Evans Solachuk
John Evans Solachuk

Reputation: 2105

How to capture powershell error in batch scripts?

Currently, I'm using this script to convert a date in yyyyMMdd format to dd/MM/yyyy format.

for /f "delims=" %%a in ('powershell -Command "& {([datetime]::parseexact('%testDate%','yyyyMMdd',[System.Globalization.CultureInfo]::InvariantCulture)).ToString('dd/MM/yyyy')}"') do SET testDate=%%a

When I input invalid characters/date-time structure for the %testDate% variable, in Powershell IDE, it throws an error message, "String was not recognized as a valid DateTime".

However, in batch scripts, it will only return an empty testDate variable. It also returns errorlevel = 0.

How do I return the error message from powershell in batch scripts?


Full script

@echo off
setlocal enabledelayedexpansion
REM Get user's inputs
:beginning
SET /p testDate="Please enter the date in yyyyMMdd format (e.g., 20171128)" || goto beginning
if /I "%testDate%"=="t" (
    for /f "delims=" %%a in ('powershell -Command "& get-date -format 'dd/MM/yyyy'"') do SET testDate=%%a
) ELSE (
    if /I "%testDate%"=="yt" (
        for /f "delims=" %%a in ('powershell -Command "& get-date (get-date).AddDays(-1) -format 'dd/MM/yyyy'"') do set testDate=%%a
    ) ELSE (
        for /f "delims=" %%a in ('powershell -Command "& {([datetime]::parseexact('%testDate%','yyyyMMdd',[System.Globalization.CultureInfo]::InvariantCulture)).ToString('dd/MM/yyyy')}"') do SET testDate=%%a
        REM Testing 
        echo !testDate!
        echo Yes!
    )
)
REM Testing 
echo !testDate!
echo !errorLevel!
pause

Upvotes: 2

Views: 1368

Answers (2)

codersl
codersl

Reputation: 2332

The error message from [datetime]::parseexact is being returned in multiple lines of text and causing the set testData=%%a to be called multiple times. You can see this by running the command separately.

eg.

c:\Temp> for /f "delims=" %a in ('powershell -Command "& {([datetime]::parseexact('%testDate%','yyyyMMdd',[System.Globalization.CultureInfo]::InvariantCulture)).ToString('dd/MM/yyyy')} "') do SET testDate=%a

output:

C:\Temp> SET testDate=Exception calling "ParseExact" with "3" argument(s): "String was not recognized as a valid
C:\Temp> SET testDate=DateTime."
C:\Temp> SET testDate=At line:1 char:4
C:\Temp> SET testDate=+ & {([datetime]::parseexact('Exception calling ParseExact with 3 argum ...
C:\Temp> SET testDate=+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
C:\Temp> SET testDate= + CategoryInfo : NotSpecified: (:) [], MethodInvocationException
C:\Temp> SET testDate= + FullyQualifiedErrorId : FormatException
C:\Temp> SET testDate=

To fix this you will need to control the return message when an error is encountered.

A try/catch statement can be used to achieve this:

@echo off
setlocal enabledelayedexpansion
REM Get user's inputs
:beginning
SET /p testDate="Please enter the date in yyyyMMdd format (e.g., 20171128)" || goto beginning
if /I "%testDate%"=="t" (
    for /f "delims=" %%a in ('powershell -Command "& get-date -format 'dd/MM/yyyy'"') do SET testDate=%%a
) ELSE (
    if /I "%testDate%"=="yt" (
        for /f "delims=" %%a in ('powershell -Command "& get-date (get-date).AddDays(-1) -format 'dd/MM/yyyy'"') do set testDate=%%a
    ) ELSE (
        for /f "delims=" %%a in ('powershell -Command "& {try { ([datetime]::parseexact('%testDate%','yyyyMMdd',[System.Globalization.CultureInfo]::InvariantCulture)).ToString('dd/MM/yyyy') } catch { return $_.Exception.Message }} "') do SET testDate=%%a
        REM Testing 
        echo !testDate!
        echo Yes!
    )
)
REM Testing 
echo !testDate!
echo !errorLevel!
pause

Upvotes: 2

Magoo
Magoo

Reputation: 80203

if not defined testdate (echo Invalid date supplied)

or

if not defined eventdate (echo Invalid date supplied %testdate%)

or

if not defined eventdate (echo Invalid date supplied %testdate%&goto someplace)

depending on quite what the circumstances are. Are you sure that testdate is neing modified (first scenario) - I'm suspicious that actually testdate remains as-is and eventdate is simply not being set.

Upvotes: 0

Related Questions