Batch file get command's output stored in a variable

不羁岁月 提交于 2021-02-05 09:39:22

问题


i'm trying to store this WMIC output into a variable. when i echo VAL i get nothing ! all i'm trying to achieve is getting a file's last modification date. the problem with this WMIC command is that it returns a date as a long number and i want to manipulate that output

this is the part of my script where i have this issue

:: these lines are at the top of the script

SETLOCAL ENABLEEXTENSIONS
SETLOCAL ENABLEDELAYEDEXPANSION

...
...
...
...

:: a function:

set COMM="WMIC DataFile WHERE Name='C:\\Program Files (x86)\\folder\\folder\\folder\\container.npp' Get InstallDate"

set VAL=1

for /f "skip=1" %%A in ('%COMM%') do (set VAL=%%A)
echo %VAL%

回答1:


@echo off
    setlocal enableextensions disabledelayedexpansion

    set "file=c:\\Program Files (x86)\\Internet Explorer\\iexplore.exe"
    for /f %%a in (
        'wmic DataFile where "Name='%file%'" get InstallDate ^| find "+" '
    ) do set "val=%%a"

    echo [%val%]

All the problem is proper quoting of the string. For wmic the string containing the name of the file needs to be single quote enclosed and to have no problems with for the where condition is double quote enclosed.




回答2:


Try removing the quotes in your set COMM= statement and because the close parenthesis ) are in the wmic command which you can't escape, just write to a temp file and read it back in, like so:

:: these lines are at the top of the script

SETLOCAL ENABLEEXTENSIONS
SETLOCAL ENABLEDELAYEDEXPANSION

...
...
...
...

:: a function:

set COMM=WMIC DataFile WHERE Name='C:\\Program Files (x86)\\folder\\folder\\folder\\container.npp' Get InstallDate 
%COMM% > "%temp%\installdate.trace"
set VAL=1

for /f "skip=1" %%A in ('type "%temp%\installdate.trace"') do (set VAL=%%A)
echo %VAL%
del /q "%temp%\installdate.trace"

The reason that you're not seeing an error is because your for /f loop is skipping the error output :)



来源:https://stackoverflow.com/questions/23776922/batch-file-get-commands-output-stored-in-a-variable

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!