2

Is there any way a batch script can know if it's called from PowerShell (without extra parameters feeded)?

Need something like..

if (%THIS_BATCH_CALLED_FROM_POWERSHELL%)
    ... warn the user or drop back to powershell to execute the proper instructions...

Question related with this question - virtualenv-in-powershell.

Community
  • 1
  • 1
utku_karatas
  • 6,163
  • 4
  • 40
  • 52
  • I'm not sure I understand the issue. Batch files are not directly executed from PowerShell. When you execute a batch file within PowerShell, a new instance of cmd.exe is spawned to do the actual execution of the batch file. – Keith Hill Sep 02 '09 at 21:26
  • I think he wants to find a way to alter environment variables in the Powershell environment. – JasonTrue Sep 02 '09 at 21:36
  • @Keith Hill: Exactly. And I'm in search for a way to know, from within the batch script, if it is called from PS. – utku_karatas Sep 02 '09 at 22:51
  • @JasonTrue: that too, but first at least we need to detect if we're in PS environment or not. – utku_karatas Sep 02 '09 at 22:52

3 Answers3

3

You could use a tool like "tlist.exe /t" or this one to display the PIDs of the current process and all parent processes. You could check each one of those PIDs to see if any correspond to PowerShell.exe.

Keith Hill
  • 194,368
  • 42
  • 353
  • 369
0

You could add a default warning in the script and pass it a flag that tells it not to show the warning. When you call it from power shell pass it that flag.

QueueHammer
  • 10,515
  • 12
  • 67
  • 91
0

In my Powershell environment (a PS 2.0 CTP), I seem to have an environment variable PSMODULEPATH which is not set by the normal command line environment, but still exists when Powershell has a child CMD.exe shell.

I think you might be able to "reliably enough" check for the existence of PSMODULEPATH in your batch script.

JasonTrue
  • 19,244
  • 4
  • 34
  • 61
  • Are you sure? %PSMODULEPATH% seems to be a global env. setting and thus exists on cmd.exe shell too on my machine. – utku_karatas Sep 02 '09 at 19:27
  • Not sure, as I only have my machine to check against, but when I run "CMD.exe" from Explorer, it doesn't exist. When I run Powershell, it does exist. When I run cmd.exe from Powershell, the environment is copied into the new cmd.exe and it exists there. – JasonTrue Sep 02 '09 at 19:49
  • 2
    %PSMODULEPATH% is a global env variable for me on Win7. – Richard Berg Sep 02 '09 at 21:14