using System;
using System.Collections.Generic;
using System.Text;
using Microsoft.Win32;
using System.IO;
using System.Security.Principal;
using System.Runtime.InteropServices;
using System.Diagnostics;
namespace DelProfs
{
class Program
{
private static string m_skeyName = "";
public static string skeyName
{
get { return m_skeyName; }
set { m_skeyName = value; }
}
private static string m_sHKLMkeyName = "";
public static string sHKLMkeyName
{
get { return m_sHKLMkeyName; }
set { m_sHKLMkeyName = value; }
}
private static string m_sFile2Check = "";
public static string sFile2Check
{
get { return m_sFile2Check; }
set { m_sFile2Check = value; }
}
[DllImport("userenv.dll", SetLastError = true)]
static extern bool DeleteProfile(string lpSidString, string lpProfilePath, string lpcomputername);
[DllImport("kernel32", SetLastError = true, CallingConvention = CallingConvention.Winapi)]
public extern static IntPtr LoadLibrary(string libraryName);
[DllImport("kernel32", SetLastError = true, CallingConvention = CallingConvention.Winapi)]
public extern static IntPtr GetProcAddress(IntPtr hwnd, string procedureName);
static void Main(string[] args)
{
//if (Is32BitProcessOn64BitProcessor())
//{
// skeyName = "HKEY_LOCAL_MACHINE\\SOFTWARE\\Wow6432Node\\Microsoft\\Windows NT\\CurrentVersion\\ProfileList";
// sHKLMkeyName = "SOFTWARE\\Wow6432Node\\Microsoft\\Windows NT\\CurrentVersion\\ProfileList";
//}
//else
//{
skeyName = "HKEY_LOCAL_MACHINE\\SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion\\ProfileList";
sHKLMkeyName = "SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion\\ProfileList";
//}
sFile2Check = "NTUSER.DAT";
//const string lpcomputername = null;
if (args.Length == 0)
{
System.Console.WriteLine("Please Enter the Age of Profiles to Delete in Days.");
System.Console.WriteLine("Usage: DelProfs
System.Console.WriteLine();
return;
//return 1;
}
string sdefUserDomain = "";
string sdefUserName = "";
int num;
bool test = int.TryParse(args[0], out num);
if (test == false)
{
System.Console.WriteLine("Please Enter the Age of Profiles to Delete in Days.");
System.Console.WriteLine("Usage: DelProfs
System.Console.WriteLine();
return;
//return 1;
}
if (args.Length == 3)
{
//get the default domain and username passed from smartbutton
sdefUserDomain = args[1].ToUpper();
sdefUserName = args[2].ToUpper();
//System.Console.WriteLine(sdefUser);
//return;
}
string sComputerName = "";
sComputerName = (string)Registry.GetValue("HKEY_LOCAL_MACHINE\\SYSTEM\\CurrentControlSet\\Control\\ComputerName\\ActiveComputerName","Computername","");
//return;
//int iMaxAge = 10;
int iMaxAge = num;
string sProfilePath = (string)Registry.GetValue(skeyName, "ProfilesDirectory", "");
sProfilePath = Environment.ExpandEnvironmentVariables(sProfilePath);
if (sProfilePath != "")
{
try
{
foreach (string sdir in Directory.GetDirectories(sProfilePath))
{
//System.Console.WriteLine(sdir);
//string sTemp = Path.Combine(sdir, "HELPASSISTANT");
if ((sdir.ToUpper().Contains(sComputerName)) && (sComputerName != ""))
{
DeleteUserProfileKey(Path.Combine(sdir, "HELPASSISTANT"));
}
DateTime dFolderAge = getFolderDateModified(sdir);
int iAge = HowOld(dFolderAge);
if (iAge > iMaxAge)
{
string scheck = Path.Combine(sdir, sFile2Check);
if ((File.Exists(scheck))
((File.GetAttributes(scheck) & FileAttributes.Hidden) == FileAttributes.Hidden))
{
//check owner
//string sowner = "";
string sowner = getFileOwner(Path.Combine(sdir, sFile2Check));
if (sowner.IndexOf("\\") > 0)
{
string[] split = null;
char[] splitchar = { '\\' };
split = sowner.Split(splitchar);
string sDomainNaime = split[0];
string sUserName = split[1];
if ((sDomainNaime.ToUpper() == "BUILTIN")
(sDomainNaime.ToUpper() == "NT AUTHORITY")
(sDomainNaime.ToUpper() == "ERROR")
(sDomainNaime.ToUpper() == "WINDOWSLIVEID")
(sDomainNaime.ToUpper() == "IIS APPPOOL")
((sDomainNaime.ToUpper() == sdefUserDomain.ToUpper()) && (sUserName.ToUpper() == sdefUserName.ToUpper())
(sUserName.ToUpper().Contains("CLEARCASE")))
)
{
//Excluded account profiles
}
else
{
//ForceDeleteDirectory(sdir);
//DeleteUserProfileKey(sdir);
DeleteUserProfileKey(sdir);
}
}
else
{
// not a domain account
}
}
else
{
//no ntuser.dat found so delete it anyway
//ForceDeleteDirectory(sdir);
//DeleteUserProfileKey(sdir);
DeleteUserProfileKey(sdir);
}
}
}
}
catch (Exception)
{
//Console.WriteLine(excpt.Message);
}
}
else { }
}
public static int HowOld(DateTime d1)
{
TimeSpan ts = DateTime.Now - d1;
return Math.Abs(ts.Days);
}
public static void DeleteUserProfileKey(string sProfilePath)
{
//string keyName = "LOCAL_MACHINE\\SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion\\ProfileList";
Boolean bfound = false;
try
{
using (RegistryKey profileList = Registry.LocalMachine.OpenSubKey(sHKLMkeyName))
{
//Get a list of SIDs corresponding to each profile on the computer
string[] sidList = profileList.GetSubKeyNames();
foreach (string ssid in sidList)
{
try
{
string sRegPath = Path.Combine(skeyName, ssid);
string sProfileTestPath = (string)Registry.GetValue(sRegPath, "ProfileImagePath", "");
if (sProfileTestPath.ToUpper() == sProfilePath.ToUpper())
{
DeleteProfile(ssid, sProfilePath, null);
bfound = true;
ForceDeleteDirectory(sProfilePath);
DeleteProfile(ssid, sProfilePath, null);
}
// }
}
catch (Exception)
{
//Console.WriteLine(e.Message);
}
}
if (bfound == false)
{
ForceDeleteDirectory(sProfilePath);
}
}
}
catch (Exception)
{
// Console.WriteLine(e.Message);
}
}
public static void deleteRegKeySub(string skey)
{
try
{
Registry.LocalMachine.DeleteSubKeyTree(skey);
}
catch (Exception)
{
}
}
public static string getFileOwner(string sFile)
{
try
{
if (File.Exists(sFile))
{
var fs = File.GetAccessControl(sFile);
var sid = fs.GetOwner(typeof(SecurityIdentifier));
//Console.WriteLine(sid); // SID
var ntAccount = sid.Translate(typeof(NTAccount));
//Console.WriteLine(ntAccount); // DOMAIN\username
return ntAccount.ToString().ToUpper();
}
else
{
return "";
}
}
catch (Exception)
{
return "";
}
}
public static DateTime getFolderDateModified(string sFolderPath)
{
try
{
string spath = @sFolderPath;
if (!Directory.Exists(spath))
{
return DateTime.Now;
}
else
{
return Directory.GetLastWriteTime(spath);
}
}
catch (Exception)
{
return DateTime.Now;
}
}
//private static void DeleteFileSystemInfo(FileSystemInfo fsi)
//{
// fsi.Attributes = FileAttributes.Normal;
// var di = fsi as DirectoryInfo;
// if (di != null)
// {
// foreach (var dirInfo in di.GetFileSystemInfos())
// DeleteFileSystemInfo(dirInfo);
// }
// fsi.Delete();
//}
public static void ForceDeleteDirectory(string path)
{
DirectoryInfo root;
Stack
DirectoryInfo fol;
try
{
fols = new Stack
root = new DirectoryInfo(path);
fols.Push(root);
while (fols.Count > 0)
{
fol = fols.Pop();
fol.Attributes = fol.Attributes & ~(FileAttributes.Archive
FileAttributes.ReadOnly
FileAttributes.Hidden);
foreach (DirectoryInfo d in fol.GetDirectories())
{
fols.Push(d);
}
foreach (FileInfo f in fol.GetFiles())
{
f.Attributes = f.Attributes & ~(FileAttributes.Archive
FileAttributes.ReadOnly
FileAttributes.Hidden);
f.Delete();
}
}
root.Delete(true);
}
catch { }
}
private delegate bool IsWow64ProcessDelegate([In] IntPtr handle, [Out] out bool isWow64Process);
public static bool IsOS64Bit()
{
try
{
if (IntPtr.Size == 8
(IntPtr.Size == 4 && Is32BitProcessOn64BitProcessor()))
{
return true;
}
else
{
return false;
}
}
catch (Exception)
{
return false;
}
}
private static IsWow64ProcessDelegate GetIsWow64ProcessDelegate()
{
try
{
IntPtr handle = LoadLibrary("kernel32");
if (handle != IntPtr.Zero)
{
IntPtr fnPtr = GetProcAddress(handle, "IsWow64Process");
if (fnPtr != IntPtr.Zero)
{
return (IsWow64ProcessDelegate)Marshal.GetDelegateForFunctionPointer((IntPtr)fnPtr, typeof(IsWow64ProcessDelegate));
}
}
}
catch (Exception)
{ }
return null;
}
private static bool Is32BitProcessOn64BitProcessor()
{
bool isWow64 = false;
bool retVal = false;
try
{
IsWow64ProcessDelegate fnDelegate = GetIsWow64ProcessDelegate();
if (fnDelegate == null)
{
return false;
}
retVal = fnDelegate.Invoke(Process.GetCurrentProcess().Handle, out isWow64);
}
catch (Exception)
{ }
if (retVal == false)
{
return false;
}
return isWow64;
}
}
}