Search code examples
powershellfunctionautoloaddynamic-function

PowerShell, auto load functions from internet on demand


It was pointed out to me (in PowerShell, replicate bash parallel ping) that I can load a function from the internet as follows:

iex (irm https://raw.githubusercontent.com/proxb/AsyncFunctions/master/Test-ConnectionAsync.ps1)

The url referenced Test-ConnectionAsync.ps1 contains two functions: Ping-Subnet and Test-ConnectionAsync

This made me wonder if I could then define bypass functions in my personal module that are dummy functions that will be permanently overridden as soon as they are invoked. e.g.

function Ping-Subnet <mimic the switches of the function to be loaded> {
    if <function is not already loaded from internet> {
        iex (irm https://raw.githubusercontent.com/proxb/AsyncFunctions/master/Test-ConnectionAsync.ps1)
    }
    # Now, somehow, permanently overwrite Ping-Subnet to be the function that loaded from the URL
    Ping-Subnet <pass the switches that we mimicked to the required function that we have just loaded>
}

This would very simply allow me to reference a number of useful scripts directly from my module but without having to load them all from the internet upon loading the Module (i.e. the functions are only loaded on demand, when I invoke them, and I will often never invoke the functions unless I need them).


Solution

  • function Ping-Subnet{
        $toImport = (IRM "https://raw.githubusercontent.com/proxb/AsyncFunctions/master/Test-ConnectionAsync.ps1").
                    Replace([Text.Encoding]::UTF8.GetString((239,187,191)),"")
        NMO([ScriptBlock]::Create($toImport))|Out-Null
        $MyInvocation.Line|IEX
    }
    function Test-ConnectionAsync{
        $toImport = (IRM "https://raw.githubusercontent.com/proxb/AsyncFunctions/master/Test-ConnectionAsync.ps1").
                    Replace([Text.Encoding]::UTF8.GetString((239,187,191)),"")
        NMO([ScriptBlock]::Create($toImport))|Out-Null
        $MyInvocation.Line|IEX
    }
    
    Ping-Subnet -Result Success
    
    Test-ConnectionAsync -Computername $env:COMPUTERNAME
    

    Result:

    Computername   Result
    ------------   ------
    192.168.1.1   Success
    192.168.1.2   Success
    192.168.1.146 Success
    
    Computername IPAddress                  Result
    ------------ ---------                  ------
    HOME-PC      fe80::123:1234:ABCD:EF12  Success