Replacing Data in .CSV Field

J

Jason Silva

Hello,

I had posted this in another forum but it was suggested this would be a
better spot for this question.

I have a .CSV file that I import in with Import-CSV. I just need to replace
one of the fields in this file with a subset of that field's data. I am able
to do up to the point of returning just the data I need, but I can't seem to
use the replace command properly. In other words, the field data isn't
actually being replaced. Here's a subset of what I'm trying to do:

$SCRIPT:IMP = Import-CSV C:\Tools\PSScripts\ShellAuditSubSet.csv
$IMP | foreach-object { $_.Message
$CleanReturn = (CleanData ($_.Message))
if($Messy -cne "")
{
($IMP.Message) -replace $_.Message, $CleanReturn
Write-Host "MESSAGE DATA IS " + $_.Message
}
}

$CleanReturn's Data is what I need, I'm just doing something wrong to stuff
it in. I'm almost considering deleting the current Message Field and adding
a new one with $CleanReturn's Data.

Thanks,
 

My Computer

R

Robert Robelo

$IMP.Message shouldn't return anything because $IMP is, or should be, a collection and Message is a Field in your CSV data.
Modify the values through the current pipeline object.
Since PowerShell's -replace operator takes a RegEx as its first argument it's not a bad idea to escape the string/pattern you intend to replace, specially if it may contain any of these chars: #.$^{[()*+?\

# change this line:
($IMP.Message) -replace $_.Message, $CleanReturn

# to... (mind word wrap, should be 1 line)
$_.Message = $_.Message -replace [regex]::Escape($_.Message), $CleanReturn

# verify changes are satisfactory
$IMP

# Then you can save the CSV data back:
Export-CSV C:\Tools\PSScripts\ShellAuditSubSet.csv -NoType

--
Robert
 

My Computer

R

Robert Robelo

Sorry, I missed the last paragraph of your post :)

# change this line:
($IMP.Message) -replace $_.Message, $CleanReturn

# to...
$_.Message = $CleanReturn

--
Robert
 

My Computer

J

Jason Silva

Robert,

WOW, it seems so simple now, thank you. That worked. Ideally I would like
to export the events without this trouble text, but this is a good work
around until then.

Thanks,

Jason

"Robert Robelo" wrote:

> Sorry, I missed the last paragraph of your post :)
>
> # change this line:
> ($IMP.Message) -replace $_.Message, $CleanReturn
>
> # to...
> $_.Message = $CleanReturn
>
> --
> Robert
>
 

My Computer

Top