Your code had 3 problems:
- a missing
; before the do statement (multiple statements placed on a single line must be ;-separated in PowerShell)
- you've later added that, which makes your command inconsistent with the described symptom.
a missing until keyword after do { ... }
- you've later added that, but with a preceding
;, which breaks the do statement.
unescaped use of |, which means that cmd.exe itself interpreted it, not PowerShell as intended (I'm assuming you're calling this from cmd.exe, otherwise there'd be no need to call PowerShell's CLI via powershell.exe).
| must be escaped as ^| to make cmd.exe pass it through to PowerShell.
Fixing these problems yields the following command for use from cmd.exe:
# From cmd.exe / a batch file:
powershell -Command $OutputString = 'Hello World'; $WScript = New-Object -ComObject 'wscript.shell'; $WScript.Run('notepad.exe') ^| Out-Null; do{ Start-Sleep -Milliseconds 100} until ($WScript.AppActivate('notepad')); $WScript.SendKeys($OutputString)
If you do want to run your code from PowerShell, you can just invoke it directly, as shown in the first snippet in your question - there's no need to create another PowerShell process via powershell.exe
If, for some reason, you do need to create another PowerShell process, use the script-block syntax ({ ... }) to pass the command, in which case no escaping is needed:
# From PowerShell
powershell -Command { $OutputString = 'Hello World'; $WScript = New-Object -ComObject 'wscript.shell'; $WScript.Run('notepad.exe') | Out-Null; do{ Start-Sleep -Milliseconds 100} until ($WScript.AppActivate('notepad')); $WScript.SendKeys($OutputString) }
;beforeuntilwhich should not be there.