ein kleines Programm um Netzwerkfreigaben remote auszulesen und ggf. zu löschen.
Parameter:
PcName: der Name des PCs
Password: das lokale Adminpasswort
using System;
using System.Collections.Generic;
using System.Text;
using System.Management;
namespace FreigabenRemoteEntfernen.Net
{
class Program
{
static void Main(string[] args)
{
if (args.Length != 2)
{
Console.WriteLine("so aufrufen: \"FreigabenRemoteEnfernen.Net.exe\" \"PCName\" \"Password\"");
}
else
{
ShareLister lister = new ShareLister();
List<ManagementObject> shares = lister.ListShares(args[0], args[0] + @"\Administrator", args[1]);
Console.WriteLine("Alle Freiagben:");
Console.WriteLine(); //Leerzeile
foreach (ManagementObject share in shares)
{
Console.WriteLine(share["name"].ToString());
}
Console.WriteLine(); //Leerzeile
Console.WriteLine("Welche Freigabe soll gelöscht werden? ");
string shareName = Console.ReadLine();
bool result = false;
//Freigabe löschen
foreach (ManagementObject share in shares)
{
if (share["name"].Equals(shareName))
{
result = lister.RemoveShare(share);
}
}
if (result)
Console.WriteLine("Gelöscht");
else
Console.WriteLine("nicht gelöscht");
}
Console.ReadKey();
}
}
class ShareLister
{
public List<ManagementObject> ListShares(string computername, string username, string password)
{
List<ManagementObject> Shares = new List<ManagementObject>();
if (computername != string.Empty)
{
ManagementScope managementScope1 = new ManagementScope((@"\\" + computername + @"\root\cimv2"));
managementScope1.Options.Username = username;
managementScope1.Options.Password = password;
managementScope1.Options.EnablePrivileges = true;
ObjectQuery objectQuery1 = new ObjectQuery("SELECT * FROM Win32_Share");
ManagementObjectSearcher managementObjectSearcher1 = new ManagementObjectSearcher(managementScope1, objectQuery1);
using (ManagementObjectCollection.ManagementObjectEnumerator managementObjectEnumerator1 =
managementObjectSearcher1.Get().GetEnumerator())
{
while (managementObjectEnumerator1.MoveNext())
{
ManagementObject managementObject1 = ((ManagementObject)managementObjectEnumerator1.Current);
Shares.Add(managementObject1);
}
}
}
return Shares;
}
public bool RemoveShare(ManagementObject shareToRemove)
{
try
{
shareToRemove.InvokeMethod("Delete", new object[] { shareToRemove.Path.ToString() });
return true;
}
catch
{
return false;
}
}
}
}
Kommentare zum Snippet