Windows 10批处理脚本突发Invalid Namespace错误求助
Hey there, let's tackle that frustrating "Invalid namespace" error you're hitting with your batch script, and make sure you get exactly the date formats you need: File Date:23032018, Month:03, and Date:23Mar2018.
Why the Error Happens
That "Invalid namespace" message usually means the WMI (Windows Management Instrumentation) service your script relies on (via wmic) is either stopped, corrupted, or its database has gone wonky. You could try repairing WMI, but honestly—there are simpler, more reliable ways to get formatted dates in batch without relying on WMIC.
Recommended Solution: Use PowerShell for Consistent Date Formatting
PowerShell lets you format dates directly without worrying about regional settings or WMI issues. Here's a drop-in replacement script that does exactly what you need:
@echo off setlocal enabledelayedexpansion :: Grab the formatted dates using PowerShell for /f "delims=" %%a in ('powershell -Command "(Get-Date).ToString('ddMMyyyy')"') do set "FileDate=%%a" for /f "delims=" %%a in ('powershell -Command "(Get-Date).ToString('MM')"') do set "Month=%%a" for /f "delims=" %%a in ('powershell -Command "(Get-Date).ToString('ddMMMyyyy')"') do set "Date=%%a" :: Verify the output (you can remove these lines if you don't need them) echo File Date: !FileDate! echo Month: !Month! echo Date: !Date! endlocal
This script will consistently output:
FileDateas DDMMYYYY (e.g., 23032018)Monthas MM (e.g., 03)Dateas DDMMMYYYY (e.g., 23Mar2018)
Alternative: Pure Batch (No PowerShell)
If you can't use PowerShell, you can leverage robocopy (a built-in Windows tool) to get a fixed-date format, then parse it:
@echo off setlocal enabledelayedexpansion :: Use robocopy to get a consistent date string for /f "tokens=1-3 delims=/ " %%a in ('robocopy /l * \null /njh /njs ^| find ":"') do ( set "day=%%a" set "month=%%b" set "year=%%c" ) :: Build your required variables set "FileDate=!day!!month!!year!" set "Month=!month!" :: Define month abbreviations set "monthAbbr[01]=Jan" set "monthAbbr[02]=Feb" set "monthAbbr[03]=Mar" set "monthAbbr[04]=Apr" set "monthAbbr[05]=May" set "monthAbbr[06]=Jun" set "monthAbbr[07]=Jul" set "monthAbbr[08]=Aug" set "monthAbbr[09]=Sep" set "monthAbbr[10]=Oct" set "monthAbbr[11]=Nov" set "monthAbbr[12]=Dec" set "Date=!day!!monthAbbr[%month%]!!year!" :: Verify output echo File Date: !FileDate! echo Month: !Month! echo Date: !Date! endlocal
If You Really Want to Fix the Original WMIC Script
If you're set on using your original code, you can try repairing the WMI service:
- Open Command Prompt as Administrator
- Run these commands one by one:
net stop winmgmt winmgmt /resetrepository net start winmgmt - Restart your PC, then try running your script again.
内容的提问来源于stack exchange,提问作者pOrinG

