Downloading Useful Scripts

by Aug 24, 2020

The PowerShell Gallery not only offers public modules with new PowerShell commands but also public scripts. Before you invest time, you may want to investigate if someone else may have created PowerShell code that can do what you want.

Here is a quick example that illustrates how searching and downloading scripts via the PowerShell Gallery works:

# create temporary folder
$destination = Join-Path -Path $env:temp -ChildPath Scripts
$exists = Test-Path -Path $destination
if (!$exists) { $null = New-Item -Path $destination -ItemType Directory }

# offer to download scripts
Find-Script -Name Get-* | Select-Object -Property Name, Description |
  Out-GridView -Title 'Select script to download' -PassThru |
  ForEach-Object {
      Save-Script -Path $destination -Name $_.Name -Force
      $scriptPath = Join-Path -Path $destination -ChildPath "$($_.Name).ps1"
      ise $scriptPath
  }

When you run this code, Find-Script looks for any script that uses the Get verb. You can of course change this and search for anything you like. Next, all scripts that match your search are displayed in a grid view window. You can now select one or more that sound interesting.

PowerShell then downloads the selected scripts to a temporary folder and opens the scripts in the PowerShell ISE. Now you can review the source code and pick from it what you find useful.

Note: Due to a bug in Out-GridView, you need to wait for all data to arrive before you can select scripts. If you select scripts and click OK while Out-GridView still receives data, no data is passed, and no script will be downloaded.

To work around this, either wait long enough for the grid view window to be completely filled, or turn off the real-time mode by first collecting all data and only then showing the data in the grid view window:

# create temporary folder
$destination = Join-Path -Path $env:temp -ChildPath Scripts
$exists = Test-Path -Path $destination
if (!$exists) { $null = New-Item -Path $destination -ItemType Directory }

# offer to download scripts
Write-Warning "Retrieving scripts, hang on..."
# collecting all results in a variable to work around
# Out-GridView bug
$all = Find-Script -Name Get-* | Select-Object -Property Name, Description 
$all | Out-GridView -Title 'Select script to download' -PassThru |
  ForEach-Object {
      Save-Script -Path $destination -Name $_.Name -Force
      $scriptPath = Join-Path -Path $destination -ChildPath "$($_.Name).ps1"
      ise $scriptPath
  }


Twitter This Tip! ReTweet this Tip!