Cricketer
Cricketer

Reputation: 409

Error: You must provide a value expression on the right hand side of the '-' operator

You can try this:

function setConfig( $file) {
    $content = Get-Content $file
    $content -remove '$content[1..14]'
    Set-Content $file     
}

I want to make a function through which I can pass through files so that it deletes specific lines or bunch of lines

Upvotes: 0

Views: 1056

Answers (1)

Matt
Matt

Reputation: 46730

I don't recall -remove being a PowerShell operator and I should think the error you would be getting to be:

Unexpected token '-remove' in expression or statement.

Also you are preventing PowerShell from expanding the code in single quotes so it is therefore being treated as the literal string "$content[1..14]".

I am going to take the liberty of assuming you are trying to remove the first 14ish lines of code from a file while keeping the first yes?

I create a test file that contains 30 lines using the following code.

1..30 | Set-Content C:\temp\30lines.txt

Then we use this updated version of your function

function setConfig($file){
    $content = Get-Content $file
    $content | Select-Object -Index (,0 + (14..$($content.Count))) | Set-Content $file     
}

Using the -Index of Select-Object we get the first line ,0 then add the remaining lines after the 14th (14..$($content.Count))). The comma is needed in from of the 0 since we went to combine two arrays of numbers. An updated file content would look like this. Change the -Index values to suit your needs.

1
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30

Upvotes: 1

Related Questions