如何使用PowerShell拆分csv列值

ttygqcqt  于 2022-12-06  发布在  Shell
关注(0)|答案(1)|浏览(151)

我有一个包含多个列的csv列,我需要拆分一个名为“Path”的特定列,它看起来如下所示

SharePoint\user\Documents\Desktop\PowerShell Scripts\Audit-Log-Script\.git\objects\ff\76e4656b4e0afa14ad3a6ea03fb6d40a5bb7c0
SharePoint\user\Documents\Desktop\PowerShell Scripts\Audit-Log-Script\Data\User_v512.csv

我只是想知道如何使用最后一个反冲符号作为指示器。如果在最后一个反冲符号后有一个点,那么它是“文件”,如果没有点,那么它是“文件夹”
我尝试for循环每行,创建一个名为“类型”的新列,该列将存储“文件”和“文件夹”值,并将其导出到新的csv文件。
我被困住了,所以任何帮助或建议都将不胜感激。

$Result=
foreach($CSVLine in $CSVImport){
    $CSVLine | 
        Select-Object -Property *,
            @{
                Name = 'Type'; 
           # Not sure how to do if else statement here to pass either "File" or "Folder" value
                Expression = {($_.Path -split "\")[-2]} \
            }
}
$Result |
    Format-Table -AutoSize
olmpazwi

olmpazwi1#

Path Class可以帮助您确定路径是否使用GetExtension method作为扩展名。以问题中提供的两个路径为例:

@'
Path
SharePoint\user\Documents\Desktop\PowerShell Scripts\Audit-Log-Script\.git\objects\ff\76e4656b4e0afa14ad3a6ea03fb6d40a5bb7c0
SharePoint\user\Documents\Desktop\PowerShell Scripts\Audit-Log-Script\Data\User_v512.csv
'@ | ConvertFrom-Csv | Select-Object @{
    Name       = 'Type'
    Expression = { if([IO.Path]::GetExtension($_.Path)) { return 'File' } 'Directory' }
}, Path

最终代码为:

Import-Csv path\to\myCsv.csv | Select-Object @{
    Name       = 'Type'
    Expression = { if([IO.Path]::GetExtension($_.Path)) { return 'File' } 'Directory' }
}, Path | Format-Table -AutoSize

正如mklement0在他的有用注解中所指出的,Split-PathPowerShell Core 7+上包含了-Extension参数:

Import-Csv .\test.csv  | Select-Object @{
    Name       = 'Type'
    Expression = { if(Split-Path -Extension $_.Path) { return 'File' } 'Directory' }
}, Path

相关问题