尝试使用参数调用PowerShell函数

时间:2018-07-17 15:47:13

标签: c# powershell

我正在尝试通过C#调用PowerShell脚本中的脚本来执行功能。该函数有两个参数。但是,我收到一个错误消息,该函数不是公认的cmdlet,函数等。根据我的代码,有人可以协助我解决我做错的事情吗?

string powerShellScript = @"D:\TestTransform\transform.ps1";
IDictionary powerShellParameters = new Dictionary<string, string>();
powerShellParameters.Add("configFile", file);
powerShellParameters.Add("transformFile", transformFile);

Runspace runspace = RunspaceFactory.CreateRunspace();
runspace.Open();

using (PowerShell powerShellInstance = PowerShell.Create())
{
    powerShellInstance.Runspace = runspace;
    powerShellInstance.AddScript(powerShellScript);
    powerShellInstance.Invoke();

    powerShellInstance.AddCommand("XmlDocTransform");
    powerShellInstance.AddParameters(powerShellParameters);

    Collection<PSObject> psOutput = powerShellInstance.Invoke(); //breaks here
}

我的Powershell脚本:

function XmlDocTransform($xml, $xdt)
{
    if (!$xml -or !(Test-Path -path $xml -PathType Leaf)) {
        throw "File not found. $xml";
    }
    if (!$xdt -or !(Test-Path -path $xdt -PathType Leaf)) {
        throw "File not found. $xdt";
    }

    $scriptPath = $PSScriptRoot + "\"
    Add-Type -LiteralPath "$scriptPath\Microsoft.Web.XmlTransform.dll"

    $xmldoc = New-Object Microsoft.Web.XmlTransform.XmlTransformableDocument;
    $xmldoc.PreserveWhitespace = $true
    $xmldoc.Load($xml);

    $transf = New-Object Microsoft.Web.XmlTransform.XmlTransformation($xdt);
    if ($transf.Apply($xmldoc) -eq $false)
    {
        throw "Transformation failed."
    }
    $xmldoc.Save($xml);
}

1 个答案:

答案 0 :(得分:0)

您的职能遵循一些社区最佳实践:

function ConvertTo-XmlDoc {
    [CmdletBinding()]
    [OutputType('System.Void')]
    param(
        [Parameter(Position = 0, Mandatory)]
        [ValidateScript({
            if (-not (Test-Path -Path $PSItem -PathType Leaf)) {
                throw "File not found: $PSItem"
            }
            return $true
        })]
        [string] $Xml,

        [Parameter(Position = 1, Mandatory)]
        [ValidateScript({
            if (-not (Test-Path -Path $PSItem -PathType Leaf)) {
                throw "File not found: $PSItem"
            }
            return $true
        })]
        [string] $Xdt
    )

    Add-Type -LiteralPath "$PSScriptRoot\Microsoft.Web.XmlTransform.dll"

    $xmldoc = [Microsoft.Web.XmlTransform.XmlTransformableDocument]::new()
    $xmldoc.PreserveWhitespace = $true
    $xmldoc.Load($Xml)

    $transform = [Microsoft.Web.XmlTransform.XmlTransformation]::new($Xdt)
    if (-not $transform.Apply($xmldoc)) {
        throw 'Transformation failed.'
    }
    $xmldoc.Save($Xml)
}

下面应该起作用的代码:

using (var ps = PowerShell.Create())
{
    ps.AddScript($@". 'D:\TestTransform\transform.ps1'; ConvertTo-XmlDoc -Xml {file} -Xdt {transformFile}");

    ps.Invoke();
}