如何从脚本中更改我正在运行的 powershell 版本? [英] How can I change the version of powershell I'm running in from within the script?

查看:46
本文介绍了如何从脚本中更改我正在运行的 powershell 版本?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在 v2 模式下运行我的 powershell 脚本.是否可以在没有包装器脚本的情况下执行此操作?

I would like to run my powershell script in v2 mode. Is it possible to do this without having a wrapper script?

例如,如果我可以创建两个文件,我现在就可以做到这一点.

So for example, I can do this now if I can two files.

MainContent.ps1

write-output 'run some code'
Read-Host -Prompt "Scripts Completed : Press any key to exit" 


Wrapper.ps1

powershell -version 2 -file 'MainContent.ps1'

这会起作用,但我希望我不需要第二个包装文件,因为我正在创建一大堆这些 ps1 脚本,并且拥有包装文件将使我需要的脚本数量增加一倍.

This will work but I'm hoping I don't need to have this second wrapper file because I'm creating a whole bunch of these ps1 scripts, and having wrapper files will double the amount of scripts I'll need.

我希望我能做这样的事情.

I'm hoping I can do something like this.

MainContent.ps1

Set-Powershell -version 2
write-output 'run some code'
Read-Host -Prompt "Scripts Completed : Press any key to exit" 

稍后,我还希望每个脚本在不使用包装文件的情况下也要求提供一组凭据.

Later on, I would also like each script to ask for a set of credentials as well without using a wrapper file.

目前有可能吗?

明确地说,我使用的是 powershell 的第 2 版

To be clear, I'm using version 2 of powershell

推荐答案

如果您的唯一目标是避免创建单独的包装脚本,您可以随时让脚本重新启动.以下脚本将始终使用 PS 2.0 版重新启动一次.

If your only goal is to avoid creating separate wrapper scripts, you can always have the script re-launch itself. The following script will always re-launch itself once with PS version 2.0.

param([switch]$_restart)
if (-not $_restart) {
  powershell -Version 2 -File $MyInvocation.MyCommand.Definition -_restart
  exit
}

'run some code'
Read-Host -Prompt "Scripts Completed : Press any key to exit"

或者您可以将其设置为有条件的.仅当版本大于 2.0 时,此脚本才会使用版本 2 重新启动.

Or you can make it conditional. This script re-launches itself with version 2 only if the version is greater than 2.0.

if ($PSVersionTable.PSVersion -gt [Version]"2.0") {
  powershell -Version 2 -File $MyInvocation.MyCommand.Definition
  exit
}

'run some code'
Read-Host -Prompt "Scripts Completed : Press any key to exit"

这篇关于如何从脚本中更改我正在运行的 powershell 版本?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