PowerShell One-Liner to Locate Scripts and Automatically Open them in New Tabs in the ISE

I recently wrote a blog about how to find scripts where you had accomplished some specific task. That blog article was titled How do I find that PowerShell Script where I did __________?.

What if you not only want to find those scripts, but also open them automatically in new tabs in the PowerShell ISE? It just so happens that you’re in luck:

Get-ChildItem -Path 'C:\Scripts\*.ps1' -Recurse |
Select-String -Pattern "1.." -SimpleMatch |
Select-Object -Property Path -Unique |
ForEach-Object {
    $psISE.CurrentPowerShellTab.Files.Add("$($_.Path)")
} | Out-Null

I went ahead and piped the results to Out-Null because I didn’t want anything returned at the command line. As you can see, there were three scripts that were automatically opened in new tabs in the PowerShell ISE:

ise-tabs1a.png

The one-liner shown above was a direct copy and paste from the previously referenced blog article, but you could also expand the “Path” property to make it a little cleaner:

Get-ChildItem -Path 'C:\Scripts\*.ps1' -Recurse |
Select-String -Pattern "1.." -SimpleMatch |
Select-Object -ExpandProperty Path -Unique |
ForEach-Object {
    $psISE.CurrentPowerShellTab.Files.Add("$_")
} | Out-Null

These scripts could of course return a lot of results, more than you would want to try to open in new tabs in the ISE so you could only open them if say there’s no more than a dozen results, otherwise return a warning and the results at the command line:

$results = Get-ChildItem -Path 'C:\Scripts\*.ps1' -Recurse |
           Select-String -Pattern "1.." -SimpleMatch |
           Select-Object -ExpandProperty Path -Unique

if ($results.count -le 12) {
    foreach ($result in $results) {
        $psISE.CurrentPowerShellTab.Files.Add("$result")
    }
}
else {
    Write-Warning -Message "There were $($results.count) results which is too many to open in new tabs."
    Write-Output $results
}

ise-tabs1b.png

The magic of opening a script in a new tab in the PowerShell ISE is with this command:

$psISE.CurrentPowerShellTab.Files.Add("ScriptName")

ยต