gpt4 book ai didi

powershell - 如何读取,转换和输出文件夹中的所有文件?

转载 作者:行者123 更新时间:2023-12-02 23:39:04 29 4
gpt4 key购买 nike

我在PowerShell中工作。我的PSVersion是3.0。我有一个包含几个CSV文件的文件夹。每个文件中可以包含几列,并在第一行包含列标题。列的顺序将始终不相同。我只需要从每个文件中提取某些列。我需要提取的列在所有文件中都是相同的,并且所有文件都至少具有我需要提取的列(通常更多)。提取后,我需要将为每个文件提取的列导出到另一个文件夹中的相应CSV。例如,我的输入文件夹中有以下2个文件:
file1.csv:

Col1   Col2   Col3   Col4a      1      z      0.0

file2.csv:

Col4   Col1   Col3   Col21.0      b      x      2

I need to fetch only columns Col1 and Col4 from each file. So, I expect to output the following files:

file1.csv:

Col1   Col4a      0.0

file2.csv:

Col1   Col4b      1.0

Below is my script:

$inputDirectory = 'C:\some_path\input\';
$outputDirectory = 'C:\another_path\output\';

$inputFiles = Get-ChildItem -Path $inputDirectory -Recurse -Include *.csv;

ForEach-Object {
Import-Csv $inputFiles |
Select-Object -Property Col1, Col4 |
Export-Csv $outputDirectory + $inputFiles.Name -NoTypeInformation
}

我在使用 Export-Csv命令时遇到麻烦。我不断收到以下错误:

A positional parameter cannot be found that accepts argument 'System.Object{}'



因此,有关我的 Select-Object管道的某些信息是错误的。如何解决此错误并实现目标?

最佳答案

您的逻辑是合理的,但是语法没有意义。

$Path = 'C:\Temp\Input'
$Output = 'C:\Temp\Output'

$Files = Get-ChildItem -Path $Path -Recurse -Include '*.csv'

ForEach ($File in $Files)
{
Import-Csv -Path $File.FullName | Select-Object -Property @('Col1','Col4') |
Export-Csv -Path (Join-Path $Output $File.Name) -NoTypeInformation -Append
}

关于powershell - 如何读取,转换和输出文件夹中的所有文件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47189498/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com