Skip to content

Instantly share code, notes, and snippets.

@InsanePrawn
Created July 13, 2016 16:10
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save InsanePrawn/f225c5e1f520243da1d39cab26096aa7 to your computer and use it in GitHub Desktop.
Save InsanePrawn/f225c5e1f520243da1d39cab26096aa7 to your computer and use it in GitHub Desktop.
using System;
using System.IO;
using System.Collections.Generic;
using System.Diagnostics;
namespace foreachfile
{
class MainClass
{
public static void Main(string[] args)
{
string path;
string cmd;
string cmdargs;
string[] files;
if (args.GetLength(0) < 3)
{
MainClass.printUsage();
return;
}
path = args[0];
cmd = args[1];
cmdargs = args[2];
try
{
files = Directory.GetFiles(path, "*", SearchOption.AllDirectories);
}
catch(Exception ex)
{
Console.WriteLine("Something went wrong while trying to accumulate the list of files :(");
Console.WriteLine(ex.ToString());
return;
}
try
{
foreach(string file in files)
{
Console.WriteLine("Working on '" + file + "'");
var proc = Process.Start(cmd, cmdargs.Replace("$1", file));
proc.WaitForExit();
if(proc.ExitCode == 0) {
Console.WriteLine("job worked (i guess?)");
} else {
Console.WriteLine("job finished, returned exit code " + proc.ExitCode + "; is that bad?");
}
}
}
catch(Exception ex)
{
Console.WriteLine("Something went wrong while trying to run the command :(");
Console.WriteLine(ex.ToString());
}
}
public static void printUsage() {
Console.WriteLine("USAGE: foreachfile.exe PATH_TO_FIND_FILES_IN COMMAND_TO_RUN \"PARAMETERS FOR COMMAND, USE $1 AS PLACEHOLDER FOR FILENAME MIND THE QUOTATION MARKS\"");
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment