January 25, 2020, 11:26 am
I had a need to take an existing directory with a specific set of files and create new copies of those files, but with new random names. These new files would test a process which needed a lot of files to be loaded and the files had to be of a specific format and data such as a zip archive.
gci {TargetDirectory} -file | Copy-Item -Destination { "$([System.IO.Path]::GetRandomFileName()).{Target Extension}" } -whatif
- This operation copies the file to the current directory.
- The
GetRandomFileName
will generate both random text and random lettered extensions.
I needed my files to be all of the same type so I this is the format I used:
gci C:\Test\Initial -file | Copy-Item -Destination { "$([System.IO.Path]::GetRandomFileName()).zip" } -whatif
February 25, 2010, 4:15 pm
Here is a quick little snippet of code which uses allows one to create a sequence of numbers and letters, or any character needed, in a sequence defined by the user. Here is the code
Random rn = new Random();
string charsToUse = "AzByCxDwEvFuGtHsIrJqKpLoMnNmOlPkQjRiShTgUfVeWdXcYbZa1234567890";
MatchEvaluator RandomChar = delegate (Match m)
{
return charsToUse[rn.Next( charsToUse.Length )].ToString();
};
Console.WriteLine( Regex.Replace( "XXXX-XXXX-XXXX-XXXX-XXXX", "X", RandomChar ) );
// Lv2U-jHsa-TUep-NqKa-jlBx
Console.WriteLine( Regex.Replace( "XXXX", "X", RandomChar ) );
// 8cPD
What is happening is that in the Regex.Replace we specify a pattern by X’s. Anything which is not an X is ignored and left in the result. We specify what characters to use in the string charsToUse and in this case we have A-Za-z0-9 expressed as written out. When we run the Regex.Replace it returns the pattern we specified with the characters we needed.