Powershell - 可以对函数参数使用自定义对象类型约束吗?
我有一个函数定义如下:
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 函数之前,是否需要对对象进行任何转换?或者我可以不在 powershell 函数中为 $Projects 参数添加类型约束吗?
I have a function defined as follows:
function Get-LatestProjects
{
[CmdletBinding()]
Param
(
[Parameter(ValueFromPipeline = $true, Position = 0)]
[Company.Project.Entities.Project[]] $Projects
)
Begin {}
Process
{
...
}
End {}
}
I'm calling this function from C# and the parameter in the code is an array of that type, but I'm getting this error:
Cannot process argument transformation on parameter 'Projects'. Cannot convert the "Company.Project.Entities.Project[]" value of type "Company.Project.Entities.Project[]" to type "Company.Project.Entities.Project".
The C# code that makes the call:
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();
...
}
Do I need to do any conversion of the objects before I pass them to the powershell function? Or can I not add a type constraint in the powershell function for the $Projects parameter?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
看起来 _pmRepository.GetAllProjects() 仅返回一个项目。难道你不能只声明没有类型的 $Projects 并使用 $Projects.gettype 来查看类型吗?
----已编辑------
您可以通过写入来避免您的数组被包装到另一个数组中。
It looks like _pmRepository.GetAllProjects() return only one project. Can't you just declare $Projects without type and use $Projects.gettype to have a look to the type.
----Edited------
You can avoid your array to be wraped into another array by writting.