Nilzor
Nilzor

Reputation: 18573

How can I detect whether or not I am in powershell from a command line?

I am creating a standard windows BAT/CMD file and I want to make an IF statement to check whether or not this CMD file is run from PowerShell. How can I do that?

Edit: My underlying problem was that test.cmd "A=B" results in %1==A=B when run from CMD but %1==A and %2==B when run from PowerShell. The script itself is actually run as an old Windows Command line script in both cases, so checking for Get-ChildItem will always yield an error.

Upvotes: 9

Views: 6221

Answers (3)

Disillusioned
Disillusioned

Reputation: 14832

A potentially simpler approach that may work for you. If not, it may be suitable for others.

  1. Create 2 separate script files: test.ps1 and test.cmd
  2. Don't include extension when calling the script. I.e. call as <path>\test (or just test if folder is in the path environment variable.
  3. This works because CMD prioritises which script to execute as: .bat > .cmd, whereas Powershell prioritises: .ps1 > .bat > .cmd.

The following is the output of a CMD session:

C:\Temp>copy con test.cmd
@echo cmd^Z
        1 file(s) copied.

C:\Temp>copy con test.ps1
Write-Output "ps1"^Z
        1 file(s) copied.

C:\Temp>.\test
cmd

C:\Temp>

And calling test from Powershell:

PS C:\Temp> .\test
ps1
PS C:\Temp>

Upvotes: 2

Austin T French
Austin T French

Reputation: 5121

One way, it to see what your process name is, and then check its attributes:

title=test
tasklist /v /fo csv | findstr /i "test"

As long as you use a unique name in place of Test, there should be little room for error.

You will get back something like:

"cmd.exe","15144","Console","1","3,284 K","Running","GNCID6101\Athomsfere","0:00:00","test"

When I ran the above code from a bat file, my output was:

"powershell.exe","7396","Console","1","50,972 K","Running","GNCID6101\Athomsfere","0:00:00","

Upvotes: 5

Damien Ryan
Damien Ryan

Reputation: 1591

Couldn't you try to execute a Get-ChildItem and then check %ERRORLEVEL% to see if it returns an exe not found?

http://ss64.com/nt/errorlevel.html

Upvotes: 0

Related Questions