powershellrecycle-bin

how to run this powershell command without curly braces{}


enter image description here

$objShell = New-Object -Com Shell.Application
$objFolder = $objShell.Namespace(0xA)
Remove-Item ($objFolder.items() | select path | where-object { $_.path -like "C:\*" }).path -Recurse -Confirm:$false

I would like take only the path with C:\ and delete it from recycle bin. But I want to do it without using {} . as u will know where-object needs curly braces. if there's any other way, kindly let me know.

I use powershell version 4 and I prefer code for lower versions only. Thanks in advance.


Solution

  • Mathias R. Jessen's helpful answer directly answers your question by demonstrating simplified Where-Object syntax (a PSv3+ feature known as a comparison statement).

    However, in your case you can bypass Where-Object altogether, and apply the -like operator directly to the (transformed) enumeration of items returned by $objFolder.items():

    Using PSv2+ syntax:

    Remove-Item (
       @($objFolder.items() | Select-Object -ExpandProperty Path) -like 'C:\*'
     ) -Recurse -Confirm:$false
    

    Note that the use of @() ensures that -like acts on an array-valued LHS and therefore acts as an element filter.

    -ExpandProperty ensures that .Path property values are returned rather than custom objects with a .Path property.


    In PSv3+ you can simplify and speed up the command by using member-access enumeration, which means accessing a property at the collection level in order to return the collection elements' property values:

    Remove-Item (
       @(@($objFolder.items()).Path) -like 'C:\*'
     ) -Recurse -Confirm:$false
    

    Note that the inner @(...), around $objFolder.items(), is only necessary because $objFolder is a COM object whose properties don't behave like regular .NET collections in PowerShell; @(...) forces enumeration in this case.