Change part of string imported from a csv.

I need to replace some placeholder text in a csv file I am importing into a variable, whilst keeping the variable as a PSCustomObject. Sounds so simple but I am struggling.

Example PowerShell code is:

$serverfqdn= "myhost.mydomain.com"
$hostname = $serverfqdn.split(".")[0]
$csvimportfile = import-csv "P:\path\to\my.csv"

$csvimportfile | get-member

TypeName: System.Management.Automation.PSCustomObject

Name MemberType Definition
---- ---------- ----------
Equals Method bool Equals(System.Object obj)
GetHashCode Method int GetHashCode()
GetType Method type GetType()
ToString Method string ToString()
Description NoteProperty string Description=A description
Name NoteProperty string Name=Some other text here with the text I want to replace being: TEXTTOREPLACE
Notes NoteProperty string Notes=Some notes

I have tried:

$csvimportfile = $csvimportfile -replace("TEXTTOREPLACE","$hostname")

But this seems to change the $csvimportfile variable into a TypeName: System.String and I lose the NoteProperty MemberType fields.

What other methods can I use to replace the placeholder text, whilst maintaining the $csvimportfile variable is a TypeName: System.Management.Automation.PSCustomObject

Any help will be appreciated.

Thanks
M

You need to specify the member that contains your text

foreach($entry in $csvimportfile) {
    $entry.Name = $entry.Name -replace "TEXTTOREPLACE",$hostname
}

Thank you so much @phansen.

I very much appreciate your help.

All the best

M

You can also use calculated properties. The first example adds the hostname to all entries. The second modifies the Email property, say it’s John.Smith@MyCompany.com and you want it all lowercase, you could overwrite all entries as lowercase.

$serverfqdn= "myhost.mydomain.com"
$hostname = $serverfqdn.split(".")[0]
$csvimportfile = import-csv "P:\path\to\my.csv" | Select *, 
                                                         @{Name='HostName';Expression={$hostname}},
                                                         @{Name='Email';Expression={$_.Email.ToLower()}}