如何在线运行我的PowerShell脚本?

问题描述 投票:0回答:1

我想执行powershell内联,但是当我尝试执行所有操作时。我得到了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)

内联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);

我希望得到相同的内联结果,但我遇到了这个问题

powershell syntax command-line-interface
1个回答
0
投票

您的代码有3个问题:

  • ;语句之前缺少do(在单行上放置多个语句必须在PowerShell中分隔;) 你后来添加了这个,这使你的命令与描述的症状不一致。
  • until之后缺少do { ... }关键字 你后来补充说,但是前面的;,打破了do声明。
  • 未使用|,这意味着cmd.exe本身解释它,而不是预期的PowerShell(我假设你从cmd.exe调用它,否则没有必要通过powershell.exe调用PowerShell的CLI)。 |必须作为^|逃脱,以使cmd.exe传递给PowerShell。

解决这些问题会产生以下命令,以便在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)

如果你想从PowerShell运行你的代码,你可以直接调用它,如你问题的第一个片段所示 - 没有必要通过powershell.exe创建另一个PowerShell进程

如果由于某种原因,您确实需要创建另一个PowerShell进程,请使用脚本块语法({ ... })来传递命令,在这种情况下不需要转义:

# 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) }
© www.soinside.com 2019 - 2024. All rights reserved.