【问题标题】:Powershell to scan 2 csv files in folder and rename one of themPowershell扫描文件夹中的2个csv文件并重命名其中一个
【发布时间】:2016-05-09 05:05:29
【问题描述】:

我无法编写一段代码来扫描文件夹中的两个 csv 文件。 File1 将具有变量名称(在每个文件夹中不同),而 File2 始终是静态的。我想要的是取 File1.csv 的名称,然后创建一个子文件夹并将 File2.csv 放在那里,然后重命名 File2.csv 以匹配 File1。

这可能吗?

【问题讨论】:

  • 是的,这是可能的。如果名称可以是任何名称,您如何知道哪个文件是 File1?是否有只有两个 CSV 文件?
  • 是的,文件夹中只有两个文件,我正在考虑扫描所有扩展名为 .csv 的文件,然后执行一个 if $file 不是 File2.csv,然后取名称并存储它比如说 $filenamefix

标签: csv powershell


【解决方案1】:

假设文件夹中只有两个 CSV 文件并且 File2.csv 始终具有相同的名称,这应该可以工作。

$folderPath = 'C:\Folder'
Add-Content -Path "$folderPath\File1.csv" -Value ''
Add-Content -Path "$folderPath\File2.csv" -Value ''

$file1 = (Get-ChildItem -Path $folderPath -Filter '*.csv').where({ $_.Name -ne 'File2.csv' })

$newFolderPath = "$folderPath\$($file1.Name)"

$null = mkdir $newFolderPath
Move-Item -Path "$folderPath\File2.csv" -Destination "$newFolderPath\$($file1.Name)"

【讨论】:

  • 嘿,谢谢大家。非常感谢您的帮助。不幸的是,它给了我以下错误方法调用失败,因为 [System.IO.FileInfo] 不包含名为“where”的方法。在 line:14 char:1 + $file1 = (Get-ChildItem -Path $folderPath -Filter '*.csv').where({ $_.Name -ne $ ... + ~~~~~~~~~ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ ~~~~~~~~~~~~~~~~~~~~~~ + CategoryInfo : InvalidOperation: (:) [], RuntimeException + FullyQualifiedErrorId : MethodNotFound
  • 好的,我发现了问题所在,我使用的是 Powershell V3,我刚刚更新到 V4 并且工作起来就像一个魅力!谢谢朋友!
猜你喜欢
  • 2022-01-06
  • 1970-01-01
  • 1970-01-01
  • 2011-10-21
  • 2017-12-19
  • 2017-10-20
  • 1970-01-01
  • 2019-01-28
  • 2018-04-26
相关资源
最近更新 更多