PowerShell脚本提取csv当中指定关键词(多个)字段开头的列

权限设置:管理员打开PowerShell-输入命令Set-ExecutionPolicy unrestricted

好处就是任何地方都能执行,不需要任何环境

# 权限设置: Set-ExecutionPolicy unrestricted
# 提示输入文件路径,默认值为 TrainFeature.csv
$file = Read-Host "Enter the file path (default: TrainFeature.csv)" 
if (-not $file) { $file = "TrainFeature.csv" }

# 检查文件是否存在
if (-Not (Test-Path $file)) {
    Write-Host "Error: The file '$file' does not exist."
    exit
}

# 提示输入关键词,多个关键词用空格分隔
$keywords = Read-Host "Enter the keywords (separated by spaces)"

# 将关键词转为数组
$keywordArray = $keywords -split '\s+'

# 读取 CSV 文件内容
$csvContent = Import-Csv -Path $file

# 提取包含关键词开头的列
$filteredColumns = $csvContent | Select-Object -Property $($csvContent[0].PSObject.Properties.Name | Where-Object { 
    $columnName = $_
    $keywordArray | ForEach-Object { 
        if ($columnName -like "$_*") { # 匹配列名以关键词开头
            return $true 
        }
    }
    return $false
})

# 检查是否有匹配的列
if ($filteredColumns.Count -eq 0) {
    Write-Host "No columns match the specified keywords."
    exit
}

# 提示输入输出文件路径,默认值为 Output.csv
$outputFile = Read-Host "Enter the output file path (default: Output.csv)"
if (-not $outputFile) { $outputFile = "Output.csv" }

# 将提取的列保存为新的 CSV 文件
$filteredColumns | Export-Csv -Path $outputFile -NoTypeInformation

Write-Host "Filtered columns have been saved to '$outputFile'."

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注