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?

1

3 Answers 3

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

Sign up to request clarification or add additional context in comments.

Comments

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 }}"

Comments

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

1 Comment

Yes, whitespaces were the problem. Thanks so much!

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.