csv 如何编写PowerShell脚本将所有.pst文件重命名为它们的保管人名称?

1rhkuytd  于 12个月前  发布在  Shell
关注(0)|答案(1)|浏览(88)

我想匹配同一行中的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"}
}
x7yiwoj4

x7yiwoj41#

解决这个问题的一种抽象方法,假设你有一个看起来像这样的Csv:

"OldName","NewName"
"hello.pst","world.pst"
"foo.pst","bar.pst"

然后我建议使用哈希表,这样你就可以将文件的.Name属性Map到表的键,并从那里获得文件的新名称(在这个抽象的例子中,新名称由NewName列定义)。创建哈希表的一个简单方法是使用Group-Object -AsHashtable,然后您可以非常轻松地执行一些过滤和重命名。
值得注意的是:

  1. -Header只在你的Csv没有header的时候才需要,对于这个抽象的例子来说,它是不需要的。
  2. -Delimiter ','是冗余的,,是默认分隔符。
$map = Import-Csv -Path 'namesemails.csv' |
    # group the objects by the `OldName` column
    Group-Object OldName -AsHashTable

# get all `.pst` files
Get-ChildItem -Path '*.pst' |
    # filter only those files existing in our map
    Where-Object { $map.ContainsKey($_.Name) } |
    # here we assume the file exist so, we get the value that maps with
    # this file name and from there we expand the `.NewName`
    Rename-Item -NewName { $map[$_.Name].NewName }

相关问题