【问题标题】:Get files from specific directories and put them in a flat structure with new file names从特定目录获取文件并将它们放在具有新文件名的平面结构中
【发布时间】:2021-10-19 14:37:01
【问题描述】:

我的 PowerShell 脚本的任务是从指定的语言文件夹中获取文件,并将它们放在另一个目录中的平面结构中,带有新的后缀 (.new),并在文件名中使用下划线后跟语言标记。

当前$lang 变量在重命名时无法正确解析。我怎样才能让它正确解决?

新文件不应该在源文件夹中创建,它们应该转到其他地方的另一个文件夹,形成一个平面结构。如何将其包含在我的脚本中?

还有一个额外的问题,对于中文(zh),文件名中的语言标签应该是 zh-cn 而不是 zh(但搜索文件夹是 zh)。 (如果太复杂我会单独运行中文...)

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

【问题讨论】:

    标签: powershell copy file-rename copy-item


    【解决方案1】:

    我会使用 ForEach-Object 循环来执行此操作,这样我们就可以在 zhzh-cn 的转换中创建一个例外。

    类似这样的:

    $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
        }
    }
    

    【讨论】:

    • 谢谢!该代码中有很多有用的模式。
    猜你喜欢
    • 1970-01-01
    • 2021-06-08
    • 2020-09-02
    • 1970-01-01
    • 1970-01-01
    • 2012-10-26
    • 2014-07-30
    • 2019-07-07
    • 2021-11-04
    相关资源
    最近更新 更多