【发布时间】:2018-07-18 02:12:40
【问题描述】:
我正在尝试通过 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);
}
【问题讨论】:
-
.... var process = new Process(); .... process.Start();为什么不使用这种方法?
-
如何创建运行空间来运行多个命令?
-
不幸的是,这不起作用。我更新了我的代码并包含了 PowerShell 脚本。
-
您没有在当前范围内执行
D:\TestTransform\transform.ps1,因此脚本完成后XmlDocTransform将消失。在第一个Invoke之后,您没有清理命令,因此第二个Invoke有效地调用. {D:\TestTransform\transform.ps1} | XmlDocTransform …。powerShellParameters中的参数名称与XmlDocTransform函数中声明的名称不匹配。
标签: c# powershell