Change part of string imported from a csv.

Welcome Forums General PowerShell Q&A Change part of string imported from a csv.

This topic contains 3 replies, has 3 voices, and was last updated by

6 days, 15 hours ago.

  • Author
  • #128316

    Points: -5
    Rank: Member

    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= ""
    $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.


  • #128317

    Points: 83
    Helping Hand
    Rank: Member

    You need to specify the member that contains your text

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

      Points: -5
      Rank: Member

      Thank you so much @phansen.

      I very much appreciate your help.

      All the best


  • #128326

    Points: 305
    Helping Hand
    Rank: Contributor

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

    $serverfqdn= ""
    $hostname = $serverfqdn.split(".")[0]
    $csvimportfile = import-csv "P:\path\to\my.csv" | Select *, 

You must be logged in to reply to this topic.