Remove content from files with Powershell

Spread the love

Remove content from files with Powershell

I love Windows PowerShell. It’s the missing < a> shell/scripting environment that could never be properly satisfied with just DOS commands and batch files. I know it’s been out for a while now, but I’ve only recently started getting on top of it, and it’s been fantastic so far.

Quite often I find myself needing to do little maintenance jobs involving iterating through files and tranforming them — C# source code, SQL scripts, my MP3 collection etc. Powershell is the perfect tool for these sorts of tasks. Here’s a very simple (and probably not that efficient) snippet I wrote last week to strip out SQL Server Management Studio’s useless ‘descriptive headers’ comments from a nested hierarchy of 2,000 generated SQL scripts:

/****** Object:  Table [dbo].[hibernate_unique_key]    Script Date: 04/12/2009 11:35:29 ******/CREATE TABLE [dbo].[hibernate_unique_key](        [next_hi] [int] NULL) ON [PRIMARY]GO
dir -recurse -filter *.sql $src | foreach ($_) {        $file = $_.fullname        echo $file        (get-content $file) | where {$_ -notmatch "^s?/****** Object:.*$" } | out-file $file}

How easy was that? I definitely need to learn more of this stuff!