Move Folders Using Values From CSV (PowerShell)

geektechstuff PowerShell Move Folder running

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)

 

Leave a Reply

Please log in using one of these methods to post your comment:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.