-4

set "$today=(Get-Date).ToString('MM_dd_yy')" echo "%today%"

I have created the date.bat file but it's not printing the date. Please help me to fix this issue. Thanks in advance

Output -

  •   + CategoryInfo          : NotSpecified: ('$today' is not...ternal command,:String) [], RemoteException
      + FullyQualifiedErrorId : NativeCommandError
    
    

operable program or batch file.

C:\Desktop>echo "$today" "$today"

aschipfl
  • 28,946
  • 10
  • 45
  • 77
  • 2
    As you have discovered, arbitrarily mixing legacy cmd.exe (batch) code and PowerShell will not work. Specifically in your code, you are using `set`, which sets environment variables in batch but not PowerShell. Also, environment variable names surrounded by `%` characters doesn't work in PowerShell. You need to decide which environment you want to use (I would recommend PowerShell) and use appropriate code. – Bill_Stewart May 28 '21 at 20:24
  • There is a perfectly good search facility at the top of the page, and a whole load of answers already showing the process of getting the result of any command into a variable, and many of those are retrieving the result of a PowerShell command too. `@For /F %%G In ('%SystemRoot%\System32\WindowsPowerShell\v1.0\powershell.exe -NoProfile -NoLogo -Command "Get-Date -Format 'MM_dd_yy'"') Do @Set "today=%%G"`. – Compo May 28 '21 at 20:24
  • Hi @Bill_Stewart, when I am running the bat file, I need to run this bat file as administrator to execute all my commands. How can I achieve it? Getting Error - Access to the path 'C:\Production_2021_05_29_06_27 AM' is denied. – Raghunath Dhara May 29 '21 at 11:58
  • Its giving me one extra space - "Current Date & Time" : 2021_05_29_ 719 @echo off For /f "tokens=2-4 delims=/ " %%a in ('date /t') do (set mydate=%%c_%%a_%%b) For /f "tokens=1-2 delims=/:" %%a in ("%TIME%") do (set mytime=%%a%%b) echo "Current Date & Time" : %mydate%_%mytime% – Raghunath Dhara May 29 '21 at 12:23

1 Answers1

0

@echo off
For /f "tokens=2-4 delims=/ " %%a in ('date /t') do (set mydate=%%c-%%a-%%b)
For /f "tokens=1-2 delims=/:" %%a in ('time /t') do (set mytime=%%a%%b)
echo %mydate%_%mytime%
It works for me
  • Do you really want to put a COLON `:` character into a filename? I would not. Not friendly on non-Windows systems. – lit May 29 '21 at 18:57