powershellcopyfile-renamecopy-item

Get files from specific directories and put them in a flat structure with new file names


The task of my PowerShell script is to get files from specified language folders and put them in a flat structure in another directory, with a new suffix (.new) and with underscore followed by the language tag in the file name.

Currently the $lang variable is not resolving properly, when renaming. How can I get it to resolve properly?

The new files are not supposed to be created in the source folder, they should go to another folder somewhere else, into a flat structure. How can I include that in my script?

And, a bonus question, for Chinese (zh) the language tag in file name should be zh-cn instead of zh (but the search folder is zh). (I will run Chinese as a separate case if it is too complicated...)

$languages = @('cs','tr','zh')
foreach ($lang in $languages) { Get-ChildItem *\*\$lang -Recurse -Filter "*mytext.xml" | Copy-Item -Destination {$_.Fullname -replace 'xml', '_$lang.new' } }

Solution

  • I would do this using a ForEach-Object loop so we can make an exception on the zh to zh-cn conversion.

    Something like this:

    $languages   = 'cs','tr','zh'
    $sourcePath  = 'X:\PathToWhereTheLanguageSUbfoldersAre'
    $destination = 'Y:\PathToWhereTheFileCopiesShouldGo'
    
    foreach ($lang in $languages) { 
        $langSource = Join-Path -Path $sourcePath -ChildPath $lang
        $suffix = if ($lang -eq 'zh') { 'zh-cn' } else { $lang }
        Get-ChildItem -Path $langSource -Recurse -Filter "*mytext.xml" -File | 
        ForEach-Object {
            $target = Join-Path -Path $destination -ChildPath ('{0}_{1}.new' -f $_.BaseName, $suffix)
            $_ | Copy-Item -Destination $target
        }
    }