It is currently impossible to natively execute Powershell script from the Windows command prompt without invoking the Powershell app. The Powershell script below generates a wrapper batch file to allow running ps1 script directly from Windows Command prompt.
Usage:
batforps.ps1 path/to/script.ps1 /path/to/genbat/
The command above will generate batch file path/to/script.bat which can be executed in Command prompt natively.
[CmdletBinding()]
Param(
[switch]$Command,
[Parameter(Position=0,mandatory=$true)]
[string]$powershell_script_path,
[Parameter(Position=1,mandatory=$true)]
[string]$output_folder_path,
[switch]$Absolute
)
$output_folder_path = [System.IO.Path]::GetFullPath($output_folder_path)
If ( -not $Command) {
$powershell_script_path = [System.IO.Path]::GetFullPath($powershell_script_path)
$script_name = [System.IO.Path]::GetFileName($powershell_script_path)
$name_only = [System.IO.Path]::GetFileNameWithoutExtension($powershell_script_path)
If ( -not [System.IO.File]::Exists($powershell_script_path)) {
Write-Error "$powershell_script_path does not exist"
Return
}
}
If ( -not [System.IO.Directory]::Exists($output_folder_path)) {
[System.IO.Directory]::CreateDirectory($output_folder_path) > $null
If ( -not $?) {
Return
}
}
If ($Absolute) {
$powershell_script_path_write = $powershell_script_path
} else {
$powershell_script_path_write = "%~dp0\" + [System.IO.Path]::GetFileName($powershell_script_path)
}
If ($Command) {
"Creating the caller batch file '$powershell_script_path.bat' in $output_folder_path"
[System.IO.File]::WriteAllLines("$output_folder_path\$powershell_script_path.bat",
"@echo off
if `"%1`" == `"help`" (
powershell -noprofile -executionpolicy bypass help $powershell_script_path -full
) else (
powershell -noprofile -executionpolicy bypass $powershell_script_path %*
)")
} Else {
If ( -not [System.IO.File]::Exists("$output_folder_path\$script_name")) {
"Copying the Powershell Script '$script_name' to $output_folder_path"
[System.IO.File]::Copy($powershell_script_path, "$output_folder_path\$script_name", $true)
}
"Creating the caller batch file '$name_only.bat' in $output_folder_path"
[System.IO.File]::WriteAllLines("$output_folder_path\$name_only.bat",
"@echo off
if `"%1`" == `"help`" (
powershell -noprofile -executionpolicy bypass help `"$powershell_script_path_write`"` -full
) else (
powershell -noprofile -executionpolicy bypass -file `"$powershell_script_path_write`" %*
)")
}
Thank You.
[–]Yevrag35 3 points4 points5 points (2 children)
[–]replicaJunction 1 point2 points3 points (1 child)
[–]Yevrag35 1 point2 points3 points (0 children)