I just needed to get this working and came up with the following:
$InServerName = 'SomeServerNameorIPAddress'
$InFilePath = '\Sharename\SomePath\'
$InFileName = 'Filename.ext'
$OutServerName = 'SomeServerNameorIPAddress'
$OutFilePath = '\Sharename\SomePath\'
$OutFileName = 'Filename.out'
$InFile = -join('\\',$InServerName,$InFilePath,$InFilename)
$OutFile = -join('\\',$OutServerName,$OutFilePath,$OutFilename)
$FindStr = 'some string to match on'
$CompareStr = [scriptblock]::Create($FindStr)
$CompareStr
Get-Content $InFile | Where-Object {$_ -notmatch $CompareStr} | Set-Content $OutFile
Get-Content $OutFile
The key being that the 'Where-Object' using a script block (as denoted by the curly braces) requires declaring the variable in a script block creation event, hence the
$CompareStr = [scriptblock]::Create($FindStr)
line.
By structuring it in this way, one can create a function, pass it a text string to partially match, perform the script block creation with the passed value, and have it work correctly.
The answers above do not correctly explain how to pass the value to be replaced within a variable.
I had the exact same problem and you answer is 99% of what I need. The final issue is that I'm running the command in a loop with a $variable (replacing 'not' in your example). If I hard code a string it work perfectly; but if I use a variable it does nothing. Any idea why? I've tried both the bare variable and putting it in "quotes" – Stephen R – 2016-05-20T16:47:31.523
I would suggest that you use Set-Content instead of Out-File, the former deals in raw data and won't cut off strings or format objects. – JasonMArcher – 2010-08-17T04:16:30.820
How can this be modified to replace the text on those lines – Tom – 2019-11-06T15:27:51.263
@JasonMArcher Can you post an example using
Set-Content
? I don't believe thatSet-Content
is a drop-in replacement forOut-File
. – Iain Samuel McLean Elder – 2012-11-24T22:05:14.193Get-Content .\in.txt | Where-Object {$_ -notmatch 'not'} | Set-Content out.txt
Out-File is basically Set-Content, but it runs the input through the default formatting instead of simple string conversion. – JasonMArcher – 2012-11-24T22:25:41.577