Ouline -
I have 300,000 folders containing subfolders and files.
I am trying to flatten each directory so that subfolders are removed and all files are brought to their respective parent directory.
Unfortunately, the Get-ChildItem cmdlet runs in the location of the .ps1 file and not those specified in the .txt file.
I have been trying to troubleshoot this for hours, any help would be greatly apprecieated.
Process -
First, I run a .ps1 file that retrieves the parent folder locations from a text file and calls a custom module:
[System.IO.File]::ReadLines("C:\Users\ccugnet\Desktop\test.txt") | ForEach-Object {
Import-Module MyFunctions
fcopy -SourceDir $line -DestinationDir $line
Remove-Module MyFunctions
}
Second, the custom module moves the child items to the parent folder, appending an incrementing digit to the end of the file name for duplicate files:
function fcopy ($SourceDir,$DestinationDir)
{
Get-ChildItem $SourceDir -Recurse | Where-Object { $_.PSIsContainer -eq $false } | ForEach-Object {
$SourceFile = $_.FullName
$DestinationFile = $DestinationDir $_
if (Test-Path $DestinationFile) {
$i = 0
while (Test-Path $DestinationFile) {
$i = 1
$DestinationFile = $DestinationDir $_.basename $i $_.extension
}
} else {
Move-Item -Path $SourceFile -Destination $DestinationFile -Verbose -Force -WhatIf
}
Move-Item -Path $SourceFile -Destination $DestinationFile -Verbose -Force -WhatIf
}
}
Text file contents:
"C:\Users\ccugnet\Desktop\Dir_Flatten\Fox, Hound & Hunter"
"C:\Users\ccugnet\Desktop\Dir_Flatten\Cat, Hat"
"C:\Users\ccugnet\Desktop\Dir_Flatten\Alice"
"C:\Users\ccugnet\Desktop\Dir_Flatten\Beetle | Juice"
CodePudding user response:
Your $line is empty
PS P:\> [System.IO.File]::ReadLines("C:\Users\ccugnet\Desktop\test.txt") | ForEach-Object {
$line
}
Try $_
PS P:\> [System.IO.File]::ReadLines("C:\Users\ccugnet\Desktop\test.txt") | ForEach-Object {
$_
}
"C:\Users\ccugnet\Desktop\Dir_Flatten\Fox, Hound & Hunter"
"C:\Users\ccugnet\Desktop\Dir_Flatten\Cat, Hat"
"C:\Users\ccugnet\Desktop\Dir_Flatten\Alice"
"C:\Users\ccugnet\Desktop\Dir_Flatten\Beetle | Juice"
Please accept my answer if it was useful