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
3
  • put try/catch Batch try/catch. Error handling in batch Commented Mar 27, 2017 at 4: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. Commented Mar 27, 2017 at 4:54
  • Why use a batch file at all? Just write the entire script in PowerShell. Much, much simpler. Commented Mar 27, 2017 at 15:29

2 Answers 2

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
Sign up to request clarification or add additional context in comments.

Comments

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.

1 Comment

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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.