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

 
Participant
6 days, 15 hours ago.

  • Author
    Posts
  • #128316

    Participant
    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= "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

  • #128317

    Participant
    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

      Participant
      Points: -5
      Rank: Member

      Thank you so much @phansen.

      I very much appreciate your help.

      All the best

      M

  • #128326

    Participant
    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 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()}}
    

You must be logged in to reply to this topic.