0

This question asks which verb to use to "delete" a resource created with new-Thing. Remove is the natural accepted verb, and so you have a remove-Thing cmdlet.

But we have several cases where Thing is also a container, which we can add items to or remove items from. At the moment we have

    Remove-Thing myThing                   # Destroys myThing
    Remove-ItemFromThing myThing myItem    # Removes myItem from myThing

which is pretty horrible. Is there a more elegant way of doing this?

Cœur
  • 37,241
  • 25
  • 195
  • 267
Rob
  • 4,327
  • 6
  • 29
  • 55

2 Answers2

1

You could extend the members of your Thing container with a Remove method via ScriptMethod. So you could do this:

$Thing.Item.Remove()

Given that there is no Remove-Member to pair with Add-Memeber cmdlet, this looks like valid approach.

beatcracker
  • 6,714
  • 1
  • 18
  • 41
  • I'm fairly new to PowerShell, I can't see where I'm specifying which item to remove. Do you mean `$Thing[$Item].Remove()`? Or `$Thing.Item.Remove($item)`? – Rob Apr 10 '15 at 15:01
  • Actually - looking for `Remove-Member` in PowerShell's intellisense showed me `Remove-RoleMember` from SqlAS, which suggests `Remove-ThingMember`. – Rob Apr 10 '15 at 15:07
  • You can do it both ways: `$Thing[Item].Remove()` and `$Thing.Item.Remove()` are equal. Off the top of head, only arrays require `$Array[Index]` notation, other object like `PsObjects`, `hashtables` and so on can be accessed either way. You can also extend `$Thing` with `RemoveItem` method and pass Item name\id to it: `$Thing.RemoveItem(item)`. – beatcracker Apr 10 '15 at 15:07
  • @Rob `Remove-RoleMember` doesn't have a parent `Add-Role` cmdlet (I think the roles are fixed), so that makes sense for Analysis Services, but it doesn't feels right for me in your case. – beatcracker Apr 10 '15 at 15:16
0

A couple of ideas come to mind.

The first is that the objects in the container should not be named the same as the container. So if your container is Thing then you have:

Remove-Thing  #destroys Thing

The objects inside Thing should not be named Thing. Let's say that they are named Part. Then you would have:

Remove-Part Thing Part # Removes Part from Thing

This would remove a Part from a Thing container.

The other way that comes to mind would be to attach a method to Thing that removes a Part. So you would do:

Thing.RemovePart(Part)
EBGreen
  • 36,735
  • 12
  • 65
  • 85
  • We already have `Remove-Part myPart`, to destroy myPart. I can add an optional `-FromThing` parameter, which would look syntactically nice, but I'm worried this may be confusing/error prone. – Rob Apr 10 '15 at 14:56
  • @Rob If `-FromThing` would accept a value from pipeline, that would look very PowerShell-like to me: `$Thing | Remove-Part -Name myPart`. – beatcracker Apr 10 '15 at 15:13