set-content

This topic contains 3 replies, has 2 voices, and was last updated by  Tony Antony 12 months ago.

  • Author
    Posts
  • #60054

    Tony Antony
    Participant

    Hello,

    I have a script to put these numbers in order

    1=mkelley@company.com
    2=jbruce@company.com
    3=oreynolds@company.com
    4=JSTACK@company.com
    5=Dwu@company.com
    1433=mkuss@company.com
    1434=ayoloye@company.com
    1435=tonierras@company.com
    1436=sgoldsborough@company.com
    1437=pbeavers@company.com
    1438=ederengowski@company.com
    1439=alippard@company.com
    1440=klaw@company.com
    one@company.com
    three@company.com

    so that it looks like

    1=mkelley@company.com
    2=jbruce@company.com
    3=oreynolds@company.com
    4=JSTACK@company.com
    5=Dwu@company.com
    6=mkuss@company.com
    7=ayoloye@company.com
    8=tonierras@company.com
    9=sgoldsborough@company.com
    10=pbeavers@company.com
    11=ederengowski@company.com
    12=alippard@company.com
    13=klaw@company.com
    14=one@company.com
    15=three@company.com

    The problem is that the below Set-Content appends only 15=three@company.com, and deletes the original text.

        $INI_Location = "\\hqfs1\users\tantony\PowerShell\CalenderGroup\config.ini"
        $Read_INI = Get-Content $INI_Location
    For($Index=0; $Index -lt $List_of_Users.length; $Index++)
                {            
                    $Email = ($List_of_Users[$Index]) -creplace '^[^=]*=', ''
                    $Index_Plus_One = $Index + 1
                    $Re_Index = "$Index_Plus_One=$Email"
                    $Re_Index | Set-Content $INI_Location -Force
    
                    Write-Host $Re_Index
                } 

    Thanks,

    Tony

  • #60057

    Rob Simmers
    Participant

    You are calling Set-Content in your loop, so the last enumerated line will be set overwriting the file. Take a look at this simplified logic:

    $results = foreach ($line in (Get-Content "C:\Users\Rob\Desktop\Archive\config.ini")) {
        "{0}={1}" -f $line.ReadCount, ($line -creplace '^[^=]*=', '')
    }
    
    $results | Set-Content "C:\Users\Rob\Desktop\Archive\config.ini"
    
  • #60060

    Tony Antony
    Participant

    I figured it out, thanks. I forgot to actually write the files before set-content

  • #60061

    Tony Antony
    Participant

    Writing powershell on less sleep, not paying attention to details 🙂

You must be logged in to reply to this topic.