Last week I shared a script for finding recently modified files in a given directory. In fact, it wouldn't be that difficult to find the last files I was working on and open them in the PowerShell ISE. Assuming my Get-RecentFile function is loaded it is a simple as this:
ManageEngine ADManager Plus - Download Free Trial
Exclusive offer on ADManager Plus for US and UK regions. Claim now!
get-recentfile -Days 4 -Newest 2 | foreach {ise $_.fullname}
But often, I already have the PowerShell ISE open. True, I could use the same expression substituting 'psedit' for 'ise', but with the ISE I'm all about working quickly So I have another function targeted for the PowerShell ISE called Open-LastScript.
#Requires -version 4.0 Function Open-LastScript { <# .SYNOPSIS List most recently edited PowerShell files and open them in the PowerShell ISE. .DESCRIPTION This command will find recently modified PowerShell scripts and display the results using Out-GridView. The command will search in the given folder for *.ps1,*.psd1,*.psm1,*.ps1xml files. It will limit the results to the newest number of files based on the last write time. YOu have the option to search recursively. Output is sent to Out-Gridview. If you select any files they will open in the ISE. The function will use a global variable you can set in your profile or session called ScriptPath for your script directory. Otherwise it will use the current location. NOTE: This command will only run in the PowerShell ISE. .PARAMETER Path The path to your scripts. The default is a global variable ScriptPath which you can set. Otherwise the function will use the current location. .PARAMETER Newest Limits the number of results based on the last modified time property. .PARAMETER Include An array of script-related file extensions or name filter. This parameter has an alias of filter. .PARAMETER Recurse Search recursively from the specified path. .EXAMPLE PS C:\> Open-LastScript Use default settings and display 10 most recent script files in the path specified by $Scriptpath. .EXAMPLE PS C:\> Open-LastScript C:\work 5 -recurse Get the 5 most recent script files from C:\Work and all subfolders. .EXAMPLE PS C:\> Open-Lastscript -include "test*" Get the 10 most recent files that start with 'test'. .NOTES NAME : Open-LastScript VERSION : 2.0 LAST UPDATED: March 19, 2015 AUTHOR : Jeffery Hicks (https://jdhitsolutions.com/blog) Learn more about PowerShell:Essential PowerShell Learning Resources**************************************************************** * DO NOT USE IN A PRODUCTION ENVIRONMENT UNTIL YOU HAVE TESTED * * THOROUGHLY IN A LAB ENVIRONMENT. USE AT YOUR OWN RISK. IF * * YOU DO NOT UNDERSTAND WHAT THIS SCRIPT DOES OR HOW IT WORKS, * * DO NOT USE IT OUTSIDE OF A SECURE, TEST SETTING. * **************************************************************** .LINK Out-GridView Get-Childitem .INPUTS String .OUTPUTS None #> [cmdletbinding()] Param( [Parameter(Position=0)] [ValidateScript({Test-Path $_})] [string]$Path = $global:ScriptPath, [Parameter(Position=1)] [ValidateScript({$_ -ge 1})] [int]$Newest = 10, #define a list of file extensions [Alias("filter")] [string[]]$Include = @("*.ps1","*.psd1","*.psm1","*.ps1xml"), [switch]$Recurse ) #verify we are in the ISE if ($host.name -notmatch 'Windows PowerShell ISE Host') { Write-Warning "This command requires the PowerShell ISE" #bail out Return } #If no path specified use the current location if (-Not $path) { Write-Verbose "Using current location" $Path = (Get-Location).Path } #verify path belongs to the filesystem Write-Verbose "Validating $path as a filesystem path" if ((Resolve-Path -Path $path).Provider -notmatch "FileSystem") { Write-Warning "The path $path is not recognized as a file system path." #bail out Return } Write-Verbose "Getting $newest script files from $path" Write-Verbose ($include -join ",") #construct a title for Out-GridView $Title = "$newest Most Recent Script Files in $Path. Select 1 or more to edit." #hash table of parameters to splat to Get-ChildItem $dirParams = @{ Path = "$Path\*" Include = $include } if ($Recurse) { Write-Verbose "Searching recursively" $dirParams.Add("Recurse",$True) } #define the file properties to display, including some custom ones $fileProperties = "LastWriteTime", "CreationTime", @{Name="Size";Expression={$_.length}}, @{Name="Lines";Expression={(Get-Content $_.Fullname | Measure-Object -line).Lines}}, "Directory", "Name", "FullName" #get all the matching files $files = Get-ChildItem @dirParams if ($files) { Write-Verbose "Found $($files.count) matching files" #sort, select properties and display in Out-Gridview $files | Sort-Object -Property LastWriteTime -Descending | Select-Object -First $newest -Property $fileProperties | Out-Gridview -Title $Title -PassThru | foreach { #open each selected file in the ISE Write-Verbose "Opening $($_.fullname)" psedit $_.fullname } #foreach } #if $files else { Write-Warning "Failed to find any matching files in $path" } Write-Verbose "Finished!" } #close function
The core commands in this function are very similar to my other script. And I probably could get by with one script so consider Open-LastScript as a variation on a theme. The function gets PowerShell related files from my Scripts directory. I could have hard coded a default value, but instead I set it to a global variable called ScriptPath which I define in my PowerShell ISE profile script. If that variable isn't defined, or if nothing is specified for –Path, then the function uses the current location, assuming it is a FileSystem path.
But the fun part, at least for me, is that I take the results of the DIR command and create a few custom properties, including one that shows the number of lines in the script file.
$fileProperties = "LastWriteTime", "CreationTime", @{Name="Size";Expression={$_.length}}, @{Name="Lines";Expression={(Get-Content $_.Fullname | Measure-Object -line).Lines}}, "Directory", "Name", "FullName"
The selected objects and properties are then piped to Out-Gridview. Starting in PowerShell 3.0 you can pass objects back to the pipeline from Out-Gridview. In other words, you can use Out-Gridview as a simple object picker. The function by default gets the 10 most recently modified scripts.
I can select as many entries as I want and click OK. Each selected script will then be opened in the ISE. Yes, I know I can see similar information in the most recently used list but that can show files outside of my Scripts folder and I'm limited to maximum MRU count. My function lets me specify the number of files to list.
The bottom line is that my Open-LastScript function is a handy tool that saves me a little bit of time finding the files I need to work on and every little bit helps. I could create an Add-Ons menu shortcut to run the function with the defaults, but for some reason I opted for an alias.
Set-Alias -Name ols -Value Open-LastScript
The alias gives me a little bit of flexibility.
I hope this gives you some ideas of how you can use PowerShell to make your scripting more efficient, or at the very least as an example of PowerShell scripting techniques.