Skip to main content

Microsoft PowerShell Script to Rename and move files to different Directory

 <#

This Script will rename the files on a folder path and move them into a single folder

#>



#Set your source path here

$oldPath = "C:\test\old";


#Set your destination path here

$newpath = "C:\test\new";


#>

This will loop through all the files in the source folder path recursively
and and get there full file path and add to the $files variable

#>

$files = Get-ChildItem -Path $oldPath -File -Recurse -Force; # |  select FullName



$ter=0;

$olddir="adad";


foreach ($file in $files)  {


$ter++;


#>

this will get only the directory name of the files

#>

$dirpath = [System.IO.Path]::GetDirectoryName($file.FullName);

$dirname = [System.IO.Path]::GetFileName($dirpath);




$foo = $dirname.Replace("`n", "");

$foo = $foo.Replace(" ", "");

$foo = $foo.Replace("`t", "");


$olddir=$foo;



$oldname = $file.FullName;

$oldext= $file.Extension;

$newname = $foo+$ter.ToString()+$oldext;

#$newnamee = $newname -replace '[~#%&*{}|:<>?/|"]', '';

$newname;

$oldname;

#$newnamee;


Rename-Item -Path $oldname -newname $newname


}





$filesNew = Get-ChildItem -Path $oldPath -File -Recurse -Force; 

foreach ($file in $filesNew)  {


$file.FullName;


Move-Item -Path $file.FullName -Destination $newpath;


}


Comments