Scripting with Powershell 7

Options
dfletcher
dfletcher Member Posts: 25 ✭✭
edited September 2023 in Scripts

We script against some 3rd party powershell modules that require Powershell 7. Running these scripts through Atera fails because it defaults to powershell.exe (Powershell 5.1) when powershell 7 requires pwsh.exe.

I found a workaround here that is working for us:

You can definitely do this it's just not builtin using a pwsh syntax. The easiest way I know is to just start the new process and use a scriptblock as the argument.

pwsh.exe {
  code inside here runs in the new process
  }

PowerShell internally will convert that scriptblock into -EncodedCommand ... and output the data as actual objects so you can get richer objects back to use in the main process. They will be serialized so essentially a read only copy of what was output.

Tagged:

Comments

  • nina
    nina Administrator Posts: 428 admin
    Options

    FYI @kim :)

  • kim
    kim Member Posts: 113 ✭✭✭
    Options

    Hi @dfletcher !

    Thank you for sharing your script! That's very helpful for a lot of the tasks I've been trying to remediate in my environment. Have you submitted it to the Shared Script Library? This would make it super easy for others to clone in their environments as well. I'm not the world's best script-er so this is very helpful for people like me.

    Thank you again!

    Sincerely,

    Kim

  • dfletcher
    dfletcher Member Posts: 25 ✭✭
    Options

    @kim

    I've submitted it to the shared script library, but it hasn't been accepted yet.

    For reference, the script name I used was ps7wrapper.ps1

  • kim
    kim Member Posts: 113 ✭✭✭
    Options

    That's awesome! I'm sure it'll be accepted soon!

  • mjones
    mjones Member Posts: 138 ✭✭✭✭
    Options

    Might be good to build some logic around this to run one version or another based on the PS version on the machine.

    if ($PSVersionTable.PSVersion -lt 7){
    # Do things in PS v5
    }else {
    pwsh.exe {
    # Do things in PS v7
    }
    }

  • dfletcher
    dfletcher Member Posts: 25 ✭✭
    Options

    Except that PowerShell 7 is a side by side installation. The default powershell is always 5.1 and as far as the current documentation it will stay that way. Calling powershell.exe gets you 5.1. Calling pwsh.exe gets 7.

  • kim
    kim Member Posts: 113 ✭✭✭
    Options

    That makes sense, @dfletcher look your script has posted! https://app.atera.com/new/admin/scripts and search for "ps7wrapper" to find your posted script in the Shared Script Library! I've already cloned it to use in my environment, so thank you in advance for this awesomeness!

    Sincerely,

    Kim

  • nina
    nina Administrator Posts: 428 admin
    Options

    #teamwork

  • nina
    nina Administrator Posts: 428 admin
    Options

    As @kim mentioned, you can view your script in-app here.