Or: Outsource your multiple PowerShell statements to a script file
(*.ps1), which you can call with powershell.exe -File.
mklement0's statement implies the need for 2 files, the BATCH file and the PowerShell script. But there is also a method for combining both into a Polyglot.
Place the following code in a file with the CMD extension and, when ran, it will first execute as a BATCH file (running the section between the <#
and #>
), and BATCH will in turn call PowerShell which in turn will load and run the file itself as a PowerShell script block.
NOTE:
- Most of the PowerShell commands in your example script are included in this script, but are surrounded by double quotes
"
, so instead of executing, they simply display what would have been executed.
- Also, the back tick
`
was used to escape the preexisting double quotes in the last 2 lines and a slight modification was made to make the $Date variable work in the strings.
- This means you will need to remove the extra double quotes and back ticks to reactivate these lines.
<# : REM [### https://stackoverflow.com/questions/43882863/strange-redirect-in-batch-powershell-polyglot ###]
@ECHO OFF
REM [### Ensure extensions enabled ###]
SETLOCAL ENABLEEXTENSIONS
REM [### Define environment variable f0 as this file ###]
SET f0=%~f0
REM [### Run this file as a PowerShell script block with $PSScriptRoot and $PSCommandPath defined: https://stackoverflow.com/a/67517934/4190564 ###]
PowerShell -NoProfile -ExecutionPolicy RemoteSigned -Command ". ([System.Management.Automation.Language.Parser]::ParseInput((get-content -raw $Env:f0), $Env:f0, [ref]$null, [ref]$null)).GetScriptBlock()"
GOTO :EOF
#>
"Remove-item -Path C:\Backup\db_temp\Backup_TmpTest.bak -Force"
"Remove-item -Path C:\Backup\db_prod\Backup_Tmp.bak -Force"
$Date = Get-Date -Format MM-dd-yyyy
"sqlcmd -S WIN-xxxxxxxxx -i C:\ScriptBackup\DBBck.sql -o executeBackupOut.txt -U usersql -P usersql"
"Compress-Archive -Path C:\Backup\db_temp\Backup_TmpTest.bak -Force -DestinationPath `"C:\Backup\db_temp\Backup_TmpTest_$Date.zip`""
"Compress-Archive -Path C:\Backup\db_prod\Backup_Tmp.bak -Force -DestinationPath `"C:\Backup\db_prod\Backup_Tmp_$Date.zip`""
The results are the following lines of text, which represent what would have been executed if the extra double quotes and back ticks are removed:
Remove-item -Path C:\Backup\db_temp\Backup_TmpTest.bak -Force
Remove-item -Path C:\Backup\db_prod\Backup_Tmp.bak -Force
sqlcmd -S WIN-xxxxxxxxx -i C:\ScriptBackup\DBBck.sql -o executeBackupOut.txt -U usersql -P usersql
Compress-Archive -Path C:\Backup\db_temp\Backup_TmpTest.bak -Force -DestinationPath "C:\Backup\db_temp\Backup_TmpTest_06-08-2023.zip"
Compress-Archive -Path C:\Backup\db_prod\Backup_Tmp.bak -Force -DestinationPath "C:\Backup\db_prod\Backup_Tmp_06-08-2023.zip"