0

I am trying to get this PowerShell command script to run in a batch file and just cannot seem to get it to work. Thank you in advance. It works fine in PowerShell, I just need it to work in a bat.

$wshell = New-Object -ComObject WScript.Shell;
$wshell.AppActivate('APPNAME')
Sleep 1
$wshell.SendKeys('{ENTER}');
Ansgar Wiechers
  • 193,178
  • 25
  • 254
  • 328
Trevor Teape
  • 23
  • 1
  • 2
  • Why not call the ps1 in your batch? And first of all why use a batch when Powershell can do it too? – Manu Oct 23 '17 at 19:58
  • 1
    You can run this in a batch file: `powershell -command "$wshell = New-Object -ComObject wscript.shell;$wshell.AppActivate('Untitled - Notepad');Sleep 1;$wshell.SendKeys('{ENTER}');"` – Squashman Oct 23 '17 at 20:01
  • Simpler: `powershell $wshell = New-Object -ComObject wscript.shell; $wshell.AppActivate('Untitled - Notepad'); Sleep 1; $wshell.SendKeys('{ENTER}')` See [this question](https://stackoverflow.com/questions/36672784/convert-a-small-ps-script-into-a-long-line-in-a-batch-file) – Aacini Oct 24 '17 at 04:27
  • It runs and returns false and does not switch to the open app. – Trevor Teape Oct 24 '17 at 16:07

1 Answers1

0

In the shortest way possible while accounting for things that happen like logos, profiles, and policies getting in the way:

powershell -ExecutionPolicy Bypass -NoProfile -NoLogo -Command "$wsh=New-Object -ComObject wscript.shell;$wsh.AppActivate('Appname');Start-Sleep 1000;$wsh.SendKeys('{ENTER}')"

As an aside, semicolons are unnecessary in PowerShell scripts except to separate statements on the same line.

Maximilian Burszley
  • 18,243
  • 4
  • 34
  • 63
  • So I am getting the following error. New-Object : Cannot find type [wscript.shell]: make sure the assembly containing this type is loaded. – Trevor Teape Oct 24 '17 at 16:01
  • @TrevorTeape looks like it's searching for an assembly rather than com object for some reason. I've updated my answer explicitly naming the com – Maximilian Burszley Oct 24 '17 at 16:06
  • Now it runs, but returns false instead of switching to the open app by name. I appreciate all your help so far by the way. – Trevor Teape Oct 24 '17 at 16:11
  • 1
    @TrevorTeape If that's the case, there is a problem in your vb example then. – Maximilian Burszley Oct 24 '17 at 16:17
  • That's very weird because it will do what I need as a powershell script without errors. I may just have to make it a ps1 and find a work around for how to get the ps1 to open in a fashion I need. – Trevor Teape Oct 24 '17 at 16:22
  • @TrevorTeape I'd suggest writing a `.cmd` or `.bat` wrapper for the PS script. `powershell -ExecutionPolicy Bypass -NoLogo -NoProfile -File "path\to\file.ps1"` – Maximilian Burszley Oct 24 '17 at 16:30
  • I found out that I need to include the Get-Process from powershell in the bat for it to not return false, I am not sure how to include that in the format cmd/bat needs. – Trevor Teape Oct 25 '17 at 17:21