PS1 Start-Process 脚本错误 - 无法在管道中间运行文档

时间:2021-04-04 23:49:11

标签: powershell

我有 1 个 .psm1 形式的 PowerShell 脚本,因此我可以拥有一个自定义 cmdlet。问题是,我不知道自己在做什么,所以我刚刚找到了一篇文章。我复制了这篇文章,我所做的唯一更改是将 cmdlet 函数更改为“Start-Process”。我还让它启动了 WT.exe(Windows 终端)并添加了在普通 ps1 文件中完美运行的参数。

我的代码:

    Function txtedit
    {
        Start-Process -FilePath 'wt.exe' -ArgumentList "-NoExit python C:\Users\hjdom\OneDrive\Documents\pyUtils\texteditor\main.py"
    }

Export-ModuleMember -Function 'txtedit'

PowerShell 返回的错误:

PS C:\Windows\System32\WindowsPowerShell\v1.0\Modules\txtedit> c:\Windows\System32\WindowsPowerShell\v1.0\Modules\txtedit\txtedit.psm1
Cannot run a document in the middle of a pipeline: C:\Windows\System32\WindowsPowerShell\v1.0\Modules\txtedit\txtedit.psm1.
    + CategoryInfo          : InvalidOperation: (C:\Windows\Syst...it\txtedit.psm1:String) [], ParentContainsErrorRecordException
    + FullyQualifiedErrorId : CantActivateDocumentInPipeline
谢谢!

1 个答案:

答案 0 :(得分:0)

Windows 终端 (wt.exe) 不是命令外壳。

它是命令 shell(powershell、bash、cmd、python、perl 等)的主机。您必须告诉 WT.exe 使用哪个,以调用您的脚本。

示例 - cmd.exe 或通过 WinKey Run:

类型:

wt d:\temp\hello.ps1

这将失败...

[error 0x800700c1 when launching `d:\temp\hello.ps1']

...即使 Windows 终端使用您的 WT 设置中的任何默认 shell 启动。

现在做这个...

wt.exe powershell D:\Scripts\hello.ps1

...这是有效的,因为您告诉 wt.exe 使用哪个 shell 来执行您的脚本。

<块引用>

但是我如何防止终端在脚本之后关闭 跑完了吗?

您的目标 shell 需要为此提供一种方法。 Powershell(Windows 和 Core)通过 -NoExit 开关提供此功能。

powershell /?

PowerShell[.exe] [-PSConsoleFile <file> | -Version <version>]
    [-NoLogo] [-NoExit] [-Sta] [-Mta] [-NoProfile] [-NonInteractive]
    [-InputFormat {Text | XML}] [-OutputFormat {Text | XML}]
    [-WindowStyle <style>] [-EncodedCommand <Base64EncodedCommand>]
    [-ConfigurationName <string>]
    [-File <filePath> <args>] [-ExecutionPolicy <ExecutionPolicy>]
    [-Command { - | <script-block> [-args <arg-array>]
                  | <string> [<CommandParameters>] } ]

wt.exe powershell -NoProfile -NoLogo -NoExit D:\Scripts\hello.ps1

wt.exe pwsh -NoProfile -NoLogo -NoExit D:\Scripts\hello.ps1

如果您正在调用另一个 shell、bash、python、perl 等,那么他们也需要提供。