If you read about or work with PowerShell 7.x, you know that it has better performance and a few improved Cmdlets. That’s why I prefer to work with PowerShell 7 whenever and wherever I can. But unfortunately, there are still some modules that won’t work properly in PowerShell 7. For instance, ‘VirtualMachineManager’. Does this mean that we need to run all scripts that require ‘VirtualMachineManager’ in PowerShell 5.1? No.
Let me give you an easy way to run that code in a PowerShell 7 console.
$Session = New-PSSession -UseWindowsPowerShell
Invoke-Command -ArgumentList $Server -Session $Session -ScriptBlock {
param (
$Server
)
Import-Module -Name "virtualmachinemanager" -Force
## Maybe some other modules you need
Start-SCVirtualMachine -Name $Server
}
Remove-PSSession -Session $Session
Let’s break down the code.
On the first line, we create a new session, but we don’t specify a target, so the target is the localhost. The `UseWindowsPowerShell` parameter ensures that the session is a Windows PowerShell session, in other words, version 5.1.
Now we can set up an `Invoke-Command` to embed our code, and we set the target to our freshly created session. Keep in mind that a session doesn’t have access to any variables or functions you may have defined earlier in your script. So, we need to import the required modules and variables. After we have all the prerequisites in place, we can run our code.
To clean it all up, we remove the session, and with that, we ran the code in PowerShell 5.1 while having a console of version 7.x in front of us.
Leave a Reply