The two PowerShell Cmdlets that are used are Invoke-RestMethodand Invoke-Expression. It is also important that these cmdlets are processed in this order, which I will touch on at the bottom of this page
Invoke-RestMethod
This cmdlet is used to return the contents of a provided URL in a structured, typically Raw format
Here are some examples of how to use Invoke-RestMethod to get the raw content from a Url
PS C:\>Invoke-RestMethod-Uri https://raw.githubusercontent.com/OSDeploy/PSCloudScript/main/ps-cmdlets.txtThis is a test to see if this raw content can be saved as a PowerShell stringPS C:\> irm https://raw.githubusercontent.com/OSDeploy/PSCloudScript/main/ps-cmdlets.txtThis is a test to see if this raw content can be saved as a PowerShell stringPS C:\> $String = irm raw.githubusercontent.com/OSDeploy/PSCloudScript/main/ps-cmdlets.txtPS C:\> $StringThis is a test to see if this raw content can be saved as a PowerShell string
Invoke-Expression
This cmdlet is used to execute a PowerShell Command. You can read Microsoft's documentation here
If you read the Microsoft Doc, you'll understand that iex commands can come from a String. This can be easily demonstrated in this example
PS D:\> $String =@'Write-Host 'This is PowerShell String''@PS D:\>Invoke-Expression-Command $StringThis is PowerShell StringPS D:\>Invoke-Expression $StringThis is PowerShell StringPS D:\> iex $StringThis is PowerShell String
This method even works if there is a PowerShell function in the String. Keep in mind this function is only available in the current PowerShell session
PS D:\> $StringFunction =@'function Test-PowerShell{ [CmdletBinding()] param() Write-Host 'This is a PowerShell Function' Write-Verbose 'And this is a Verbose PowerShell Function'}'@PS D:\>Invoke-Expression-Command $StringFunctionPS D:\>Test-PowerShellThis is a PowerShell FunctionPS D:\>Test-PowerShell-VerboseThis is a PowerShell FunctionVERBOSE: And this is a Verbose PowerShell Function
Order
These commands have to follow a specific order. You need the content from Invoke-RestMethod before you can execute in Invoke-Expression
#Command in parenthesis is processed first in both of these examples
Invoke-Expression -Command (Invoke-RestMethod -Uri $Uri)
#Alternate using Alias
iex(irm $Uri)
#Pipeline can be used
Invoke-RestMethod -Uri $Uri | Invoke-Expression
#Alternate using Alias
irm $Uri | iex
Sponsor
OSDeploy is sponsored by Recast Software and their Systems Management Tools