File to function / String to ScriptBlock


Someone asked a question in forum that got me thinking about PS1 files and functions. The problem was they couldn’t run PS1 files due to the security on the machine. Mostly they wanted to do this to learn, and I suspect it was just from running files they’ve download.

At any rate, this got me thinking, how could I import a PS1 in to my session as a function? Well after a little tinkering, I found a way.

###create ps1 file for test

Set-Content -path testadd.ps1 -value ‘
    param (
    [int] $variable1,
    [int] $variable2
    )
    $variable3=$variable1+$variable2;
    $variable3
    ‘

##create a function from our testadd.ps1 script

New-Item -Path function: -Name SimpleAdd -ItemType function -Value ([scriptblock]::create((gc .\testadd.ps1) -join [environment]::newline))

SimpleAdd 1 2

That’s all there is to it! Not really sure how useful this is, but was a neat little experiment.

Enjoy!

Advertisements

About jrich

I am the Solutions Architect for Apex Learning in Seattle WA. I've been working with computers since I was 13. Started programming when I was 14. Had my first IT job as tech support at an ISP at the age of 15 and became a network admin at the age of 17. Since then I've worked at a variety of small to mid size companies supporting, maintaining and developing all aspects of IT. Mostly working with Windows based networks but have recently been working with Solaris system as well. I created this blog mostly as a place for me to take my own notes, but also share things that I had a hard time finding the info for.

Posted on June 15, 2011, in WMF (Powershell/WinRM) and tagged , , , . Bookmark the permalink. Leave a comment.

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

%d bloggers like this: