Last active
May 23, 2020 16:59
-
-
Save devavret/1ea5b32cdc759244125a2ccbd6e472d7 to your computer and use it in GitHub Desktop.
powershell to move files based on part of file name
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 1. Get a list of files in the d:\queries folder | |
$FileList = Get-ChildItem -Path d:\queries; | |
# 2. Parse file names, create folder structure, and move files | |
foreach ($File in $FileList) { | |
# Use regular expression to split up file name and assign pieces to field names of $matches | |
$File.Name -match '(?<folder>.*?)(?:_)(?<subfolder>\w{2})(?:_)(?<filename>.*)'; | |
# $matches is a special variable which receives output of the -match operation, see http://www.powershelladmin.com/wiki/Powershell_regular_expressions | |
if ($matches) { # If the file name matched the regular expression | |
# Concatenate to get name of file after the move | |
$Destination = 'd:\queries\{0}\{1}\{2}' -f $matches.folder, $matches.subfolder, $matches.filename; | |
mkdir -Path (Split-Path -Path $Destination -Parent) -ErrorAction SilentlyContinue; | |
# This mkdir call did not work for me, so I used the following line instead | |
# $DestinationFolder = '{0}Folder_{1}\' -f $SourceFolder, $matches.day | |
# if (-not (test-path $DestinationFolder)){mkdir $DestinationFolder} # Create subdirectory if it doesn't exist | |
Move-Item -Path $File.FullName -Destination $Destination -WhatIf; | |
} | |
$matches = $null | |
} | |
#eof | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment