When I'm working on simple PowerShell scripts, I find myself using the PowerShell ISE. When I need to share those scripts on my blog I inevitably need to save the script as a text file so I can post it. I finally realized that instead of the few manual steps, I could automate this process.
ManageEngine ADManager Plus - Download Free Trial
Exclusive offer on ADManager Plus for US and UK regions. Claim now!
I wrote a simple function called ConvertTo-TextFile that will take the current PowerShell file and save it as a text file in the same location.
[cc lang="PowerShell"]
Function ConvertTo-TextFile {
Param (
[switch]$Reload
)
#verify we are in the ISE
if ($psise) {
#get the current file name and path and change the extension
$psVersion=$psise.CurrentFile.FullPath
$textVersion=$psversion -replace "ps1","txt"
#save the file.
$psise.CurrentFile.SaveAs($textVersion)
#if -Reload then reload the PowerShell file into the ISE
if ($Reload)
{
$psise.CurrentPowerShellTab.Files.Add($psVersion)
}
} #if $psise
else
{
Write-Warning "This function requires the Windows PowerShell ISE."
}
} #end function
[/cc]
Using the ISE object model, I can get the current file name and path. Using the -replace operator I chance the .ps1 extension to .txt. Of course if you have an odd filename like "My.ps1Script.ps1" you'll get less than ideal results but hopefully you're keeping it simple. Once I have the new filename it is a simple matter of invoking the SaveAs() method.
When this method is invoked, the original file is "gone" from the ISE. But perhaps you want to keep editing it. If so, you can use the -Reload parameter which will add the original version back into the ISE.
To fully leverage this function, I dot source the script file in my ISE profile script and then add a menu item to the Add-Ons menu.
[cc lang="PowerShell"]
. c:\scripts\ConvertTo-TextFile.ps1
$psISE.CurrentPowerShellTab.AddOnsMenu.Submenus.Add("Convert to text file",{ConvertTo-TextFile}, "ALT+T") | out-null
[/cc]
Now, whenever I want to save a text file version all I need to do is press Alt+T. You define your own combination. Or you might want to define an alias. My implementation does not use -Reload.
I hope you find this useful. Download ConvertTo-TextFile.ps1.