首页 > 解决方案 > 尝试使用参数调用 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);
}

标签: c#powershell

解决方案


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

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();
}

推荐阅读