Quantcast
Channel: PowerShell.com – PowerShell Scripts, Tips, Forums, and Resources
Viewing all articles
Browse latest Browse all 6937

Powershell v2. Delete or Remove Lines of Text. Regex Issue.

$
0
0

Hi All,

First time posting and very new to PS. Please be gentle ;)

I've been through so many posts today that offer Powershell examples of how to remove entire lines from a file by using line numbers. Unfortunately none of them do quite what I need, or they have some 'but' type clauses in them.

The closest example I found uses the -remove method. This managed to do the job, until I noticed that not all lines that I was trying to remove, were indeed removed. After more research I found that -remove is reliant on Regex and Regex does not like certain special characters which happen to be in some of the lines I wish to delete/remove.

The example I'm using is not my own work. I found the example from a guy over on StackOverflow. I found it very simple and elegant though, so I made it into a Function:

FunctionDeleteLineFromFile($Path, $File, $LineNumber){
        $Contents =Get-Content $Path\$File
        $Contents -replace $Contents[$LineNumber -1],""|Set-Content $Path\$File}

A great example I reckon. Only regex won't work with the special chars.

The goal is this: To make a function that doesn't care about what is in the line. I wan't to feed it a path, file and line, then have the function delete that line and save the file.

I'm at the end of a +200 line powershell script and this is my last hurdle. Any help would be greatly appreciated.

On the downside, the company I work for have just today packaged a fix via CCM that resolves the very issue I was attempting to resolve using PS (don't you just hate being late to the party!). But since this is my first PS project I still want to finish it up (I'm stubborn that way).

Thanks in advance for any input.

Best Regards,

A Powershell Nooby ;)


Viewing all articles
Browse latest Browse all 6937

Trending Articles