Finding and Deleting Orphaned Shares

by Mar 23, 2009

Maybe you never noticed but when you delete folders that were shared on the network, the share may be left behind. To locate shares that have no folder anymore, use WMI and the Win32_Share class to give you the folder path that the share is pointing toward. Next, use Test-Path to see if the path still exists:

Get-WmiObject Win32_Share | Where-Object { $_.Path -ne '' }  |
Where-Object { -not (test-path $_.Path) }

Your system is in good shape if this line does not return any results. Orphaned shares can occur when a shared folder is deleted in a low-level way. When you delete a shared folder with Explorer, you will also delete the share. But deleting a shared folder from within a VBScript, a batch file or PowerShell will only reproduce the problem.

  1. Create a folder: md c:testfolder
  2. Share the folder using Explorer
  3. Delete the folder: del c:testfolder

To automatically remove shares that have no target folder anymore, use this line:

Get-WmiObject Win32_Share | Where-Object { $_.Path -ne '' } |
Where-Object { -not (test-path $_.Path) } | ForEach-Object { $_.Delete() }

Note that you may need administrator privileges, depending on who created the share.