WMI批处理脚本返回No Instance(s)Available

时间:2016-05-19 10:03:26

标签: batch-file wmi

我正在尝试使用批处理脚本中的WMI以YYYYMMDDHHMMSS格式检索文件的时间戳,如下所示:

@echo off
::if "%~1" == "" goto :EOF
setlocal EnableDelayedExpansion
::for %%V in (%1) do (

    rem Get name of file with full path.
    set FileName='C:\scot\logs\marker.txt'

    rem Escape each backslash in file path with one more backslash.
    rem set 'FileName=!FileName:\=\\!'

    echo FilePath=%FileName%
    rem Get creation date and time of file in format YYYYMMDDHHMMSS.
    ::for /F "usebackq skip=1 tokens=1 delims=." %%T in (`%SystemRoot%\System32\wbem\wmic.exe DATAFILE where "name='!FileName!'" get CreationDate') do set FileDateTime=%%T

    for /f "usebackq tokens=2 delims=." %%T in ('%SystemRoot%\System32\wbem\wmic.exe DATAFILE where "name='!FileName!'" get CreationDate') do set FileDateTime=%%T

    echo FileCreationTime1=%FileDateTime%

    rem The first 8 characters are file creation date.
    set "FileDate=!FileDateTime:~0,8!"
    rem The next 6 characters are file creation time.
    set "FileTime=!FileDateTime:~8,6!"
    echo FileCreationTime2=%FileTime%

    if exist "!FileDate!_!FileTime!-%%~nV%%~xV" (
        echo Cannot rename file: %%~fV
    ) else (
        ren "%%~fV" "!FileDate!-!FileTime!-%%~nV%%~xV"
    echo FileCreationTime=%FileTime%
    )
::)
endlocal

但它正在回复说"没有可用的实例"。

当我从命令行运行相同的WMIC命令时,我可以获得时间戳值。请帮帮我?

1 个答案:

答案 0 :(得分:2)

你有usebackq但是在代码中没有使用反引号。并且反斜杠加倍被注释。检查此示例:

@echo off
setlocal enableDelayedExpansion
set "FileName=%SystemRoot%\System32\wbem\wmic.exe"
set "FileName=!FileName:\=\\!"
for /f "usebackq tokens=2 delims=." %%T in (`"%SystemRoot%\System32\wbem\wmic.exe DATAFILE where name='!FileName!' get CreationDate"`) do set "FileDateTime=%%T"
echo %FileDateTime%

由于我没有您的文件,因此使用wmic.exe来获取时间。

编辑:

@echo off
setlocal enableDelayedExpansion
set "FileName=%SystemRoot%\System32\wbem\wmic.exe"
set "FileName=!FileName:\=\\!"
for /f "usebackq delims=" %%T in (`"%SystemRoot%\System32\wbem\wmic.exe DATAFILE where name='!FileName!' get CreationDate /format:value"`) do (
    for /f "tokens=2 delims==" %%# in ("%%T") do  set "FileDateTime=%%#"
)
echo %FileDateTime%