2

我的 Prevalidation 文件夹中有许多扩展名为 .psa 的文件,我想:

  1. 将它们一一复制到我的工作文件夹中
  2. 将 .psa 文件重命名为 psaload.csv
  3. 对文件运行一组命令以将其加载到我的数据库中
  4. 然后从我的工作文件夹中删除 csv 文件。

这将针对我的源文件夹中的所有 .psa 文件重复。

所以,问题是我如何在尽可能多的 .psa 文件上循环执行命令集。

这是我对 Prevalidation 文件夹中的一个文件进行的一段代码测试-

Copy-Item  C:\Downloads\PreValidation\*.psa C:\Downloads\Validation\WIP
Rename-Item 'C:\Downloads\Validation\WIP\abc 1234.psa' 'psaload1.csv'

Get-Content C:\Downloads\Validation\WIP\psaload1.csv | ForEach-Object { $_.replace("\,"," ") } | Set-Content C:\Downloads\Validation\WIP\psaload.csv

Remove-Item C:\Downloads\Validation\WIP\psaload1.csv

<run the psaload.csv to load to my db>

这就是我打算做的——

考虑我的 C:\Downloads\Prevalidation 文件夹中的多个 .psa 文件。

For each C:\Downloads\PreValidation\*.psa

BEGIN LOOP

Copy-Item  C:\Downloads\PreValidation\aaaa.psa C:\Downloads\Validation\WIP\aaaa.psa
Rename-Item 'C:\Downloads\Validation\WIP\aaaa.psa' 'psaload1.csv'

Get-Content C:\Downloads\Validation\WIP\psaload1.csv | ForEach-Object { $_.replace("\,"," ") } | Set-Content C:\Downloads\Validation\WIP\psaload.csv

Remove-Item C:\Downloads\Validation\WIP\psaload1.csv


END LOOP

我正在寻找语法来为我的 /prevalidation 文件夹中的每个文件一个一个地运行这些命令集。

4

3 回答 3

5

由于所有其他答案都是非常糟糕的代码并且不是非常惯用的 PowerShell,因此这是我的看法(尽管未经测试):

# Get all .psa files
Get-ChildItem C:\Downloads\PreValidation\*.psa |
   ForEach-Object {
      # Load the file's contents, replace commas with spaces
      (Get-Content $_) -replace ',', ' ' |
         # and write it to the correct folder and file name
         Out-File C:\Downloads\WIP\psaload.csv

      # I guess you'd run whatever you're doing against the file here,
      # not after the loop

      Remove-Item C:\Downloads\WIP\psaload.csv
   }
于 2011-11-15T18:08:04.467 回答
0

您可以将 foreach 与 Get-Item 一起使用来执行循环。Get-Item 将返回一个FileInfo 对象,您可以使用该对象从中获取文件名(和其他信息)。因此,您可以执行以下操作:

foreach($file in (Get-Item .\*.psa))
{
   Copy-Item $file.FullName "C:\Downloads\Validation\WIP\$($file.Name)";
}

等等

于 2011-11-15T15:48:49.960 回答
0

试试这个:

$a = Get-Item .\*.psa

foreach($file in $a)
{
   Copy-Item $file.FullName "C:\Downloads\Validation\WIP\$($file.Name.replace(".psa",".psload.csv)";

remove-item $file

}
于 2011-11-15T15:56:44.943 回答