在复制项目中重命名文件

时间:2019-11-04 13:22:33

标签: powershell csv

我目前正在读取CSV文件,并根据列值创建文件夹结构,并将文件复制到这些子目录中。我目前正在努力进行调整,以使文件名在复制到DotDate_CurrentName时得到修改(DotDate是csv中的一列)。

##Pull the CSV & Create Directories
Echo "Getting root directory for CSV File" #via root variable

#import the csv file and loop through the results
Echo "Importing CSV file"
Import-Csv -Path "$($FilePath)\$($DateStr)_$($TimeStr)_Export.csv" | ForEach-Object {
    Echo "Building subpath and fullpath strings"
    $subPath = [System.IO.Path]::Combine($_.'ID' + '_' + $_.'First Name' + '_' + $_.'Surname', $_.Area, $_.SubArea, $_.'DotDate')
    $fullPath = Join-Path -Path $rootPath -ChildPath $subPath
    "Test fullpath and build path from strings"
    if (!(Test-Path -Path $fullPath -PathType Container)) {
        New-Item -Path $fullPath -ItemType Directory | Out-Null
    }
    Copy-Item -Path $_.'Document File Path' -Destination $fullPath
}

1 个答案:

答案 0 :(得分:1)

您无需复制然后重命名;您可以在同一操作中同时执行这两项操作。要在DotDate之前添加前缀,您可以执行以下操作:

#requires -Version 4
@(Import-Csv -Path "$FilePath${DateStr}_${TimeStr}_Export.csv").ForEach{
    $path = [IO.Path]::Combine(
        $rootPath,
        ('{0}_{1}_{2}' -f $_.ID, $_.'First Name', $_.Surname),
        $_.Area,
        $_.SubArea,
        $_.DotDate
    )

    if (-not (Test-Path -Path $path -PathType Container)) {
        New-Item -Path $path -ItemType Directory >$null
    }

    $copy = [IO.FileInfo]$_.'Document File Path'
    $copy | Copy-Item -Destination "$path\$($_.DotDate)_$($copy.Name)"
}