#requires -version 2.0 <# ----------------------------------------------------------------------------- Script: LoadCmds.ps1 Version: 2.0 Author: Jeffery Hicks http://jdhitsolutions.com/blog http://twitter.com/JeffHicks http://www.ScriptingGeek.com Date: 9/22/2011 Keywords: Scriptblock, variable Comments: "Those who forget to script are doomed to repeat their work." **************************************************************** * DO NOT USE IN A PRODUCTION ENVIRONMENT UNTIL YOU HAVE TESTED * * THOROUGHLY IN A LAB ENVIRONMENT. USE AT YOUR OWN RISK. IF * * YOU DO NOT UNDERSTAND WHAT THIS SCRIPT DOES OR HOW IT WORKS, * * DO NOT USE IT OUTSIDE OF A SECURE, TEST SETTING. * **************************************************************** ----------------------------------------------------------------------------- #> [cmdletbinding()] param ( [Parameter(Position=0)] [ValidateNotNullorEmpty()] [string]$Path="cmds.txt", [string]$Delimiter="~", [switch]$Passthru ) Write-Verbose "Starting $($myinvocation.mycommand)" if (Test-Path $path) { Write-Verbose "Processing $path" #filter out blanks and lines that start with a comment Get-Content $path | Where { ($_ -match $delimiter) -AND (!($_.Trim().StartsWith("#"))) } | foreach -begin { $script:newvariables=@() } -process { #split the line at the ~ $data=$_.Split("~") $sb=$data[0].Trim() $cmd=$data[1].Trim() Write-Verbose "Creating $sb" #add the scriptblock name to the array $script:newvariables+=$sb #create a script block object and assign it to the value variable $value=$executioncontext.InvokeCommand.NewScriptBlock($cmd) #define the new variable Set-Variable -name $sb -Value $value -Scope Global } -end { if ($Passthru) { #write the new variables to the pipeline if -Passthru get-variable -Name $script:newvariables } } #close end } #close if else { Write-Warning "Failed to find $path" } Write-Verbose "Ending $($myinvocation.mycommand)" #end