Reputation: 18573
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
Reputation: 14832
A potentially simpler approach that may work for you. If not, it may be suitable for others.
test.ps1
and test.cmd
<path>\test
(or just test
if folder is in the path environment variable..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
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
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