Deleting Shared Folders

Microsoft® Windows® 2000 Scripting Guide

Shared folders provide a convenient way for users to access and share resources. This also means that shared folders are a potential security risk; anything that gives remote users access to your computer provides a method by which that computer can be exploited.

As a system administrator, you want to keep track of the folders being shared on your network (especially those shared on servers); folders should be shared only if there is a valid reason for them to be shared and only if the proper security precautions are in place. If neither of these criteria is true, the share should be removed, at least until the reason for the share is clear and security is correctly implemented.

The Win32_Share class includes a Delete method that can be used to delete shared folders. The Delete method does not remove the local folder or erase any of the files stored in that folder. It simply stops the folder from being shared over the network. If you later change your mind, you can use the Create method to reshare the folder.

Scripting Steps

Listing 11.36 contains a script that deletes the FinanceShare shared folder on a computer. To carry out this task, the script must perform the following steps:

  1. Create a variable to specify the computer name.

  2. Use a GetObject call to connect to the WMI namespace root\cimv2, and set the impersonation level to "impersonate."

  3. Use the ExecQuery method to query the Win32_Share class.

    Because only one shared folder is to be deleted, a Where clause is included to limit data retrieval to the shared folder with the name FinanceShare. This results in a collection consisting of a single folder.

    To delete all the shared folders on a computer, leave out the Where clause. The resulting collection consists of all the shared folders on the computer.

  4. For each shared folder in the collection, use the Delete method to remove the share.

Listing 11.36 Deleting Network Shares


strComputer = "."
Set objWMIService = GetObject("winmgmts:" _
 & "{impersonationLevel=impersonate}!\\" & strComputer & "\root\cimv2")
Set colShares = objWMIService.ExecQuery _
 ("SELECT * FROM Win32_Share WHERE Name = 'FinanceShare'")
For Each objShare in colShares