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