Move Folders Using Values From CSV (PowerShell)

This evening I came up with a way for PowerShell to move multiple folders depending on names in a CSV. Below I will describe the scenario and my PowerShell scripts coding.

Imagine you had a folder structure on your device (or network share) containing folders named after the users that use them e.g. The account John.Smith has a folder called John.Smith.

geektechstuff_ods_powershell
Document Share

Now imagine several of the users move to another company, or leave but want their folders to go with them. Their user names have been provided in a CSV file.

powershell_names_csv_geektechstuff
CSV of usernames

And the users (all leaving at the same time and going to the same new location) want their folders copying to the same location.

geektechstuff_nds_ps
New Document Share (empty)
Each folder could individually be moved to the new location OR PowerShell could do all the moving for us!
——————-
# geektechtstuff
# variables
$logfile = “C:\temp\folder_move.txt”
$old_document_share = “C:\temp\document_share”
$new_document_share = “C:\temp\new_document_share”
$date_time = Get-Date -Format g
$names_account = (Get-Content C:\temp\names.csv) -split ‘,’
foreach ($account_name in $names_account){
# move foldersmatchthat match account name
write-host $account_name
$folders = Get-ChildItem $old_document_share\* | Where-Object{($_.psiscontainer -eq $true) -and ($_.name.EndsWith($account_name))}
foreach ($folder in $folders)
{
write-host $folder
$get_acl = Get-Acl $folder.FullName | ft $folder.FullName | out-file $logfile -append 
$output_details = $date_time | out-file $logfile -append
$move_item =Move-Item -Path $folder -Destination $new_document_share
}
—————-
geektechstuff_powershell_move_folders
geektechstuff PowerShell Move Folders Script

 

And as it is probably best to log when a folder was being moved, I even put in a logfile:

geektechstuff_powershell_logfile
Log File

As well as logging to a log file PowerShell will display in the console where it is up to:

geektechstuff_powershell_foldermove_running
geektechstuff PowerShell Move Folder running
geektechstuff_newdocumentshare_done
New document share (not empty)

 

Welcome to GeekTechStuff

my home away from home and where I will be sharing my adventures in the world of technology and all things geek.

The technology subjects have varied over the years from Python code to handle ciphers and Pig Latin, to IoT sensors in Azure and Python handling Bluetooth, to Ansible and Terraform and material around DevOps.

Let’s connect