I'm trying to write and execute a .cmd script in powershell. The code I have for this is:
$script = @'
@echo off
SETLOCAL
CALL something here
'@
Invoke-Expression -Command: $script
This is based off this link which explains the here string in powershell. It's at the bottom of the link. Here's the related msdn.
Here's another related link to someone trying to do the same thing.
I keep getting an error that has to do with including the '@' operator within the string:
Invoke-Expression : At line:1 char:7
+ @echo off
+ ~~~
Unexpected token 'off' in expression or statement.
At line:1 char:1
+ @echo off
+ ~~~~~
The splatting operator '@' cannot be used to reference variables in an expression. '@echo' can be used only as an argument to a command. To reference variables in an expression use '$echo'.
I've tried escaping the '@' symbol, and a plethora of other things. I'd like to know why it seemed to work for them in the third link, but throws this error in my case.
Edit: Writing to a .bat file then running the bat file resulted in the same error:
$batchFileContent = @'
@echo off
c:\windows\system32\ntbackup.exe backup "C:\Documents and Settings\Administrator\Local Settings\Application Data\Microsoft\Windows NT\NTBackup\data\chameme.bks" /n "1file.bkf1 created 06/09/2013 at 09:36" /d "Set created 06/09/2013 at 09:36" /v:no /r:no /rs:no /hc:off /m normal /j chameme /l:s /f "\\fs1\Exchange Backups$\1file.bkf"
'@
$batchFileContent | Out-File -LiteralPath:"$env:TEMP\backup.cmd" -Force
Invoke-Expression -Command:"$env:TEMP\backup.cmd"
Remove-Item -LiteralPath:"$env:TEMP\backup.cmd" -Force
As Bill Stewart pointed out, I should write the content of the .cmd script in powershell.
Edit: This
$script = @'
cmd.exe /C "@echo off"
cmd.exe /C "SETLOCAL"
cmd.exe /C "CALL something here"
'@
Invoke-Expression -Command: $script
Seems to work.