Reputation: 23
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
Upvotes: 0
Views: 3500
Reputation: 437248
Your code had 3 problems:
;
before the do
statement (multiple statements placed on a single line must be ;
-separated in PowerShell)
a missing until
keyword after do { ... }
;
, 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) }
Upvotes: 1