Quick Tip: cleaning code copied from blogs.

I’ve decided that from time to time I should use this blog to write down some tiny things I came up with while working/ playing with PowerShell. My memory is leaking all the time, and once I write something down – I will be able to come back to it when needed. Puszczam oczko

Today I had need to copy some code from blog. Having PowerShell code on the blog is pretty neat, it’s usually nicer when you add line numbers. Line numbers are handy, but if you do not use plugin that allows others to take code without them – they get extra step of removing prefixes from copied “stuff”. Today I decided that it would be wiser to have some simple function to do that for me, instead of writing some one-liner each time:

function Remove-LinePrefix {             
param (            
    [Alias('PrefixPattern', 'PP')]            
    [string]$Pattern            
)            
            
if ($Text = $psISE.CurrentFile.Editor.Text) {            
    $Text = $Text.Split("`n") | ForEach-Object {            
        $_ -replace $Pattern            
    }            
    $psISE.CurrentFile.Editor.Text = $Text            
}            
}             

With this function defined I could copy code from blog directly to new ISE window and with single line (and proper regex pattern that would match only the prefix) clean it up:

Remove-LinePrefix -Pattern '^\s+\d+:'

Done! Uśmiech

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s