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

5 months, 2 weeks ago.

  • Author
  • #128316

    Topics: 3
    Replies: 3
    Points: -4
    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

    Topics: 0
    Replies: 38
    Points: 197
    Helping Hand
    Rank: Participant

    You need to specify the member that contains your text

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

      Topics: 3
      Replies: 3
      Points: -4
      Rank: Member

      Thank you so much @phansen.

      I very much appreciate your help.

      All the best


  • #128326

    Topics: 8
    Replies: 1190
    Points: 639
    Helping Hand
    Rank: Major 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 *, 

The topic ‘Change part of string imported from a csv.’ is closed to new replies.

denizli escort samsun escort muğla escort ataşehir escort kuşadası escort