[英]C# Application to batch file
我需要一点帮助,希望你们中的一个能帮助我。
我有一个路径(目录),其中有很多文件夹。在这些文件夹中,有很多我不知道的子文件夹和文件。 因此,我不知道它们和文件下有多少个子文件夹和子文件夹。 这是一棵大树的文件夹。 我的任务是创建一个脚本,该脚本可以检查是否存在72小时的文件夹或文件,如果存在,则需要删除该文件夹。 这意味着我有很多文件夹。
一个示例是名为ANSYS的文件夹。 在ANSYS中,有许多子文件夹和文件。 我必须检查所有ANSYS文件夹,并查看该文件夹及其子文件夹中的任何文件是否存在72个小时。 如果ANSYS中的所有内容都存在72小时,则必须删除整个ANSYS。 我已经制作了一个可以完成我的工作的C#应用程序,但是我需要在数百台服务器上使用该应用程序,而且我没有时间在所有服务器上安装.NET框架。 这就是为什么我必须使用可以执行相同操作的bash脚本的原因。
这是我的C#应用程序,您可以查看它以了解更多我的作业:
using System;
using System.IO;
namespace Scripts
{
internal class Program
{
private static void Main(string[] args)
{
//Defines the main path.
var topPath = @"C:\Ansys_RSM_Work_DIR\";
//Converts the first argument written as a parameter in TaskScheduler or CMD, called 'hours'.
string argument = args[0];
int hours = Int32.Parse(argument);
//Defines the timespan in which a file has to be modified.
var deleteIfNotModifiedIn = new TimeSpan(hours, 0, 0);
//Is set to true if the file file has been modified within the timespan.
bool fileTooOld = false;
//Searches through all directories in topPath, one at a time.
foreach (var dir in Directory.GetDirectories(topPath))
{
//Searches through all files in directory, one at a time.
foreach (var file in Directory.GetFiles(dir, "*", SearchOption.AllDirectories))
{
//Calculate the difference between now and lastWriteTime = fileLastModified.
var fileLastModified = DateTime.Now - File.GetLastWriteTime(file);
if (fileLastModified < deleteIfNotModifiedIn)
fileTooOld = true;
}
if (fileTooOld == false)
Directory.Delete(dir, true);
else
fileTooOld = false;
}
}
}
}
我已经尝试制作脚本,但是如果脚本中的文件已存在72个小时,那么我编写的脚本会删除该子文件夹,这是不应该的。 如果自上一个72小时以来未修改ANSYS中的所有文件和ANSYS中的所有子文件夹,则它仅应删除第一个文件夹(类似于ANSYS):我的脚本:
FORFILES /S /D -3 /C "cmd /c IF @isdir==TRUE rd /S /Q @path"
for /f "delims=" %i in ('dir /s /b /ad ^| sort /r') do rd "%i"
谁能帮帮我吗?
诚挚的问候Shaban Mahmood
好的,尝试这样的事情:
@echo off
pushd C\...[Taret folder containg folders to check, that is containing ANSYS]
set /p check="Date after which to check: "
Rem When prompted with above line type the date 3 days ago.
forfiles /c "cmd /c (IF @isdir==TRUE search "@path" "%check%")"
popd
并在同一目录中:
set del=TRUE
forfiles /p %1 /d +%2 /s /m *.* /c "cmd /c (set del=FALSE)"
Pause |Echo Deleting %1... Exit to cancel
if %del%==True (rd /s %1)
应该可以,请注意,它将在删除每个文件之前暂停。 它的工作方式是检查与该文件一起发送的文件是否少于72小时,如果有,则不会删除该文件夹。 它将对指定文件夹中的每个文件夹执行此操作。 search.bat文件是可以使用文件夹路径调用的文件,它将根据您指定的要求搜索该父文件夹内的所有文件。 Program.bat为您完成了第一步。
如果出现故障(或根本无法工作),我将其暂停,如果是这种情况,请告诉我在哪里无效。 另外,如果需要解释,请评论。
莫娜
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.