Subscribe

Get the Network Administrators tool pack

Subscribe to our newsletter and get 11 free network administrator tools, plus a 30 page user guide so you can get the most out of them.

Click Here to get your free tools

Recent Posts

Search

Archives

Remove shared folders from a script

Post image for Remove shared folders from a script

by Steve Wiseman on March 7, 2012 · 2 comments

in BAT Files,Tips,Tools,Windows 7,Windows XP


.

This week we got a question from Mark:

“Hi Steve,

I just inherited a network of about 50 computers. I noticed that many of them have all kinds of shared folders. I am trying to do some cleanup and lock-down. Wondering if you have a nice script to remove all shares, except the administrative shares like $ipc, $admin, and $c”

Good question Mark. I got just the thing for you in VB Script.

Lets start out with a script that will list all of your shares, except those admin shares:

Set objWMIService = GetObject("winmgmts:{impersonationLevel=impersonate}!\\.\root\cimv2")

Set colShares = objWMIService.ExecQuery("Select * from Win32_Share")

For each objShare in colShares
 if (objShare.Type=0) then
  WScript.Echo "Share: (" & objShare.Name & ")"
 end if
Next

The above script will query WMI for our shares, and by looking at the type we can tell if they are admin shares – non admin shares will always have a type of zero.

Delete All Shares Test

Now, what do we need to change so it will delete?

We simply need to call the ‘delete’ verb on the shared folder object:

Set objWMIService = GetObject("winmgmts:{impersonationLevel=impersonate}!\\.\root\cimv2")
'Select our list of shares on the system

Set colShares = objWMIService.ExecQuery("Select * from Win32_Share")

For each objShare in colShares
 if (objShare.Type=0) then
  WScript.Echo "Deleting Share (" & objShare.Name & ")"
  if objshare.delete then
   WScript.echo "Error Deleting Share"
  end if
 end if
Next

If the delete verb returns a non-zero value it means there was an error deleting the share.

Delete All Shares

If you want to run this on Windows 7, or Vista you will need to make sure it is in the “Computer Logon Script” (Not the user) of group policy, or it will fail – it needs the privileges to delete.

Please be careful with this one. Test, Test, Test before adding that delete command!

Get the full script from here (Rename to .vbs):

DeleteAllShares.dat

One more thing…Subscribe to my newsletter and get 11 free network administrator tools, plus a 30 page user guide so you can get the most out of them. Click Here to get your free tools

Related Articles:

{ 2 comments… read them below or add one }

1 Meatball March 9, 2012 at 12:24 pm

Thanks for the tip steve. I didn’t know you could detect the admin shares like that.

2 Jennifer March 9, 2012 at 12:25 pm

Thanks for the script steve. Works perfect for me.

Leave a Comment

Category Links - Windows Forum - Exchange Forum