upd
This commit is contained in:
@@ -1,161 +1,273 @@
|
|||||||
using System;
|
using System.Net.NetworkInformation;
|
||||||
using System.IO;
|
|
||||||
using System.Diagnostics;
|
|
||||||
using System.Threading;
|
|
||||||
using System.Linq;
|
|
||||||
|
|
||||||
class FileDeleter
|
class FileSearchProgram
|
||||||
{
|
{
|
||||||
static int deletedCount = 0;
|
static string resultFilePath = "results.txt";
|
||||||
static int failedCount = 0;
|
|
||||||
static int skippedCount = 0;
|
|
||||||
|
|
||||||
static void Main(string[] args)
|
static void Main(string[] args)
|
||||||
{
|
{
|
||||||
Console.WriteLine("Удаление файлов по списку");
|
// Очищаем файл результатов при каждом новом запуске
|
||||||
string listFilePath = "results450.txt";
|
File.WriteAllText(resultFilePath, $"Запуск программы: {DateTime.Now}\n\n");
|
||||||
|
|
||||||
if (!File.Exists(listFilePath))
|
Console.WriteLine("Программа поиска и удаления папки программы на доменных компьютерах");
|
||||||
{
|
LogToFile("Программа поиска и удаления папки программы на доменных компьютерах");
|
||||||
Console.WriteLine("Файл со списком не найден!");
|
|
||||||
Console.ReadKey();
|
string fileName = "DowntimeClassifier.exe";
|
||||||
return;
|
string folderToDelete = "";
|
||||||
}
|
string searchPath = "D:\\lrpo\\downtimeclassifier";
|
||||||
|
string computersFile = "computers.txt";
|
||||||
|
|
||||||
try
|
try
|
||||||
{
|
{
|
||||||
string[] filesToDelete = File.ReadAllLines(listFilePath)
|
if (!File.Exists(computersFile))
|
||||||
.Where(f => !string.IsNullOrWhiteSpace(f))
|
{
|
||||||
|
string error = $"Файл {computersFile} не найден. Создайте файл со списком компьютеров.";
|
||||||
|
Console.WriteLine(error);
|
||||||
|
LogToFile(error);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
string[] computers = File.ReadAllLines(computersFile)
|
||||||
|
.Where(c => !string.IsNullOrWhiteSpace(c))
|
||||||
.ToArray();
|
.ToArray();
|
||||||
|
|
||||||
Console.WriteLine($"Найдено {filesToDelete.Length} файлов для обработки...\n");
|
string startMessage = $"Начинаем обработку {computers.Length} компьютеров...";
|
||||||
|
Console.WriteLine(startMessage);
|
||||||
|
LogToFile(startMessage);
|
||||||
|
|
||||||
foreach (string filePath in filesToDelete)
|
Console.WriteLine("\nВыберите режим работы:");
|
||||||
|
Console.WriteLine("1 - Только поиск файла");
|
||||||
|
Console.WriteLine("2 - Только удаление папки");
|
||||||
|
Console.WriteLine("3 - Поиск файла + удаление папки");
|
||||||
|
Console.WriteLine("4 - Только поиск папки");
|
||||||
|
Console.Write("Введите номер режима (1/2/3/4): ");
|
||||||
|
string mode = Console.ReadLine()?.Trim() ?? "1";
|
||||||
|
|
||||||
|
foreach (string computer in computers)
|
||||||
{
|
{
|
||||||
ProcessFile(filePath);
|
|
||||||
}
|
|
||||||
|
|
||||||
Console.WriteLine($"\nИтог:");
|
|
||||||
Console.WriteLine($"Успешно удалено: {deletedCount}");
|
|
||||||
Console.WriteLine($"Не удалось удалить: {failedCount}");
|
|
||||||
Console.WriteLine($"Пропущено (не существует): {skippedCount}");
|
|
||||||
}
|
|
||||||
catch (Exception ex)
|
|
||||||
{
|
|
||||||
Console.WriteLine($"Критическая ошибка: {ex.Message}");
|
|
||||||
}
|
|
||||||
|
|
||||||
Console.WriteLine("\nНажмите любую клавишу для выхода...");
|
|
||||||
Console.ReadLine();
|
|
||||||
}
|
|
||||||
|
|
||||||
static void ProcessFile(string filePath)
|
|
||||||
{
|
|
||||||
Console.WriteLine($"\nОбработка файла: {filePath}");
|
|
||||||
|
|
||||||
try
|
try
|
||||||
{
|
{
|
||||||
if (!File.Exists(filePath))
|
if (PingComputer(computer))
|
||||||
{
|
{
|
||||||
Console.WriteLine("Файл не существует, пропускаем.");
|
string checkingMsg = $"Проверяем компьютер {computer}...";
|
||||||
skippedCount++;
|
Console.WriteLine($"\n{checkingMsg}");
|
||||||
return;
|
LogToFile(checkingMsg);
|
||||||
|
|
||||||
|
string uncPath = $"\\\\{computer}\\{searchPath.Replace(":", "$")}";
|
||||||
|
|
||||||
|
if (!Directory.Exists(uncPath))
|
||||||
|
{
|
||||||
|
string pathError = $"Путь {uncPath} недоступен на компьютере {computer}";
|
||||||
|
Console.WriteLine(pathError);
|
||||||
|
LogToFile(pathError);
|
||||||
|
continue;
|
||||||
}
|
}
|
||||||
|
|
||||||
string fileName = Path.GetFileName(filePath);
|
// Режим 1 или 3: поиск файла
|
||||||
string? computerName = GetComputerNameFromPath(filePath);
|
if (mode == "1" || mode == "3")
|
||||||
|
|
||||||
if (!string.IsNullOrEmpty(computerName))
|
|
||||||
{
|
{
|
||||||
KillProcessOnRemotePC(computerName, fileName);
|
bool fileFound = SearchFiles(uncPath, fileName);
|
||||||
|
|
||||||
|
if (!fileFound)
|
||||||
|
{
|
||||||
|
string notFoundMsg = $"Файл {fileName} не найден на компьютере {computer}";
|
||||||
|
Console.WriteLine(notFoundMsg);
|
||||||
|
LogToFile(notFoundMsg);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Режим 2 или 3: удаление папки
|
||||||
|
if (mode == "2" || mode == "3")
|
||||||
|
{
|
||||||
|
DeleteFolder(uncPath, folderToDelete, computer);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Режим 4: поиск папки
|
||||||
|
if (mode == "4")
|
||||||
|
{
|
||||||
|
bool folderFound = SearchFolder(uncPath, folderToDelete);
|
||||||
|
|
||||||
|
if (!folderFound)
|
||||||
|
{
|
||||||
|
string notFoundMsg = $"Папка \"{folderToDelete}\" не найдена на компьютере {computer}";
|
||||||
|
Console.WriteLine(notFoundMsg);
|
||||||
|
LogToFile(notFoundMsg);
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
else
|
else
|
||||||
{
|
{
|
||||||
KillProcessesUsingFile(filePath);
|
string unavailable = $"Компьютер {computer} недоступен";
|
||||||
|
Console.WriteLine(unavailable);
|
||||||
|
LogToFile(unavailable);
|
||||||
}
|
}
|
||||||
|
|
||||||
Thread.Sleep(1000);
|
|
||||||
|
|
||||||
File.SetAttributes(filePath, FileAttributes.Normal);
|
|
||||||
File.Delete(filePath);
|
|
||||||
Console.WriteLine("Файл успешно удален.");
|
|
||||||
deletedCount++;
|
|
||||||
}
|
|
||||||
catch (UnauthorizedAccessException)
|
|
||||||
{
|
|
||||||
Console.WriteLine("Ошибка: Нет прав доступа к файлу");
|
|
||||||
failedCount++;
|
|
||||||
}
|
|
||||||
catch (IOException ioEx)
|
|
||||||
{
|
|
||||||
Console.WriteLine($"Ошибка ввода/вывода: {ioEx.Message}");
|
|
||||||
failedCount++;
|
|
||||||
}
|
}
|
||||||
catch (Exception ex)
|
catch (Exception ex)
|
||||||
{
|
{
|
||||||
Console.WriteLine($"Ошибка при удалении файла: {ex.Message}");
|
string compError = $"Ошибка при обработке компьютера {computer}: {ex.Message}";
|
||||||
failedCount++;
|
Console.WriteLine(compError);
|
||||||
|
LogToFile(compError);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
static string? GetComputerNameFromPath(string path)
|
string endMessage = $"\nОбработка завершена: {DateTime.Now}";
|
||||||
{
|
Console.WriteLine(endMessage);
|
||||||
if (path.StartsWith(@"\\"))
|
LogToFile(endMessage);
|
||||||
{
|
|
||||||
int endIndex = path.IndexOf('\\', 2);
|
|
||||||
if (endIndex > 2)
|
|
||||||
{
|
|
||||||
return path.Substring(2, endIndex - 2);
|
|
||||||
}
|
}
|
||||||
|
catch (Exception ex)
|
||||||
|
{
|
||||||
|
string fatalError = $"Критическая ошибка: {ex.Message}";
|
||||||
|
Console.WriteLine(fatalError);
|
||||||
|
LogToFile(fatalError);
|
||||||
}
|
}
|
||||||
return null;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
static void KillProcessesUsingFile(string filePath)
|
static bool PingComputer(string computerName)
|
||||||
{
|
|
||||||
string fileName = Path.GetFileNameWithoutExtension(filePath);
|
|
||||||
foreach (var process in Process.GetProcessesByName(fileName))
|
|
||||||
{
|
{
|
||||||
try
|
try
|
||||||
{
|
{
|
||||||
Console.WriteLine($"Завершение процесса {process.ProcessName} (ID: {process.Id})");
|
Ping ping = new Ping();
|
||||||
process.Kill();
|
PingReply reply = ping.Send(computerName, 1000);
|
||||||
process.WaitForExit(3000);
|
return reply.Status == IPStatus.Success;
|
||||||
}
|
}
|
||||||
catch (Exception ex)
|
catch
|
||||||
{
|
{
|
||||||
Console.WriteLine($"Не удалось завершить процесс: {ex.Message}");
|
return false;
|
||||||
}
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
public static void KillProcessOnRemotePC(string computerName, string processName)
|
static bool SearchFiles(string path, string fileName)
|
||||||
{
|
{
|
||||||
try
|
try
|
||||||
{
|
{
|
||||||
Console.WriteLine($"Попытка завершить процесс {processName} на компьютере {computerName}");
|
bool found = false;
|
||||||
|
|
||||||
ProcessStartInfo psi = new ProcessStartInfo
|
foreach (string file in Directory.GetFiles(path, fileName))
|
||||||
{
|
{
|
||||||
FileName = "taskkill",
|
found = true;
|
||||||
Arguments = $"/S {computerName} /IM {processName} /F",
|
string foundMsg = $"Найден файл: {file}";
|
||||||
CreateNoWindow = true,
|
Console.WriteLine(foundMsg);
|
||||||
UseShellExecute = false,
|
LogToFile(foundMsg);
|
||||||
RedirectStandardOutput = true,
|
}
|
||||||
RedirectStandardError = true
|
|
||||||
};
|
|
||||||
|
|
||||||
using (Process process = new Process { StartInfo = psi })
|
foreach (string directory in Directory.GetDirectories(path))
|
||||||
{
|
{
|
||||||
process.Start();
|
if (SearchFiles(directory, fileName))
|
||||||
string output = process.StandardOutput.ReadToEnd();
|
{
|
||||||
string error = process.StandardError.ReadToEnd();
|
found = true;
|
||||||
process.WaitForExit();
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return found;
|
||||||
|
}
|
||||||
|
catch (Exception ex)
|
||||||
|
{
|
||||||
|
string searchError = $"Ошибка при поиске в {path}: {ex.Message}";
|
||||||
|
Console.WriteLine(searchError);
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
static bool SearchFolder(string path, string folderName)
|
||||||
|
{
|
||||||
|
try
|
||||||
|
{
|
||||||
|
// Проверяем текущую папку
|
||||||
|
foreach (string dir in Directory.GetDirectories(path))
|
||||||
|
{
|
||||||
|
string dirName = Path.GetFileName(dir);
|
||||||
|
if (string.Equals(dirName, folderName, StringComparison.OrdinalIgnoreCase))
|
||||||
|
{
|
||||||
|
string foundMsg = $"Найдена папка: {dir}";
|
||||||
|
Console.WriteLine(foundMsg);
|
||||||
|
LogToFile(foundMsg);
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Рекурсивно ищем во вложенных папках
|
||||||
|
foreach (string dir in Directory.GetDirectories(path))
|
||||||
|
{
|
||||||
|
if (SearchFolder(dir, folderName))
|
||||||
|
{
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
catch (Exception ex)
|
||||||
|
{
|
||||||
|
string searchError = $"Ошибка при поиске папки в {path}: {ex.Message}";
|
||||||
|
Console.WriteLine(searchError);
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
static void DeleteFolder(string basePath, string folderName, string computerName)
|
||||||
|
{
|
||||||
|
try
|
||||||
|
{
|
||||||
|
string targetFolder = Path.Combine(basePath, folderName);
|
||||||
|
|
||||||
|
if (Directory.Exists(targetFolder))
|
||||||
|
{
|
||||||
|
Console.WriteLine($"Найдена папка {targetFolder} на компьютере {computerName}. Удаляем...");
|
||||||
|
LogToFile($"Найдена папка {targetFolder} на компьютере {computerName}. Удаляем...");
|
||||||
|
|
||||||
|
Directory.Delete(targetFolder, recursive: true);
|
||||||
|
|
||||||
|
string successMsg = $"Папка {folderName} успешно удалена на компьютере {computerName}";
|
||||||
|
Console.WriteLine(successMsg);
|
||||||
|
LogToFile(successMsg);
|
||||||
|
}
|
||||||
|
else
|
||||||
|
{
|
||||||
|
// Если папки нет в корне, ищем её во вложенных папках
|
||||||
|
bool deleted = false;
|
||||||
|
foreach (string dir in Directory.GetDirectories(basePath))
|
||||||
|
{
|
||||||
|
string subFolder = Path.Combine(dir, folderName);
|
||||||
|
if (Directory.Exists(subFolder))
|
||||||
|
{
|
||||||
|
Console.WriteLine($"Найдена папка {subFolder} на компьютере {computerName}. Удаляем...");
|
||||||
|
LogToFile($"Найдена папка {subFolder} на компьютере {computerName}. Удаляем...");
|
||||||
|
|
||||||
|
Directory.Delete(subFolder, recursive: true);
|
||||||
|
|
||||||
|
string successMsg = $"Папка {folderName} успешно удалена на компьютере {computerName} (в {dir})";
|
||||||
|
Console.WriteLine(successMsg);
|
||||||
|
LogToFile(successMsg);
|
||||||
|
deleted = true;
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!deleted)
|
||||||
|
{
|
||||||
|
string notFoundMsg = $"Папка {folderName} не найдена на компьютере {computerName} (искали в {basePath} и подпапках)";
|
||||||
|
Console.WriteLine(notFoundMsg);
|
||||||
|
LogToFile(notFoundMsg);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
catch (Exception ex)
|
catch (Exception ex)
|
||||||
{
|
{
|
||||||
Console.WriteLine($"Ошибка при удаленном завершении процесса: {ex.Message}");
|
string deleteError = $"Ошибка при удалении папки {folderName} на компьютере {computerName}: {ex.Message}";
|
||||||
|
Console.WriteLine(deleteError);
|
||||||
|
LogToFile(deleteError);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
static void LogToFile(string message)
|
||||||
|
{
|
||||||
|
try
|
||||||
|
{
|
||||||
|
File.AppendAllText(resultFilePath, message + Environment.NewLine);
|
||||||
|
}
|
||||||
|
catch (Exception ex)
|
||||||
|
{
|
||||||
|
Console.WriteLine($"Ошибка при записи в файл результатов: {ex.Message}");
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -1,136 +0,0 @@
|
|||||||
using System.Linq.Expressions;
|
|
||||||
using System.Net.NetworkInformation;
|
|
||||||
|
|
||||||
class FileSearchProgram
|
|
||||||
{
|
|
||||||
static string resultFilePath = "results.txt";
|
|
||||||
|
|
||||||
static void Main(string[] args)
|
|
||||||
{
|
|
||||||
// Очищаем файл результатов при каждом новом запуске
|
|
||||||
File.WriteAllText(resultFilePath, $"Поиск файла начат: {DateTime.Now}\n\n");
|
|
||||||
|
|
||||||
Console.WriteLine("Программа поиска файла в доменных компьютерах");
|
|
||||||
LogToFile("Программа поиска файла в доменных компьютерах");
|
|
||||||
|
|
||||||
string fileName = "Monitoring850.exe";
|
|
||||||
string searchPath = "D:\\";
|
|
||||||
string computersFile = "computers.txt";
|
|
||||||
|
|
||||||
try
|
|
||||||
{
|
|
||||||
if (!File.Exists(computersFile))
|
|
||||||
{
|
|
||||||
string error = $"Файл {computersFile} не найден. Создайте файл со списком компьютеров.";
|
|
||||||
Console.WriteLine(error);
|
|
||||||
LogToFile(error);
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
string[] computers = File.ReadAllLines(computersFile)
|
|
||||||
.Where(c => !string.IsNullOrWhiteSpace(c))
|
|
||||||
.ToArray();
|
|
||||||
|
|
||||||
string startMessage = $"Начинаем поиск файла {fileName} в {computers.Length} компьютерах...";
|
|
||||||
Console.WriteLine(startMessage);
|
|
||||||
LogToFile(startMessage);
|
|
||||||
|
|
||||||
foreach (string computer in computers)
|
|
||||||
{
|
|
||||||
try
|
|
||||||
{
|
|
||||||
if (PingComputer(computer))
|
|
||||||
{
|
|
||||||
string checkingMsg = $"Проверяем компьютер {computer}...";
|
|
||||||
Console.WriteLine(checkingMsg);
|
|
||||||
LogToFile(checkingMsg);
|
|
||||||
|
|
||||||
string uncPath = $"\\\\{computer}\\{searchPath.Replace(":", "$")}";
|
|
||||||
|
|
||||||
if (Directory.Exists(uncPath))
|
|
||||||
{
|
|
||||||
SearchFiles(uncPath, fileName);
|
|
||||||
}
|
|
||||||
else
|
|
||||||
{
|
|
||||||
string pathError = $"Путь {uncPath} недоступен на компьютере {computer}";
|
|
||||||
Console.WriteLine(pathError);
|
|
||||||
LogToFile(pathError);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
else
|
|
||||||
{
|
|
||||||
string unavailable = $"Компьютер {computer} недоступен";
|
|
||||||
Console.WriteLine(unavailable);
|
|
||||||
LogToFile(unavailable);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
catch (Exception ex)
|
|
||||||
{
|
|
||||||
string compError = $"Ошибка при обработке компьютера {computer}: {ex.Message}";
|
|
||||||
Console.WriteLine(compError);
|
|
||||||
LogToFile(compError);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
string endMessage = $"\nПоиск завершен: {DateTime.Now}";
|
|
||||||
Console.WriteLine(endMessage);
|
|
||||||
LogToFile(endMessage);
|
|
||||||
}
|
|
||||||
catch (Exception ex)
|
|
||||||
{
|
|
||||||
string fatalError = $"Критическая ошибка: {ex.Message}";
|
|
||||||
Console.WriteLine(fatalError);
|
|
||||||
LogToFile(fatalError);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
static bool PingComputer(string computerName)
|
|
||||||
{
|
|
||||||
try
|
|
||||||
{
|
|
||||||
Ping ping = new Ping();
|
|
||||||
PingReply reply = ping.Send(computerName, 1000);
|
|
||||||
return reply.Status == IPStatus.Success;
|
|
||||||
}
|
|
||||||
catch
|
|
||||||
{
|
|
||||||
return false;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
static void SearchFiles(string path, string fileName)
|
|
||||||
{
|
|
||||||
try
|
|
||||||
{
|
|
||||||
foreach (string file in Directory.GetFiles(path, fileName))
|
|
||||||
{
|
|
||||||
string foundMsg = $"Найден файл: {file}";
|
|
||||||
Console.WriteLine(foundMsg);
|
|
||||||
LogToFile(foundMsg);
|
|
||||||
}
|
|
||||||
|
|
||||||
foreach (string directory in Directory.GetDirectories(path))
|
|
||||||
{
|
|
||||||
SearchFiles(directory, fileName);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
catch (Exception ex)
|
|
||||||
{
|
|
||||||
string searchError = $"Ошибка при поиске в {path}: {ex.Message}";
|
|
||||||
Console.WriteLine(searchError);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
static void LogToFile(string message)
|
|
||||||
{
|
|
||||||
try
|
|
||||||
{
|
|
||||||
File.AppendAllText(resultFilePath, message + Environment.NewLine);
|
|
||||||
}
|
|
||||||
catch (Exception ex)
|
|
||||||
{
|
|
||||||
Console.WriteLine($"Ошибка при записи в файл результатов: {ex.Message}");
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -8,7 +8,9 @@
|
|||||||
</PropertyGroup>
|
</PropertyGroup>
|
||||||
|
|
||||||
<ItemGroup>
|
<ItemGroup>
|
||||||
<PackageReference Include="System.DirectoryServices" Version="9.0.6" />
|
<None Update="computers.txt">
|
||||||
|
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
|
||||||
|
</None>
|
||||||
</ItemGroup>
|
</ItemGroup>
|
||||||
|
|
||||||
</Project>
|
</Project>
|
||||||
|
|||||||
1
SearchFiles/computers.txt
Normal file
1
SearchFiles/computers.txt
Normal file
@@ -0,0 +1 @@
|
|||||||
|
izh-w02404
|
||||||
Reference in New Issue
Block a user