我想匹配同一行中的name变量作为文件名(在本例中,$CSV.name 和 $CSV.filename),然后相应地重命名每个文件。我该怎么做呢?任何帮助都非常感谢。
理想情况下,我想用两列自动填充.CSV:文件名和文件名内的电子邮件地址的保管人名称(例如,email protected(https://stackoverflow.com/cdn-cgi/l/email-protection))使用Regex,但我才刚刚开始使用PowerShell。
这就是我到目前为止所写的。它似乎工作得很好,并将实际文件名与CSV中的文件名相匹配。然而,当我使用Rename-Item命令时,它要么什么也不做,要么我收到这个错误:我假设这是因为它匹配了所有行,并试图用这些行而不是一行重命名。
Cd "C:\Users\Nick\Downloads\PST"
(
$CSV = Import-Csv -Path 'C:\Users\Nick\Downloads\PST\namesemails.csv' -Delimiter ',' -Header Name, Email, FileName
)
$psts = Get-ChildItem -Path "*.pst"
#Match filenames to Name column
if((Compare-Object $CSV.filename $psts.name | Where-Object SideIndicator -eq '=='))
{
Rename-Item -Path "*.pst" -NewName $CSV.name |foreach {$_ + ".pst"}
}
1条答案
按热度按时间x7yiwoj41#
解决这个问题的一种抽象方法,假设你有一个看起来像这样的Csv:
然后我建议使用哈希表,这样你就可以将文件的
.Name
属性Map到表的键,并从那里获得文件的新名称(在这个抽象的例子中,新名称由NewName
列定义)。创建哈希表的一个简单方法是使用Group-Object -AsHashtable
,然后您可以非常轻松地执行一些过滤和重命名。值得注意的是:
-Header
只在你的Csv没有header的时候才需要,对于这个抽象的例子来说,它是不需要的。-Delimiter ','
是冗余的,,
是默认分隔符。