Menu

Virtual Geek

Tales from real IT system administrators world and non-production environment

Powershell Trick : Execute or run any file as a script file

October 18, 2017 02:22PM

This blog post is addition to my earlier article Different ways to bypass Powershell execution policy :.ps1 cannot be loaded because running scripts is disabled. Just to recap If you have execution policy blocked in your environment and want to execute riles in PowerShell, you can compile the the file to PowerShell ScriptBlock using .net object. In the screen shot right side is my text file with sample content.

First line of the script is reading text file, using -Raw parameter, will return all data as single string. This us required in next line of code.
$AnyFile = Get-Content C:\temp\AnyFile.txt -Raw

In next I am using .net object System.Management.Automation.ScriptBlock and method create to compile text content to script block.
$ScriptBlock = [System.Management.Automation.ScriptBlock]::Create($AnyFile)

Using & I can easily execute the this compiled and formatted text file.
& $ScriptBlock

Powershell script executionpolicy execute any file as script, get-content, automation, scriptblock create .net system.management,automation.scriptblock create

Check the gettype() and its fullname results, information is perfect for execution.

PS C:\> $ScriptBlock.GetType()
IsPublic IsSerial Name                                     BaseType
-------- -------- ----                                     --------
True     True     ScriptBlock                              System.Object

PS C:\> $ScriptBlock.GetType().Fullname
System.Management.Automation.ScriptBlock

Powershell .net object scriptblock gettype(), system.management.automation.scriptblock convert execute any file compile

I have converted this script to function and it can be stored in PowerShell $PROFILE and can be invoked any time as below.

System.Management.Automation.ScriptBlock microsoft Powershell .net object GetType().Fullname, function ValidateScript cmdletbinding Get-content -raw

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
Function Invoke-FileAsScript {
Param (
    [CmdletBinding()]
    [ValidateScript({
        If(Test-Path $_){$true}else{throw "Invalid path given: $_"}
    })]
    [string]$Path
)
    $AnyFile = Get-Content -Path $Path -Raw
    $ScriptBlock = [System.Management.Automation.ScriptBlock]::Create($AnyFile)
    & $ScriptBlock
}

Invoke-FileAsScript -Path C:\Temp\Text.txt

Useful blogs
Different ways to bypass Powershell execution policy :.ps1 cannot be loaded because running scripts is disabled
Installing, importing and using any module in powershell

Go Back

Comment