###################################
# mkdirAndMoveFilesToThere.ps1
###################################
# NOTES:
# "Alt-Shift-Arrow" to select multiple lines
# The line continuation character in Windows PowerShell is the backtick ( ` )
# Parameters in calls to functions in PowerShell (all versions) are space-separated, not comma-separated.
###################################
<####### ########>
Set-Location "\\serverName\dataFolder"; #*****UNC PATH TO WORKING DIRECTORY*****
$listOfDirectories = Get-ChildItem . | Where-Object {$_.PsIsContainer}; #*****COLLECT SUBDIRECTORIES*****
foreach ($directory in $listOfDirectories) #*****LOOP THROUGH EACH DIRECTORY*****
{
cd $directory;
createDirectoriesAndMoveFiles;
cd..; #*****THIS STATEMENT IS REQUIRED! OTHERWISE, IT WOULD FAIL TO CD TO THE NEXT DIRECTORY*****
}
function createDirectoriesAndMoveFiles()
{
$listOfFiles = Get-ChildItem . | Where-Object {!$_.PsIsContainer}; #*****GET FILES FROM CURRENT DIRECTORY*****
foreach ($file in $listOfFiles)
{
$newDirectory = $file.Name.SubString(0,7);
If (Test-Path $newDirectory)
{
if ($file.Name.SubString(0,7) -eq $newDirectory) {mv $file "$newDirectory\$file" -Force;}
}
Else
{
md $newDirectory.ToUpper();
mv $file "$newDirectory\$file";
}
}
}