如何检测客户机的Windows解释器:cmd还是PowerShell?

huangapple go评论78阅读模式
英文:

how to detect the guest windows interpreter: cmd or powershell?

问题

我正在开发一个Go的CLI工具,用于在不同的操作系统中触发终端命令。

我对Windows 10不太了解,所以我想问一个基本问题:如何检测我的二进制文件在哪种Windows shell中运行?(cmd还是powershell)。

我想知道是否可以通过读取环境变量来实现这一点。

我可以看到一些潜在的候选项,特别是PSSessionOptionPSSesionConfigurationName

在cmd方面,有SESSIONNAMEComSpec

  • 这些环境变量是检测Windows shell类型的好方法吗?
  • 它们经常被其他应用程序覆盖吗?
  • 请给我提供其他用于此目的的替代环境变量的建议。
  • 作为备选方案,有没有其他方法可以识别Windows中的主机shell类型?
英文:

I am developing a go CLI tool which triggers terminal commands in different OSs.

I do not have much idea about Windows 10, so I will ask you this basic question: how to detect on which kind of windows shell my binary is run? (cmd or powershell).

I am wondering if this is feasible by reading environment variables.

I can see a set of potential candidates, specially PSSessionOption and PSSesionConfigurationName.

如何检测客户机的Windows解释器:cmd还是PowerShell?

On the cmd side, there is SESSIONNAME and ComSpec.

如何检测客户机的Windows解释器:cmd还是PowerShell?

如何检测客户机的Windows解释器:cmd还是PowerShell?

  • Are these good environment variables to detect the windows shell type?

  • Or they are often overwritten by other applications?

  • Could you please suggest me any other alternative environment variables for this purpose?

  • As a fallback, is there any other method to identify the host shell type in windows?

答案1

得分: 2

这对我有用:

package main
import "os"

func main() {
   if os.Getenv("PROMPT") != "" {
      println("命令提示符")
   } else {
      println("PowerShell")
   }
}

或者这样:

if _, ok := os.LookupEnv("PROMPT"); ok {

尽管其他人已经说过,这可能不是一个好主意,无论你试图做什么。无论你是在尝试编写 .bat.ps1 脚本,你都可以直接使用 Go 来完成。Go 程序几乎可以像其他类型的程序一样访问你的系统。

英文:

This worked for me:

package main
import "os"

func main() {
   if os.Getenv("PROMPT") != "" {
      println("Command Prompt")
   } else {
      println("PowerShell")
   }
}

or this:

if _, ok := os.LookupEnv("PROMPT"); ok {

Although, as others have said, it's probably not a good idea to do, whatever it is you're trying to do. Whatever .bat or .ps1 script you're trying to work up, you could just do it with Go directly. Go programs can have pretty much the same access to your system as the other types.

huangapple
  • 本文由 发表于 2021年6月15日 22:49:48
  • 转载请务必保留本文链接:https://go.coder-hub.com/67988583.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定