Skip to content

Instantly share code, notes, and snippets.

@steviecoaster
Last active January 10, 2025 21:14
Show Gist options
  • Save steviecoaster/027d2e53b79e200ffb2455f74e2f1308 to your computer and use it in GitHub Desktop.
Save steviecoaster/027d2e53b79e200ffb2455f74e2f1308 to your computer and use it in GitHub Desktop.
Understanding using Scriptblocks in PowerShell
#Download the sample_script.ps1 contents included in this gist
$url = 'https://gist.githubusercontent.com/steviecoaster/027d2e53b79e200ffb2455f74e2f1308/raw//sample_script.ps1'
$scriptData = [System.Net.WebClient]::new().DownloadString($url)
<#
The above uses the [System.Net.WebClient] .Net class directly, however you can use New-Object if you are more comfortable:
(New-Object System.Net.WebClient).DownloadString('https://gist.githubusercontent.com/steviecoaster/027d2e53b79e200ffb2455f74e2f1308/raw/3bc513de7c664915691b6bbd78c49649069f52c5/sample_script.ps1')
#>
# Next, we create our script block, and fill it with our $scriptData
$scriptBlock = [Scriptblock]::Create($scriptData)
# Now that we have our scriptblock, we can execute it, but first let's define those parameters it can accept
# We'll define them as a hashtable so we can use splatting to provide them to our scriptblock
# See Get-Help about_Splatting forr more info about splatting.NOTE: You may need to run Update-Help first
$scriptParameters = @{
FirstName = 'Stephen'
BlueskyHandle = '@steviecoaster.dev'
}
# Let's execute our script block. We do that with the PowerShell call (&) operator.
# Go ahead and give it a try!
& $scriptblock @scriptParameters
[CmdletBinding()]
Param(
[Parameter()]
[String]
$FirstName,
[Parameter()]
[String]
$BlueskyHandle
)
end {
Write-Host 'Scriptblocks are so cool!'
[pscustomobject]@{
FirstName = $FirstName
BlueskyHandle = $BlueSkyHandle
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment