相关疑难解决方法(0)

如何在代码中创建具有Write-Host命令的powershell shell中的脚本?

我有一个我正在编写的脚本,它依赖于导入模块中的函数.由于IO(Web请求),这个脚本需要一段时间,我想为脚本块的数十万次迭代进行并行化.

在尝试了几种不同的方法(由于限制Start-Job和其他方面很少成功)之后,当前的实现依赖于预创建通过创建的powershell"shell"池$shell = [Powershell]::Create().

我必须调用引导shell的模块方法之一(因此它处于正确的状态)中有一个调用Write-Host.当我调用$shell.Invoke()时出现以下错误:

Write-Host:一个命令,提示用户失败,因为主机程序或命令类型不支持用户交互.尝试支持用户交互的主机程序(如Windows PowerShell控制台或Windows PowerShell ISE),并从不支持用户交互的命令类型(如Windows PowerShell工作流)中删除与提示相关的命令.

现在,由于模块是自定义的,我可以删除Write-Host调用,但是当最终用户直接运行时,这会降低用户友好性.switch如果参数为true,我可以创建一个不执行Write-Host的参数,但要做到这一点是很好的工作(可行,但我宁愿不这样做).

Write-Host在这种情况下,我有什么方法可以避免错误吗?我实际上并不关心这种情况下的输入,我只是不想要错误.

powershell

14
推荐指数
2
解决办法
1万
查看次数

Powershell实例的Streams属性上的"Information"属性不可用于编译时

所以..非常奇怪的问题.

使用VS2015和.net 4.52

我开发了这个C#powershell代码,它正在运行一个脚本并捕获输出.像这样:

        using (PowerShell powerShellInstance = PowerShell.Create())
        {
            powerShellInstance.AddScript(scriptContents);

            Collection<PSObject> PSOutput = powerShellInstance.Invoke(); 

            if (powerShellInstance.Streams.Information.Count > 0)
            {

                    foreach (var item in powerShellInstance.Streams.Information)
                    {
                        //do something with info
                    }


                }

            }
        }
Run Code Online (Sandbox Code Playgroud)

编译和运行(在Windows 10 pro机器上),没有问题.

直到我得到一台新机器(Surface pro 4,所以也是windows 10 pro)并尝试编译代码,我收到此错误:

'PSDataStreams'不包含'Information'的定义,也没有接受'PSDataStreams'类型的第一个参数的扩展方法'Information'(你是否缺少using指令或汇编引用?)

这都是基于TFS的,所以我确定它是相同的代码.

如果我在两台机器上进行定义,问题就变得很明显了:

在此输入图像描述

所以,我注释掉了不编译代码并运行它,看看运行时发生了什么:

在此输入图像描述

那么财产就在那里..有人对此有一个很好的解释吗?

顺便说一句:msdn文档没有提到信息属性..

.net c# powershell

6
推荐指数
1
解决办法
898
查看次数

如何从 C# 中的 Powershell 脚本读取 Write-Host 输出

在 Powershell 中运行脚本时,我能够接收 Write-Host 输出,但在 C# 中则无法接收。
以下是输出 Write-Host“HELLO WORLD TEST”的代码。
当应用程序到达此行时失败:
Collection<PSObject> results = pipeline.Invoke();
我收到此错误消息:

HostException:由于宿主程序或命令类型不支持用户交互而提示用户失败的命令。尝试使用支持用户交互的主机程序(例如 Windows PowerShell 控制台或 Windows PowerShell ISE),并从不支持用户交互的命令类型(例如 Windows PowerShell 工作流)中删除与提示相关的命令

如何返回 Write-Host 的输出?提前致谢。

protected void Page_Load(object sender, EventArgs e) {

    if (!IsPostBack) {
        RunScript(@"C:\TestScript.ps1");
    }
}

private string RunScript(string scriptText) {

    Runspace runspace = RunspaceFactory.CreateRunspace();

    runspace.Open();

    Pipeline pipeline = runspace.CreatePipeline();
    pipeline.Commands.AddScript(scriptText);

    pipeline.Commands.Add("Out-String");

    Collection < PSObject > results = pipeline.Invoke();

    runspace.Close();

    StringBuilder stringBuilder = new StringBuilder();
    foreach(PSObject obj in results) {
        //do something …
Run Code Online (Sandbox Code Playgroud)

c# powershell runspace

2
推荐指数
1
解决办法
4103
查看次数

标签 统计

powershell ×3

c# ×2

.net ×1

runspace ×1