如何在批处理脚本中捕获PowerShell错误?

时间:2017-03-27 03:51:58

标签: powershell batch-file

目前,我正在使用此脚本将yyyyMMdd格式的日期转换为dd/MM/yyyy格式。

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

当我为%testDate%变量输入无效字符/日期时间结构时,在Powershell IDE中会抛出错误消息"String was not recognized as a valid DateTime"

但是,在批处理脚本中,它只返回一个空的testDate变量。它还会返回errorlevel = 0

如何在批处理脚本中从powershell返回错误消息?

完整脚本

@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

2 个答案:

答案 0 :(得分:1)

来自[datetime]::parseexact的错误消息在多行文本中返回,导致set testData=%%a被多次调用。您可以通过单独运行命令来查看。

例如

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

输出:

  

C:\温度> SET testDate =使用“3”参数调用“ParseExact”的异常:“字符串未被识别为有效
  C:\温度> SET testDate = DateTime。“
  C:\温度> SET testDate = At line:1 char:4
  C:\温度> SET testDate = +& {([datetime] :: parseexact('异常调用ParseExact与3 argum ...
  C:\温度> SET testDate = + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ ~~~~~~
  C:\温度> SET testDate = + CategoryInfo:NotSpecified:(:) [],MethodInvocationException
  C:\温度> SET testDate = + FullyQualifiedErrorId:FormatException
  C:\温度> SET testDate =

要解决此问题,您需要在遇到错误时控制返回消息。

try/catch语句可用于实现此目的:

@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

答案 1 :(得分:0)

if not defined testdate (echo Invalid date supplied)

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

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

取决于具体情况。您确定testdate正在修改(第一种情况) - 我怀疑实际上testdate仍然是原样而且eventdate根本没有设置。