Yes, you can integrate the .ps1 PowerShell script directly into a .bat batch file using the -Command parameter of PowerShell instead of -File. This allows you to directly execute PowerShell commands within a batch file without needing to separately maintain a .ps1 file. Here's how you can do it:
Steps to Integrate:
-
Directly Encode PowerShell Commands in Batch File:
You can rewrite your .bat file to include the PowerShell script directly by using the -Command option to pass the entire PowerShell script sequence as a string. Here's an example based on your scripts:
@echo off
PowerShell.exe -NoProfile -ExecutionPolicy Bypass -Command "& { . \"$PSScriptRoot\Set-ScreenResolution.ps1\"; Set-ScreenResolution 1920 1080 60; }"
-
Explanation:
@echo off: Suppresses the command echo to keep the output clean.
PowerShell.exe: Runs PowerShell.
-NoProfile: Starts PowerShell without profiles.
-ExecutionPolicy Bypass: Allows scripts to run without restrictions.
-Command "& { ... }": The & is a call operator that allows running script blocks. Everything inside the curly braces {} is a part of the PowerShell command to execute.
- We incorporate the scripts previously inside
1080.ps1 directly into the command.
-
Ensuring Script and Function Accessibility:
- Since we've removed the dependency on
1080.ps1, you must ensure that the script Set-ScreenResolution.ps1 is either in the same directory or the path is correctly updated in the batch file.
$PSScriptRoot dynamically gets the directory of the currently running PowerShell script, but in this inline approach, make sure Set-ScreenResolution.ps1's path is accessible with the use of $PSScriptRoot.
Enhanced Approach (Including the PowerShell Function Directly)
If you find maintaining the Set-ScreenResolution.ps1 separately cumbersome, consider defining this function directly within the batch file as well. Assuming Set-ScreenResolution.ps1 is a simple function, you might inline everything:
@echo off
PowerShell.exe -NoProfile -ExecutionPolicy Bypass -Command "& {
function Set-ScreenResolution {
param ([int] $width, [int] $height, [int] $freq)
# Presumed contents of Set-ScreenResolution function here
}
Set-ScreenResolution 1920 1080 60
}"
Remember:
- Ensure the actual contents of your
Set-ScreenResolution.ps1 are compatible with being inlined and you accommodate for any dependencies or external considerations in your inline function.
- While the integration can definitely streamline your setup process, the specifics of your
Set-ScreenResolution function might influence how effectively it can be included inline. This will need you to adjust your inlined scripts based on the function's complexity and dependencies.