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.
Enter the name of one command, such as the name of a cmdlet, function, or CIM command. If you omit this parameter, Show-Command displays a command window that lists all of the PowerShell commands in all modules installed on the computer.
Run an old-fashioned command line (cmd.exe), type powershell and execute. Or, you can hit the PowerShell icon on the taskbar. Either way, you'll get a ready-to-use Windows PowerShell console. Use “Get-Help” cmdlet from before as a starting point for your journey.
How can I tell if I am executing on PowerShell Core? Just use the $PSVersionTable object and examine the PSEdition value. If it returns 'Core' you are running on PowerShell core.
The executables can be run from any command-line shell, like PowerShell. This includes script files that may require other shells to work properly. For example, if you run a Windows batch script ( . cmd file) in PowerShell, PowerShell runs cmd.exe and passes in the batch file for execution.
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","
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>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With