Amirul Akmal
Amirul Akmal

Reputation: 411

Determine whether programs run on Powershell or CMD

I created a program that should rename some files

system("rename file.txt file2.txt"); // examples only

did run fine at cmd , but not powershell

rename : The term 'rename' is not recognized as the name of a cmdlet, function, script file, or operable program. Check the spelling of the name, or if a path was included, verify that the path is correct and try again.
At line:1 char:1
+ rename
+ ~~~~~~
    + CategoryInfo          : ObjectNotFound: (rename:String) [], CommandNotFoundException
    + FullyQualifiedErrorId : CommandNotFoundException

by This article from MS , powershell should use rename-item
However , I don't know any "trick" to determine whther programs ran by powershell or cmd
A post for determine program's run by which , uses process checking which I find it hard to implement ( they said use wmic.exe , but I don't know how to and further research needed to be )


The conclusion:

How to determine whether my programs runs on powershell or cmd by C++ ?
Is it possible, by knowing the console used ( programmingly ) , my programs could use if-else method to change the command?

Edit: for the time being , My program's method is read file.txt and paste it in file2.txt ( examples only )..Basically like copy and paste to another renamed file and use system("del file.txt");

Upvotes: 2

Views: 530

Answers (1)

mklement0
mklement0

Reputation: 437042

How to determine whether my programs runs on powershell or cmd by C++

While that is possible, it also irrelevant to your use case, because the shell that launched your program is your program's parent process (to which you cannot submit commands).

Since your program must launch its own shell (child) process in order to execute a shell command, you're free to choose which shell to invoke .

The system() C library function targets the host platform's default shell, which is cmd.exe on Windows (and /bin/sh on Unix-like platforms), so your command - which uses the internal cmd.exe rename command - will work fine, irrespective of whether your program was invoked from PowerShell or cmd.exe.

Upvotes: 5

Related Questions