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:
1Get-ChildItem -Path 'C:\Scripts\*.ps1' -Recurse |
2Select-String -Pattern "1.." -SimpleMatch |
3Select-Object -Property Path -Unique |
4ForEach-Object {
5 $psISE.CurrentPowerShellTab.Files.Add("$($_.Path)")
6} | 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:
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:
1Get-ChildItem -Path 'C:\Scripts\*.ps1' -Recurse |
2Select-String -Pattern "1.." -SimpleMatch |
3Select-Object -ExpandProperty Path -Unique |
4ForEach-Object {
5 $psISE.CurrentPowerShellTab.Files.Add("$_")
6} | 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:
1$results = Get-ChildItem -Path 'C:\Scripts\*.ps1' -Recurse |
2 Select-String -Pattern "1.." -SimpleMatch |
3 Select-Object -ExpandProperty Path -Unique
4
5if ($results.count -le 12) {
6 foreach ($result in $results) {
7 $psISE.CurrentPowerShellTab.Files.Add("$result")
8 }
9}
10else {
11 Write-Warning -Message "There were $($results.count) results which is too many to open in new tabs."
12 Write-Output $results
13}
The magic of opening a script in a new tab in the PowerShell ISE is with this command:
1$psISE.CurrentPowerShellTab.Files.Add("ScriptName")
µ