powershell - 使用 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}
}
}
解决方案
假设您的 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 }
.
推荐阅读
- php - 无法弄清楚为什么我得到一段代码的“未定义索引”而不是另一段
- python - 根据多个空单元格在 Pandas 中删除行?
- rust - 如何在 `cargo doc` 生成的文档中获取功能需求标签?
- xcode - React-Native:不变违规:模块 AppRegistry 不是注册的可调用模块(调用 runApplication)
- docker - 在 Linux Docker 容器中运行的 .NET Core 应用程序无法访问特定的 SQL Server
- c# - 无法将“System.Int32”类型的对象转换为“System.Int64”类型
- android - 试图将谷歌支付集成到我的安卓应用中
- types - 类型构造函数和数据类型之间有什么区别和关系?
- angular - 如何使用 http Angular 访问对象内部的数组?
- php - PHP Query 不适用于我为它创建的函数