Run a script block using powershell 5?

Hello,

All my code is running in powershell 7, but I have subsection of a script that needs to run under powershell 5. I would like to know is there is an elegant way to run a script block from a powershell 7 script, using powershell 5

Of course, on way to resolve this is to use the command invoke-command :

$Result=  Invoke-Command -ComputerName MyServerName -ScriptBlock {
   Import-Module MyOldThirdPartyModule # not compatible with powershell 7
   Somecommand -do this -alsodo that -Credential $using:Credential 
}

But I found 2 issues with this :

1.It requires the account to have elevated privileges, which is not the ideal senario for an automation
2. I found erratic behavior, with some commands, on the same server, succeeding, and then failing right after

At the moment, the only way I found to do it is to run another script :

 powershell.exe -file path -mylocalArg1 servername ...

using $using:myariable is not a possibility there.

Any suggestion is welcome.

This will launch an instance of 5.1 inside of 7.3.4 on my workstation:

invoke-command -ScriptBlock { C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe }

Then try $PSVersionTable to verify, enter commands that you need running in 5.1 and type exit.
Then you’re back in version 7.x.
That should give you what you need to run your 5.1 code.

You may also want to look into the -Command argument to PowerShell.EXE

Yes and no. You are not invoking a code block that will do something, you are invoking a code block that will launch a new powershell 5 session.
The idea is that I want to execute a function that is part of a module that does not support powershell 7.

If I want to pass a credential object, this won’t work.

The command you are showing will just launch a new powershell session … I don’t think I will be able to run any command beyond.

Since a simple scriptblock does not launch a new session in any kind I’d say “no”. :man_shrugging:t3:

But you can start a new PowerShell session with the PowerShell version of your choice by calling the desired PowerShell executable. :man_shrugging:t3:

Did you pay for this “MyOldThirdPartyModule”? How about contacting the creator/vendor for an updated version? What exactly does this “Somecommand” do? Is it a binary module? You might replace it with a version you created yourself.