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

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.

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.
Create 2 separate script files: test.ps1 and test.cmd
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.
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>

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

Related

How to execute .cmd file within powershell script?

I have cmd file, look like this
set Name=Joy
I want to execute that cmd file within my powershell script, then I want to see the value of cmd file from command line with command echo %Name% and It should show Joy.
But I can not figure it out, I tried this way, but its not working,
1st Way
$File = Get-Command .\TEST.cmd
& .\TEST2.cmd
2nd Way
Invoke-Expression ".\TEST.cmd"
3rd Way
&.\TEST.cmd

How To Use A Windows Environment Variable Independent Of Shell?

I have a need within a .bat file to change to a certain directory which is referenced by an environment variable. Something along these lines:
cd %TMP%
And this works fine from Windows CMD shell. However if I try to run the bat within a Powershell terminal window, it appears that the command simply doesn't work. This does though:
cd $Env:TMP
So I'm trying to figure out how to keep things to one .bat file but still allow users to run it under both the CMD prompt and the PS prompt. I can think of some hacky ways to check to see if I'm under CMD (as opposed to PS) but I'd like to know if there's a better solution.
One thing I noticed is that the PROMPT environment variable is present with CMD but not with Powershell but, as I say, that seems a bit hacky and potentially error-prone.
I'm not trying to pad my rep so if this has already been asked and answered, please point me to it. I just want to find something less hacky than trying to figure out which shell the bat is being run in and changing the cd command to suit it.
By the way, since it may make a difference, I'm running under Powershell 4. I could probably use a .cmd file if that would make any difference but I'd be surprised if it did.
EDIT:
I guess maybe I wasn't as clear as I could be. I'm trying to figure out if there's a way to get the value of an environment variable that will work within a .bat file that will work regardless of whether or not the .bat file is run under the cmd shell or the powershell shell.
Running batch files from PowerShell works just fine. However, since the batch files run in a different interpreter (running .\your.bat is basically the same as running cmd /c .\your.bat), changing the working directory via cd %TMP% in the (CMD) child process doesn't change the working directory for the (PowerShell) parent process.
The syntax you use for variables in batch files is always %variable%.
Demonstration:
PS C:\> $PWD.Path
C:\
PS C:\> Get-Content .\test.bat
#echo off
echo before: %CD%
cd %TMP%
echo after: %CD%
PS C:\> .\test.bat
before: C:\
after: C:\Users\me\AppData\Local\Temp
PS C:\> $PWD.Path
C:\
The batch file echoes the path of the current working directory (%CD%) before and after changing the working directory to %TMP%. The working directory of the parent process (PowerShell) remains unchanged ($PWD.Path).

Running CMD command in PowerShell

