Newbie, need ps script to replace substring at beginning of item in csv column

Hello I need a ps script to import-csv and then replace a substring in each line:

The source.csv looks like this:

#TYPE Selected.System.IO.FileInfo
"Directory","Name","FullName","Length","CreationTime","LastAccessTime","LastWriteTime"
"\\server\Data\project1\Analyze\GD4.2020\190109","Pic1_190110.Tif","\\server\Data\project1\Analyze\GD4.2020\190109\Pic1_190110.Tif","2785475","11.01.2019 13:28:45","10.01.2019 16:11:33","11.01.2019 13:28:46"
"\\server\Data\project1\Analyze\GD4.2020\190109","Pic2_190110.Tif","\\server\Data\project1\Analyze\GD4.2020\190109\Pic2_190110.Tif","2785475","11.01.2019 13:31:15","10.01.2019 16:11:34","11.01.2019 13:31:18"
"\\server\Data\project1\Analyze\GD4.2020\190109","Pic3_190110.Tif","\\server\Data\project1\Analyze\GD4.2020\190109\Pic3_190110.Tif","2785475","11.01.2019 13:33:36","10.01.2019 16:11:33","11.01.2019 13:33:38"

I need to replace the string '"\\server\Data\' with '"D:\new\Data\' but only at the start of the line.
The the 2nd occurrence of the string in the line should remain intact '"\\server\Data\'


The destination csv should look like this:
#TYPE Selected.System.IO.FileInfo
"Directory","Name","FullName","Length","CreationTime","LastAccessTime","LastWriteTime"
"D:\new\Data\project1\Analyze\GD4.2020\190109","Pic1_190110.Tif","\\server\Data\project1\Analyze\GD4.2020\190109\Pic1_190110.Tif","2785475","11.01.2019 13:28:45","10.01.2019 16:11:33","11.01.2019 13:28:46"
"D:\new\Data\project1\Analyze\GD4.2020\190109","Pic2_190110.Tif","\\server\Data\project1\Analyze\GD4.2020\190109\Pic2_190110.Tif","2785475","11.01.2019 13:31:15","10.01.2019 16:11:34","11.01.2019 13:31:18"
"D:\new\Data\project1\Analyze\GD4.2020\190109","Pic3_190110.Tif","\\server\Data\project1\Analyze\GD4.2020\190109\Pic3_190110.Tif","2785475","11.01.2019 13:33:36","10.01.2019 16:11:33","11.01.2019 13:33:38"

I've did:
##### Test 1

(gc -path .\source.csv -raw) -replace '"\\\\server\\Data\', '"D:\new\Data' | Out-File  .\new.csv}

Which did replace everty occurrence of the string, which is not wanted


##### Test 2
I need this on a column mode:

Import-Csv .\source.csv | ForEach-Object {
if ($_.Directory -startwith '"\\server\Data\') {
$_.Directory = '"D:\new\Data\'
}
$_
} | Export-Csv .\new.csv -NoTypeInformation

Any help appreciated very much
Thank You

Parents
  • #1
    $csv = Get-Content test.csv | ConvertFrom-Csv
    foreach ($i in $csv) { $i.Directory = $i.Directory -replace '\\\\server','D:\New' }
    $csv | Export-Csv new.csv
    
    # 2
    (Get-Content test.csv) -replace '^"\\\\server','D:\New' | Set-Content new1.csv
    

Reply Children
No Data