Deleting Folders with WMI

I recently saw a question about deleting folders with WMI.

Let’s create a file structure we’re happy to delete

New-Item -Path c:\ -Name Expendable -ItemType Directory
New-Item -Path c:\Expendable -Name Target1  -ItemType Directory
New-Item -Path c:\Expendable -Name Target2  -ItemType Directory

Get-Process | Out-File -FilePath c:\Expendable\Target1\proc.txt
Get-Service | Out-File -FilePath c:\Expendable\Target2\serv.txt


A look through the WMI classes brings out Win32_Directory

PS> $class = Get-CimClass -ClassName Win32_Directory
PS> $class.CimClassMethods | ft -a

Name                        ReturnType Parameters
—-                        ———- ———-
TakeOwnerShip                   UInt32 {}
ChangeSecurityPermissions       UInt32 {Option, SecurityDescriptor}
Copy                            UInt32 {FileName}
Rename                          UInt32 {FileName}
Delete                          UInt32 {}
Compress                        UInt32 {}
Uncompress                      UInt32 {}
TakeOwnerShipEx                 UInt32 {Recursive, StartFileName, StopFileName}
ChangeSecurityPermissionsEx     UInt32 {Option, Recursive, SecurityDescriptor,…}
CopyEx                          UInt32 {FileName, Recursive, StartFileName, StopFileName}
DeleteEx                        UInt32 {StartFileName, StopFileName}
CompressEx                      UInt32 {Recursive, StartFileName, StopFileName}
UncompressEx                    UInt32 {Recursive, StartFileName, StopFileName}
GetEffectivePermission         Boolean {Permissions}


The Delete method looks promising

CIM uses inert objects so we need to get an instance an pipe it into Invoke-CimMethod

Get-CimInstance -ClassName Win32_Directory -Filter “Name=’C:\\Expendable'” |
Invoke-CimMethod -MethodName Delete

When you delete a folder like this – the folder, its contents, any subfolders and their contents are deleted. They don’t appear in the recycle bin either so its a one way trip

This entry was posted in File system, PowerShell and WMI, PowerShell V3. Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s