ahmet alp balkan
ahmet alp balkan

Reputation: 45312

Find out if process is running in a cmd.exe or PowerShell window

Imagine you're writing a program in a high level language where you are not allowed to do custom system calls (win32 API) because code is cross compiling or the language doesn't support that.

When your process is running on windows, is there a way to find out if you're running inside powershell and not cmd.exe? Or vice versa?

I'm trying to print "I'm running in powershell" and "I'm running in cmd.exe" from the program.

In this case I'm writing the program in Golang but that shouldn't really matter because I don't want to traverse process tree.

Upvotes: 2

Views: 1854

Answers (1)

Matt
Matt

Reputation: 46730

Eryksun might have a point about the usefullness of this but there is a post about getting the parent process.

Putting the following text into a ps1 script:

$parentpid=(gwmi win32_process -Filter "processid='$pid'").parentprocessid
Write-Host ("I am running in {0}" -f (Get-Process -id $parentpid).Name)

Running it from CMD calling PowerShell:

I am running in cmd

Running it from PowerShell and ISE:

I am running in explorer

So while explorer is not very useful it is not CMD which I think is what you actually wanted to know.

Upvotes: 2

Related Questions