从托管PowerShell中的脚本或命令检索参数

时间:2014-03-05 17:56:27

标签: .net powershell clr

我在我的VB.net应用程序中托管PowerShell。我希望能够在运行时弄清楚我正在运行的任何随机脚本的参数。例如,给出代码:

 Using powerShellObject As PowerShell = PowerShell.Create

    powerShellObject.AddScript("get-process")
    powerShellObject.AddParameter("FileVersionInfo", "")
    Dim output As New PSDataCollection(Of PSObject)()
    AddHandler output.DataAdded, AddressOf Output_DataAdded
    AddHandler powerShellObject.InvocationStateChanged, AddressOf Powershell_InvocationStateChanged

    ' Invoke the pipeline asynchronously.
    Dim asyncResult As IAsyncResult = powerShellObject.BeginInvoke(Of PSObject, PSObject)(Nothing, output)

    While powerShellObject.InvocationStateInfo.State <> PSInvocationState.Completed
        System.Threading.Thread.Sleep(0)
    End While

End Using

我希望能够通过'AddScript'确定我添加的脚本的参数(我知道get-process可以采取

Get-Process [-ComputerName <String[]>] [-FileVersionInfo] [-Module] -Id <Int32[]> [<CommonParameters>]

但我希望我的用户能够提交任何随机脚本,我希望能够在运行时找出这些参数。

我该怎么做?

1 个答案:

答案 0 :(得分:2)

Get-Command -Syntax MyScript.ps1

将返回语法。我认为这仅限于从脚本处理param语句(做更多的事情会相当困难)。

这也适用于cmdlet(并且非常有用,比阅读帮助,查找参数名称更快)。

获取每个参数数据:

(Get-Command MyScript).Parameters

是由参数名称System.Management.Automation.ParameterMetadata键入的哈希值,其中包含各种有趣的信息。