Powershell script to copy file named 'dat' from multiple folders

I am trying to copy a file named 'dat'. This file has no extension. The thing is though that under a Parent Folder 'Personal' I have 500 folders and all of these 500 folders have the 'dat' file. I am interested in copying all these 'dat' files and placing them in my destination directory.

So when I paste these 'dat' files in my destination directory, I am hoping to name them as follows:

"Folder_they_were_residing_in.dat"

So all the dat files will be renamed to the folder_name they were residing under with the extension'dat'.

Is this possible?


Solution 1:

Configure $source and $dest as needed, include trailing slash.

$source = "H:\personal\"
$dest   = "H:\archive\"

Get-ChildItem -Recurse -Path $source |
    Where-Object { $_.PsIsContainer -eq $false -and $_.Name -eq "dat" } |
        ForEach-Object { $_.CopyTo( $( $dest + $_.Directory.Name + ".dat" ), $true ) }

Solution 2:

PS H:\> foreach($_ in Get-ChildItem dat -Recurse) { Copy-Item $_.Fullname H:\dest\$($_.Directory.ToString().Split("\")[-1])`.dat }