Reputation: 57
How can I copy the folder names to the filenames during the copy. At the moment the script copies only files from the subdirectory without all folder and sub-foldername. However, I want which takes the absolute pathname while copying.
Here an example: Folder1 Subfolder1 Subfolder2 Subfolder3 Subfolder4 File1 Folder2
Then a copied file would be called so:
Folder1_Subfolder1_Subfolder2_Subfolder3_Subfolder4_File.pdf
Powershell code:
Get-ChildItem –path C:\12 -Recurse -Include "*.???" |
Foreach-Object { copy-item -Path $_.fullname -Destination c:\12 }
Upvotes: 2
Views: 3011
Reputation: 1909
Ok, if I'm understanding you correctly, you want a file like:
C:\12\foo\bar\baz.txt
To be copied to:
C:\12\foo_bar_baz.txt
If I'm understanding that correctly, then something like the following should work:
function Copy-FileUsePath {
[cmdletbinding()]
param(
[parameter(Mandatory=$true,Position=0)][string]$Path,
[parameter(Mandatory=$true,Position=1)][string]$Destination
)
$files = Get-ChildItem -Path $Path -Recurse -Include "*.???"
foreach ( $file in $files ) {
$discard = $Destination.Length
if( $Destination -notlike "*\" ) {
$discard++
}
$newFileName = $file.FullName.Replace('\', '_').Remove( 0, $discard )
$newFile = $Destination + '\' + $newFileName
Write-Verbose "Copy-Item -Path $file.fullname -Destination $newFile"
Copy-Item -Path $file.fullname -Destination $newFile
}
}
To use this, save it to a file (I called it Copy-FileUsePath.ps1), and you can do the following:
. .\Copy-FileUsePath.ps1
Copy-FileUsePath -Path C:\12 -Destination C:\export
Upvotes: 1