When deploying PowerShell scripts from my RMM (NinjaOne), the scripts are called from a .bat
(batch file).
Example:
@powershell -ExecutionPolicy Bypass -File "test.ps1" -stringParam "testing" -switchParam > "output.txt" 2>&1
The script I am calling requires PowerShell 7+, so I need to restart the script by calling pwsh
with the current parameters. I planned to accomplish this via the following:
Invoke-Command { & pwsh -Command $MyInvocation.Line } -NoNewScope
Unfortunately, $MyInvocation.Line
does not return the correct result when a PowerShell script is called from a batch file. What alternatives exist that would work in this scenario?
Notes:
- I am unable to make changes to the
.bat
file. $PSBoundParameters
also does not return the expected result.
Testing Script (called from batch):
Param(
[string]$string,
[switch]$switch
)
if (!($PSVersionTable.PSVersion.Major -ge 7)) {
Write-Output "`n"
Write-Output 'Attempting to restart in PowerShell 7'
if(!$MyInvocation.Line) {
Write-Output 'Parameters not carried over - cannot restart'
Exit
} else { Write-Output $MyInvocation.Line }
Invoke-Command { & pwsh -Command $MyInvocation.Line } -NoNewScope # PowerShell 7
Exit
}
Write-Output 'Parameters carried over:'
Write-Output $PSBoundParameters
Write-Output "`nSuccessfully restarted"
Edit: I've discovered the reason for $MyInvocation
/ $PSBoundParameters
not being set properly is due to the use of -File
instead of -Command
when my RMM provider calls the PowerShell script from the .bat
file. I've suggested they implement this change to resolve the issue. Until they do, I am still looking for alternatives.