首页 > 解决方案 > 使用 CSV 附加文件名

问题描述

我正在尝试重命名与 csv 第一列中的值匹配的文件,将第 3 列中的值添加到文件名的开头,使文件名的其余部分保持不变。这是我到目前为止所拥有的。我似乎无法弄清楚重命名项目。

# Common Paths
$PathRoot = "C:\Temp\somefiles" #Where the files are to rename

# Get csv file
$ClientAccounts = Import-CSV -path "\\server\some\path\to\csv\file.csv"

# Get each file and rename it
ForEach($row in $ClientAccounts) 
{
    $CurrentClientTaxId = $row[-1].TaxId
    $CurrentClientName = $row[-1].ClientName 

    #loop through files

    $FileExists = Test-Path -Path "$PathTotal\*$CurrentClientLB_Number*" #See if there is a file.

    If ($FileExists -eq $true) #The file does exist.
    {

        #ReName File
        Rename-Item -Path $PathRoot -NewName {$CurrentClientName + " " + $_.name}
    }
}

标签: powershell

解决方案


假设您的 CSV 文件类似于以下内容:

"LB_Number","TaxId","ClientName"
"987654","12345","Microsoft"
"321456","91234","Apple"
"741852","81234","HP"

第 1 列包含与现有文件名匹配的部分
第 3 列包含您要添加到文件名的客户端名称

那么你的函数可能是这样的:

# Common Paths
$PathRoot = "C:\Temp\somefiles" # Where the files are to rename

# Get csv file
$ClientAccounts = Import-CSV -path "\\server\some\path\to\csv\file.csv"

# Loop through all clients in the CSV
foreach($client in $ClientAccounts) {
    $CurrentClientLB_Number = $client.LB_Number
    $CurrentClientTaxId     = $client.TaxId       # unused...??
    $CurrentClientName      = $client.ClientName 

    # get the file(s) using wildcards (there can be more than one)
    # and rename them
    Get-ChildItem -Path "$PathRoot\*$CurrentClientLB_Number*" -File | ForEach-Object {
        $_ | Rename-Item -NewName ($CurrentClientName + " " + $_.Name) 
    }

    # Curly braces work also, although this is not very common practice:
    # Get-ChildItem -Path "$PathRoot\*$CurrentClientLB_Number*" -File | 
    #     Rename-Item -NewName { ($CurrentClientName + " " + $_.Name) }
}

我使用-File参数 withGet-ChildItem所以函数只会返回文件;不是目录。如果您使用的是 PowerShell 2.0 版,则需要将其替换为| Where-Object { !$_.PSIsContainer }.


推荐阅读