1

I am trying these commands in a .bat file

@echo off & setLocal EnableDelayedExpansion

powershell -NoLogo -NoProfile -Command ^    
    "$h = [int](Get-Date -Format "HH");" ^
    "$diff = (7-$h)*3600;" ^
    "if ($h -le 7 -or $h -ge 0) { ECHO $h; ECHO $diff; }"

But this throws an error saying command not recognized. Here I am trying to get the hour and subtract $h from 7. Then multiply the result with 3600 and print it on the console.

Can anyone tell me what am I doing wrong?

CuriousDev
  • 1,255
  • 1
  • 21
  • 44

3 Answers3

1

The correct powershell syntax would look something like this:

$h = [int](Get-Date -Format "HH")
    $diff = (7-$h)*3600
    if ($h -le 7 -or $h -ge 0) { 
        write-output $h 
        write-output $diff
    }

You could save this powershell code as a ps.1 file and call it from your batch file

Tr4p
  • 9
  • 1
  • 1
  • 5
1

Try running them in one line:

powershell -NoLogo -NoProfile -Command "& {    $h = [int](Get-Date -Format 'HH'); $diff = (7-$h)*3600; if ($h -le 7 -or $h -ge 0) { Write-Output $h; Write-Output $diff }}"
Wasif
  • 14,755
  • 3
  • 14
  • 34
0

Caret ^ must be the last character on a line that continues. In the code, there is some trailing whitespace in the first row.

Consider code that has whitespace, illustrated by adding pipe chars to beginning and end of line.

|powershell -NoLogo -NoProfile -Command ^    |
|    "$h = [int](Get-Date -Format "HH");" ^|
|    "$diff = (7-$h)*3600;" ^|
|    "if ($h -le 7 -or $h -ge 0) { ECHO $h; ECHO $diff; }"|

Running this provides the following output:

C:\Temp>t.cmd
Cannot process the command because of a missing parameter. A command must follow -Command.

PowerShell[.exe] [-PSConsoleFile <file> | -Version <version>]
...
'"$h = [int](Get-Date -Format "HH");"' is not recognized as an internal or external command, operable program or batch file.

Whereas removing trailing whitespace works like so, |powershell -NoLogo -NoProfile -Command ^| ...

C:\Temp>t.bat
10
-10800
vonPryz
  • 22,996
  • 7
  • 54
  • 65