Windows Vista Forums

Set-Content not updating file after get-content and forEach-Object
  1. #1


    Tolli Guest

    Set-Content not updating file after get-content and forEach-Object

    I have a file I need to append a value to the end of a specific line of text
    (in a random location in the file).



    First entry works (replaces text in file) second one does not update file at
    the end of the line. I can't use the first entry because I can't do a
    -replace.

    1# (get-content $file) | foreach-object {$_ -replace "Group Membership","My
    Membership"} | Set-Content $file

    2# (Get-Content $File) | ForEach-Object {if
    ($_.contains("S-1-5-32-545__Members") -eq $true) {$_ = $_+",*S-1-5-4"
    }} | Set-Content $File

    Even though $_ is being updated with the new value, that new value is not
    being passed on to the Set-Content command.

      My System SpecsSystem Spec

  2. #2


    Kiron Guest

    Re: Set-Content not updating file after get-content and forEach-Object

    The if block changes the value of the object but it doesn't send it through
    the pipeline; add another statement inside the block that will send the
    changed object through. Also, need to add an else statement to output the
    lines that don't match the if condition:

    (Get-Content $File) | ForEach-Object {if
    ($_.contains("S-1-5-32-545__Members") -eq $true) {$_ = $_+",*S-1-5-4"; $_}
    else {$_}} | Set-Content $File

    You can also use -replace:

    (Get-Content $File) | ForEach-Object {$_ -replace "S-1-5-32-545__Members",
    "S-1-5-32-545__Members,*S-1-5-4"} | Set-Content $File

    --
    Kiron


      My System SpecsSystem Spec

Set-Content not updating file after get-content and forEach-Object problems?

Similar Threads
Thread Thread Starter Forum Replies Last Post
Get-content -wait not updating? PeoB PowerShell 2 26 Nov 2008
Get-Content and Group-Object Kam-Hung Soh PowerShell 10 05 Jan 2008
Issue: getting/setting variable content using Get/Set-Content =?Utf-8?B?Um9tYW4gS3V6bWlu?= PowerShell 1 23 Sep 2006
About adding content to the same file using "add-content" =?Utf-8?B?ZGFuY2UyZGll?= PowerShell 3 14 Aug 2006
Weirdness with get-content | replace | set-content - file content is deleted!! Andrew Watt [MVP] PowerShell 4 23 May 2006