【发布时间】:2013-04-04 21:20:37
【问题描述】:
我有一个名为“Get-Connections”的函数,它返回一些 sql 连接的列表,例如:
PS C:\Windows\system32> Get-Connections
Id : e1a2fd17-91aa-4975-b1ee-1a7df65e6d6b
DataSource : myDataSource1
InitialCatalog : myInitCatalog
UseIntegratedSecurity : True
DisplayName : testConnection
Id : 2688f2af-1b49-405f-aa92-417a43b76dca
DataSource : myDataSource1
InitialCatalog : myInitCatalog
UseIntegratedSecurity : True
DisplayName : testConnection
我还有一个名为“Remove-connection”的函数,它通过 Id 删除连接:
Remove-Connection "2688f2af-1b49-405f-aa92-417a43b76dca"
现在我尝试使用删除所有连接
Get-Connections | % { Remove-Connection $_.Id }
这不起作用,例外是:
Remove-Connection : Cannot convert 'System.Object[]' to the type 'System.Guid' required by parameter 'Id'. Specified method is not supported.
实际工作是这样的:
Get-Connections | % { $_.Id } | % { Remove-Connection "$_" }
前面的说法有什么问题?
更新 1。
获取连接:
[Cmdlet(VerbsCommon.Get, "Connections", SupportsShouldProcess = true)]
public class GetConnectionsCommand : Cmdlet
{
private List<ConnectionDto> Connections { get; set; }
public void GetConnections()
{
var binding = new BasicHttpBinding();
var address = new EndpointAddress(Address);
var repositoryService = new WcfConnectionRepositoryServiceProxy(binding, address);
Connections = repositoryService.GetAll().ToList();
}
protected override void BeginProcessing()
{
base.BeginProcessing();
GetConnections();
}
protected override void ProcessRecord()
{
base.ProcessRecord();
WriteObject(Connections);
}
}
删除连接:
[Cmdlet(VerbsCommon.Remove, "Connection", SupportsShouldProcess = true)]
public class RemoveConnectionCommand : Cmdlet
{
[Parameter(Position = 0, ParameterSetName = "Id",
Mandatory = true, ValueFromPipeline = true,
ValueFromPipelineByPropertyName = true,
HelpMessage = "Please enter the ID of the connection to remove")]
[ValidateNotNullOrEmpty]
public Guid Id { get; set; }
private void RemoveConnection()
{
var binding = new BasicHttpBinding();
var address = new EndpointAddress(Address);
var repositoryService = new WcfConnectionRepositoryServiceProxy(binding, address);
repositoryService.Delete(Id);
}
protected override void BeginProcessing()
{
base.BeginProcessing();
RemoveConnection();
}
}
DTO:
[DataContract(Name = "ConnectionDto"]
public class ConnectionDto
{
[DataMember]
public Guid Id { get; set; }
[DataMember]
public string DataSource { get; set; }
...
【问题讨论】:
-
Get-Connections的返回类型是什么?列表还是数组? -
或者更具体地说,
Get-Connections返回的对象的Id属性的类型是什么?你试过Get-Connections | % { Remove-Connection $_.Id.ToString() }吗? -
Get-Connections 的类型是 ConnectionDTO 的列表。 ConnectionDTO 的 Id 属性是一个 GUID,而 Remove-Connection 也需要一个 GUID。您的示例也不起作用:Remove-Connection:无法绑定参数“Id”。无法将值“System.Object[]”转换为类型“System.Guid”。错误:“Guid 应包含 32 位数字和 4 个破折号
-
您确定 ID 是 guid 吗?看来它是一个具有 guid 属性的对象,而该 guid 是该对象的默认输出。
-
你试过
Get-Connections | % {Remove-Connection "$($_.Id)"}吗?
标签: powershell