PS Cmdlets
22.1.16
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
Invoke-RestMethod (Microsoft.PowerShell.Utility) - PowerShell
docsmsft
Here are some examples of how to use Invoke-RestMethod to get the raw content from a Url
1
PS C:\> Invoke-RestMethod -Uri https://raw.githubusercontent.com/OSDeploy/PSCloudScript/main/ps-cmdlets.txt
2
This is a test to see if this raw content can be saved as a PowerShell string
3
4
PS C:\> irm https://raw.githubusercontent.com/OSDeploy/PSCloudScript/main/ps-cmdlets.txt
5
This is a test to see if this raw content can be saved as a PowerShell string
6
7
PS C:\> $String = irm raw.githubusercontent.com/OSDeploy/PSCloudScript/main/ps-cmdlets.txt
8
PS C:\> $String
9
This is a test to see if this raw content can be saved as a PowerShell string
Copied!

Invoke-Expression

This cmdlet is used to execute a PowerShell Command. You can read Microsoft's documentation here
Invoke-Expression (Microsoft.PowerShell.Utility) - PowerShell
docsmsft
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
1
PS D:\> $String = @'
2
Write-Host 'This is PowerShell String'
3
'@
4
5
PS D:\> Invoke-Expression -Command $String
6
This is PowerShell String
7
8
PS D:\> Invoke-Expression $String
9
This is PowerShell String
10
11
PS D:\> iex $String
12
This is PowerShell String
Copied!
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
1
PS D:\> $StringFunction = @'
2
function Test-PowerShell
3
{
4
[CmdletBinding()]
5
param()
6
Write-Host 'This is a PowerShell Function'
7
Write-Verbose 'And this is a Verbose PowerShell Function'
8
}
9
'@
10
11
PS D:\> Invoke-Expression -Command $StringFunction
12
13
PS D:\> Test-PowerShell
14
This is a PowerShell Function
15
16
PS D:\> Test-PowerShell -Verbose
17
This is a PowerShell Function
18
VERBOSE: And this is a Verbose PowerShell Function
Copied!

Order

These commands have to follow a specific order. You need the content from Invoke-RestMethod before you can execute in Invoke-Expression
1
#Command in parenthesis is processed first in both of these examples
2
Invoke-Expression -Command (Invoke-RestMethod -Uri $Uri)
3
#Alternate using Alias
4
iex(irm $Uri)
5
6
#Pipeline can be used
7
Invoke-RestMethod -Uri $Uri | Invoke-Expression
8
#Alternate using Alias
9
irm $Uri | iex
Copied!

Sponsor

OSDeploy is sponsored by Recast Software and their Systems Management Tools
Home
Recast Software
Sponsored by Recast Software