Blog Archives

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!