I have thousands of files like the following in a directory called D:\\queries\\
#TIM_DV_ORDERINQUERY.SQL
#TIM_QA_ORDERINQUERY.SQL
#TIM_P1_ORDERINQUERY.SQL
You'll probably want to use a regular expression for this. That will help to ensure that only files that match the specified pattern get moved, and you don't have any "accidents."
# 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) {
$File.Name -match '(?.*?)(?:_)(?\w{2})(?:_)(?.*)';
if ($matches) {
$Destination = 'd:\queries\{0}\{1}\{2}' -f $matches.folder, $matches.subfolder, $matches.filename;
mkdir -Path (Split-Path -Path $Destination -Parent) -ErrorAction SilentlyContinue;
Move-Item -Path $File.FullName -Destination $Destination -WhatIf;
}
$matches = $null
}