2

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
John Evans Solachuk
  • 1,953
  • 5
  • 31
  • 67
  • put try/catch [Batch try/catch](http://stackoverflow.com/questions/21772060/batch-file-try-catch). [Error handling in batch](http://stackoverflow.com/questions/1164049/batch-files-error-handling) – Ranadip Dutta Mar 27 '17 at 04:00
  • @RanadipDutta what I want is to return the error message generated by powershell, not create my own error message when there is a problem. – John Evans Solachuk Mar 27 '17 at 04:54
  • Why use a batch file at all? Just write the entire script in PowerShell. Much, much simpler. – Bill_Stewart Mar 27 '17 at 15:29

2 Answers2

2

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
codersl
  • 2,222
  • 4
  • 30
  • 33
0
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.

Magoo
  • 77,302
  • 8
  • 62
  • 84
  • Hi, I have updated the question to show the full script. Also, what I aimed for was to output the error message from powershell process caused by invalid characters, not creating own custom messages. Sorry that I wasn't clear enough. – John Evans Solachuk Mar 27 '17 at 04:14