繁体   English   中英

使用C#将参数传递到Powershell

[英]passing parameters with c# to powershell

我试图将字符串从我的C#应用​​程序传递到我的Powershell脚本。

我不断收到错误消息:“找不到一个接受参数'$null'位置参数
我该怎么办?

我的C#代码:

  public void PowerShell()
    {
        RunspaceConfiguration runspaceConfiguration = RunspaceConfiguration.Create();
        Runspace runspace = RunspaceFactory.CreateRunspace(runspaceConfiguration);
        runspace.Open();
        RunspaceInvoke scriptInvoker = new RunspaceInvoke(runspace);

        Pipeline pipeline = runspace.CreatePipeline();

        String scriptfile = @"c:\test.ps1";

        Command myCommand = new Command(scriptfile, false);

        CommandParameter testParam = new CommandParameter("username", "serverName");

        myCommand.Parameters.Add(testParam);


        pipeline.Commands.Add(myCommand);
        Collection<PSObject> psObjects;
        psObjects = pipeline.Invoke(); <---error- "A positional parameter cannot be found that accepts argument '$null'" 
        runspace.Close();

    }

我的PowerShell代码:

 Out-Host  $username

您的PS脚本没有参数,仅使用变量。 因此,请尝试以下操作:

Param($username)
Write-Output $username

请注意,在您的情况下,Out-Host是不可接受的,因为它试图将参数输出到调用范围,而不是简单地将一些内容写入输出流。

另外,您可以在运行空间中设置变量,因此它将在不带参数的脚本中可用:

runspace.SessionStateProxy.SetVariable("username", "SomeUser");

(必须在runspace.Open()之后和pipeline.Invoke()之前完成)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM