我有一个定义如下的函数:
function Get-LatestProjects
{
[CmdletBinding()]
Param
(
[Parameter(ValueFromPipeline = $true, Position = 0)]
[Company.Project.Entities.Project[]] $Projects
)
Begin {}
Process
{
...
}
End {}
}
我从C#调用此函数,代码中的参数是该类型的数组,但我收到此错误:
无法处理参数'Projects'的参数转换。无法将“Company.Project.Entities.Project []”类型的“Company.Project.Entities.Project []”值转换为“Company.Project.Entities.Project”。
拨打电话的C#代码:
var script = @". \\server01\Runspace.ps1; Get-LatestProjects $args";
var args = _pmRepository.GetAllProjects().ToArray(); // GetAllProjects returns List<Project>
using (Runspace runSpace = RunspaceFactory.CreateRunspace())
{
runSpace.Open();
var ps = PowerShell.Create();
ps.Runspace = runSpace;
ps.AddScript(script);
ps.AddArgument(args);
Collection<PSObject> results = ps.Invoke();
...
}
在将对象传递给powershell函数之前,是否需要对对象进行任何转换?或者我不能在powersject函数中为$ Projects参数添加类型约束吗?
答案 0 :(得分:1)
看起来像_pmRepository.GetAllProjects()只返回一个项目。你不能只声明$ Projects没有类型,并使用$ Projects.gettype来查看类型。
function Get-LatestProjects
{
[CmdletBinding()]
Param
(
[Parameter(ValueFromPipeline = $true, Position = 0)]
$Projects
)
Begin {
#Set-Content -path c:\temp\debug.txt -value $Projects.Gettype()
$projects | get-member -force | out-file -filepath c:\temp\debug.txt
}
Process
{
for ($i=0 ; $i -le $projects.count ; $i++)
{
$projects[$i].State | out-file -filepath c:\temp\debug.txt -append
}
}
End {}
}
----被修改------
您可以通过写入来避免将数组包装到另一个数组中。
var script = @". \\server01\Runspace.ps1; Get-LatestProjects $args[0]";