0

I want to execute powershell inline , but when I try to execute everything. I got Out-Null : A positional parameter cannot be found that accepts argument 'do'.

$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)

inline 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);

I want to get the same result inline , but I got this issue

1
  • 1
    There is a ; before until which should not be there. Commented Apr 2, 2019 at 5:41

1 Answer 1

1

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) }
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.