英文:
how to detect the guest windows interpreter: cmd or powershell?
问题
我正在开发一个Go的CLI工具,用于在不同的操作系统中触发终端命令。
我对Windows 10不太了解,所以我想问一个基本问题:如何检测我的二进制文件在哪种Windows shell中运行?(cmd还是powershell)。
我想知道是否可以通过读取环境变量来实现这一点。
我可以看到一些潜在的候选项,特别是PSSessionOption
和PSSesionConfigurationName
。
在cmd方面,有SESSIONNAME
和ComSpec
。
- 这些环境变量是检测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
.
On the cmd side, there is SESSIONNAME
and ComSpec
.
-
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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论