locked
Using Get-Content RRS feed

  • Question

  • Hi all, i'm trying to write a Ps script that read a file and give me as result only some lines of this filtering the whole file.

    I'm trying to do this with this code:

    $testo = Get-Content C:\myfile.txt | where {$_ -Like "*word*"}
    ForEach-Object {$line in $testo -replace(";" , ","}

    i receive thi error:
    + ForEach-Object {$line in <<<<  $testo -replace (";" , ","}
        + CategoryInfo          : ParserError: (in:String) [], ParentContainsErrorRecordException
        + FullyQualifiedErrorId : UnexpectedToken

    How can i corret this instruction ?
    Sorry but i'm newbie using powershell :-(

     

    Thursday, January 12, 2012 4:27 PM

Answers

  • You can/should be able to use the 'Where' filter with Foreach, as long as it's piped, as mjolinor kind of hinted to. 
    (ex.: Get-Content Users.txt | Where{$_ -like *@domain.com} | Foreach-Object{Set-User -WindowsEmailAddress $null})

    It should be highly important to note, though, that any trailing or leading blank/white spaces will cause PowerShell to throw an error, because a ' ' character is still a character and Powershell will treat it as a literal, in the object. (ex: 'Somestuff' -ne 'Somestuff ')

     

    Get-Content "C:\myfile.txt" | Where{$_ -like "Word"} | Foreach-Object{($line in $testo) -replace(";",",")}
    

    • Marked as answer by OttobreRosso Monday, January 16, 2012 8:56 AM
    Saturday, January 14, 2012 9:08 PM

All replies

  • ForEach  ($line in $testo){$line -replace ";" , ","}

    foreach-object is only used in a pipeline.


    [string](0..33|%{[char][int](46+("686552495351636652556262185355647068516270555358646562655775 0645570").substring(($_*2),2))})-replace " "
    • Proposed as answer by Bigteddy Thursday, January 12, 2012 4:40 PM
    Thursday, January 12, 2012 4:37 PM
  • You can/should be able to use the 'Where' filter with Foreach, as long as it's piped, as mjolinor kind of hinted to. 
    (ex.: Get-Content Users.txt | Where{$_ -like *@domain.com} | Foreach-Object{Set-User -WindowsEmailAddress $null})

    It should be highly important to note, though, that any trailing or leading blank/white spaces will cause PowerShell to throw an error, because a ' ' character is still a character and Powershell will treat it as a literal, in the object. (ex: 'Somestuff' -ne 'Somestuff ')

     

    Get-Content "C:\myfile.txt" | Where{$_ -like "Word"} | Foreach-Object{($line in $testo) -replace(";",",")}
    

    • Marked as answer by OttobreRosso Monday, January 16, 2012 8:56 AM
    Saturday, January 14, 2012 9:08 PM