I have a csv columns that have multiple columns and I need to split a particular column called "Path" that look something like this
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
I'm just wondering how can I use the last backlash symbol for indicator. If there is a dot after the last backlash then it's a "File" if there no dot then, it's a "Folder"
I'm trying to for loop each row, create a new column called "Type" that will store "File" and "Folder" value and export it to the new csv file.
I'm stuck so any help or suggestion would be really appreciated.
$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
CodePudding user response:
The Path
Class can help you determine if the path has an extension or not using it's GetExtension
method. Using both paths provided in your question as an example:
@'
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
The final code would be:
Import-Csv path\to\myCsv.csv | Select-Object @{
Name = 'Type'
Expression = { if([IO.Path]::GetExtension($_.Path)) { return 'File' } 'Directory' }
}, Path | Format-Table -AutoSize
As mklement0 notes in his helpful comment, Split-Path
includes the -Extension
parameter on PowerShell Core 7 :
Import-Csv .\test.csv | Select-Object @{
Name = 'Type'
Expression = { if(Split-Path -Extension $_.Path) { return 'File' } 'Directory' }
}, Path