I am having a bunch of issues with getting a PowerShell command to run. All it is doing is running a command that would be run in a CMD prompt window.
Here is the command:
"C:\Program Files (x86)\Microsoft Configuration Manager\AdminConsole\bin\i386\CmRcViewer.exe" PCNAME
I have tried the following with no success (I have tried many iterations of this to try and get one that works. Syntax is probably all screwed up):
$TEXT = $textbox.Text #$textbox is where the user enters the PC name.
$CMDCOMMAND = "C:\Program Files (x86)\Microsoft Configuration Manager\AdminConsole\bin\i386\CmRcViewer.exe"
Start-Process '"$CMDCOMMAND" $TEXT'
#iex -Command ('"C:\Program Files (x86)\Microsoft Configuration Manager\AdminConsole\bin\i386\CmRcViewer.exe"' $TEXT)
The command will just open SCCM remote connection window to the computer the user specifies in the text box.
Try this:
& "C:\Program Files (x86)\Microsoft Configuration Manager\AdminConsole\bin\i386\CmRcViewer.exe" PCNAME
To PowerShell a string "..." is just a string and PowerShell evaluates it by echoing it to the screen. To get PowerShell to execute the command whose name is in a string, you use the call operator &.
To run or convert batch files externally from PowerShell (particularly if you wish to sign all your scheduled task scripts with a certificate) I simply create a PowerShell script, e.g. deletefolders.ps1.
Input the following into the script:
cmd.exe /c "rd /s /q C:\#TEMP\test1"
cmd.exe /c "rd /s /q C:\#TEMP\test2"
cmd.exe /c "rd /s /q C:\#TEMP\test3"
*Each command needs to be put on a new line calling cmd.exe again.
This script can now be signed and run from PowerShell outputting the commands to command prompt / cmd directly.
It is a much safer way than running batch files!
One solution would be to pipe your command from PowerShell to CMD. Running the following command will pipe the notepad.exe command over to CMD, which will then open the Notepad application.
PS C:\> "notepad.exe" | cmd
Once the command has run in CMD, you will be returned to a PowerShell prompt, and can continue running your PowerShell script.
Edits
CMD's Startup Message is Shown
As mklement0 points out, this method shows CMD's startup message. If you were to copy the output using the method above into another terminal, the startup message will be copied along with it.
For those who may need this info:
I figured out that you can pretty much run a command that's in your PATH from a PS script, and it should work.
Sometimes you may have to pre-launch this command with cmd.exe /c
Examples
Calling git from a PS script
I had to repackage a git client wrapped in Chocolatey (for those who may not know, it's a package manager for Windows) which massively uses PS scripts.
I found out that, once git is in the PATH, commands like
$ca_bundle = git config --get http.sslCAInfo
will store the location of git crt file in $ca_bundle variable.
Looking for an App
Another example that is a combination of the present SO post and this SO post is the use of where command
$java_exe = cmd.exe /c where java
will store the location of java.exe file in $java_exe variable.
You must use the Invoke-Command cmdlet to launch this external program. Normally it works without an effort.
If you need more than one command you should use the Invoke-Expression cmdlet with the -scriptblock option.

How to change the cmd's current-dir using PowerShell?

I read some file using PowerShell, and change current dir accordingly, but all I can do is change the current PowerShell's current dir, not the caller's dir (the cmd.exe environment that called that ps1 file). Things I tried:
powershell ch-dir.ps1 | cd
(won't work, obviously, since CD is internal command)
powershell cd $myDir
(changes current dir in PowerShell, but when script exits, the cmd environment still in original dir)
I really hope I won't need to find the script's caller process (the cmd), and make a change in it's cur-dir by-force... (or even worse - to save the dir I want in some env-var and then cd %my_var% since it would require two lines of command)
I'm not sure if this meets your needs, but if you set it up so that the only output from your powershell script is your desired new working directory, you could do this:
c:\>for /F %i IN ('powershell -noprofile -command "write-output 'c:\users'" ') DO #cd %i
c:\Users>
The cmd prompt is hosting your powershell session, unless you can figure out a way to return an exit code to the prompt that will (on exit code 99999) change directory to (predefined values, switch?). As far as powershell is concerned they're different processes.
Heres a good example for you to try:
Open a cmd prompt.
Open task manager, find cmd.exe
In your cmd prompt type Powershell
View powershell as a different process (check the PID.)
End the powershell process. Watch what happens.
Alternatively, if you need something run from cmd in a specific directory based on logic in your powershell script, you can invoke it with a cmd /c from within Powershell.

Call ps1 from cmd

I want to call ps1 from command line, there are 2 files in same folder (very straight forward)
test.cmd:
#set powershell=powershell.exe
echo ^^^&'%~dpn0.ps1' %*| "%powershell%" -ExecutionPolicy Bypass -Command -
exit /b %ERRORLEVEL%
test.ps1:
ls>abc.txt
The problem is:
When I call test.cmd from command line, abc.txt does't get generated. but When I call test.ps1 from powershell ise from that folder, abc.txt is created. I'm also be able to call powershell.exe from that folder as well.
Did I miss something?
This issue was sorted. I have 's in my folder's name, once I remove it, it's working fine.
Thanks guys!!
Are you sure ls>test.txt worked by just running the test.ps1 script?
You have to write is as ls > test.txt for it to work and I have confirmed that that works from test.cmd as well.