【问题标题】:running powershell script with parameters with vb.net使用 vb.net 运行带有参数的 powershell 脚本
【发布时间】:2017-10-12 15:36:49
【问题描述】:

我有一个我想用 vb.net 代码启动的 powershell 脚本,但是当它到达我调用管道的部分时,我收到错误“由于缺少一个或多个强制参数而无法处理命令:区县 FMS。” powershell 脚本非常简单,它需要 3 个参数并将主机的参数值写回 shell。几乎我的问题是,我如何使它工作?谢谢大家的时间。

vb.net(与我一起工作的其他专业人员将错误归结为“get-process”不是我的 scriptParams 变量的正确命令,但我们不确定要使用哪个命令)

Sub Main()
    Console.WriteLine(RunScript(LoadScript(Directory.GetCurrentDirectory() + "/CreateProject.ps1 ")))
    Console.ReadLine()
End Sub
Private Function RunScript(ByVal scriptText As String) As String

    ' create Powershell runspace 
    Dim MyRunSpace As Runspace = RunspaceFactory.CreateRunspace()

    ' open it 
    MyRunSpace.Open()

    ' create a pipeline and feed it the script text 
    Dim MyPipeline As Pipeline = MyRunSpace.CreatePipeline()

    MyPipeline.Commands.AddScript(scriptText)

    ' add an extra command to transform the script output objects into nicely formatted strings 
    ' remove this line to get the actual objects that the script returns. For example, the script 
    ' "Get-Process" returns a collection of System.Diagnostics.Process instances. 
    MyPipeline.Commands.Add("Out-String")

    '[ay]create a command object by bassing the command to the constructor
    Dim scriptParams As New Command("get-process")
    '[ay]pass parameters to the command
    scriptParams.Parameters.Add("District", "D1")
    scriptParams.Parameters.Add("County", "Lee")
    scriptParams.Parameters.Add("FMS", "101000")
    MyPipeline.Commands.Add(scriptParams)

    ' execute the script 
    Dim results As Collection(Of PSObject) = MyPipeline.Invoke()

    ' close the runspace 
    MyRunSpace.Close()

    ' convert the script result into a single string 
    Dim MyStringBuilder As New StringBuilder()

    For Each obj As PSObject In results
        MyStringBuilder.AppendLine(obj.ToString())
    Next

    ' return the results of the script that has 
    ' now been converted to text 
    Return MyStringBuilder.ToString()

End Function

Private Function LoadScript(ByVal filename As String) As String

    Try

        ' Create an instance of StreamReader to read from our file. 
        ' The using statement also closes the StreamReader. 
        Dim sr As New StreamReader(filename)

        ' use a string builder to get all our lines from the file 
        Dim fileContents As New StringBuilder()

        ' string to hold the current line 
        Dim curLine As String = ""

        ' loop through our file and read each line into our 
        ' stringbuilder as we go along 
        Do
            ' read each line and MAKE SURE YOU ADD BACK THE 
            ' LINEFEED THAT IT THE ReadLine() METHOD STRIPS OFF 
            curLine = sr.ReadLine()
            fileContents.Append(curLine + vbCrLf)
        Loop Until curLine Is Nothing

        ' close our reader now that we are done 
        sr.Close()

        ' call RunScript and pass in our file contents 
        ' converted to a string 
        Return fileContents.ToString()

    Catch e As Exception
        ' Let the user know what went wrong. 
        Dim errorText As String = "The file could not be read:"
        errorText += e.Message + "\n"
        Return errorText
    End Try

End Function

PowerShell

    [CmdletBinding()]

   Param(
   [Parameter(Mandatory = $True)]
   [string]$District, 
   [Parameter(Mandatory = $True)]
   [string]$County,
   [Parameter(Mandatory = $True)] 
   [string]$FMS 

   )

Write-Host "District: $Dsistrict"
Write-Host "County: $County"
Write-Host "FMS: $FMS"

【问题讨论】:

  • 你为什么要调用 get-process

标签: vb.net powershell


【解决方案1】:

这些示例使用 C# 编写,但使用相同的 API。

https://blogs.msdn.microsoft.com/kebab/2014/04/28/executing-powershell-scripts-from-c/

更多 C# 示例,但这些使用的是您在管道中已有的 RunspaceFactory API。 Execute PowerShell Script from C# with Commandline Arguments

【讨论】:

    【解决方案2】:

    我是 PowerShell 新手,但这对你有帮助

    在您的代码中

    scriptParams.Parameters.Add("District", "D1")
    
    scriptParams.Parameters.Add("County", "Lee")
    
    scriptParams.Parameters.Add("FMS", "101000")
    
    MyPipeline.Commands.Add(scriptParams)
    

    我认为这会将新参数添加到您的脚本中,因此未设置已退出参数的值

    您需要将参数值传递给脚本而不是添加新参数

    【讨论】:

      【解决方案3】:

      我知道这是一个老问题,但没有好的答案,我只是花了太长时间才解决这个问题,没有分享我的知识。

      在 VB 代码中,您将删除以下内容:

      MyPipeline.Commands.AddScript(scriptText)
      MyPipeline.Commands.Add("Out-String")
      

      然后,代替 Out-String 添加,添加:

      Dim myCommand As Command = New Command(scriptText, True)
      
      ' Add your parameters here.
      ' Obviously you can add variables instead of static strings if needed.
      myCommand.Parameters.Add("District", "D1")
      myCommand.Parameters.Add("County", "Lee")
      myCommand.Parameters.Add("FMS", "101000")
      
      ' You can add switches in this manner as well. For example, a switch "I"
      ' You need to include the - with switches
      myCommand.Parameters.Add("-i")
      
      ' Finally, apply your command object to the pipeline and proceed as normal    
      MyPipeline.Commands.Add(myCommand)
      

      【讨论】:

        猜你喜欢
        • 2018-12-22
        • 2014-07-04
        • 1970-01-01
        • 1970-01-01
        • 2015-07-06
        • 2019-04-17
        • 2012-08-21
        • 1970-01-01
        相关资源
        最近更新 更多