Save script as records in Powershell ISE

Introduction

This article talks about how to save your work in a most easier way and also to keep your activity safe as a record.

Details

First, you should modify your profile, using the following command

PS:\>psedit $profile

and add following functions

i) save your current file :

function Save-ISEScript {
  param(
   
  [Parameter(Mandatory=$True,Position=1)]
  [string]$nume,
  $path='Your Powershell scripts path'
    )
    $nume_complet = Join-Path  $path "$nume.ps1"
    $psise.CurrentFile.SaveAs($nume_complet, [System.Text.Encoding]::UTF8)
    }

Set your $path variable with your own path.To use the function, you will use

ps:\>save-isescript <yourfilename>

ii) save ( backup ) current file as a record in separate place

In a folder specified by you in $path variable, and a subfolder as your file name. The name will contain also the timestamp. Finally, it will set the record as Read-Only

function Save-AsRecord {
  param(
  $path='Your Powershell scripts path\records\'
    )
 
    $nume_record = $path+(($psise.CurrentFile.DisplayName).Split('.'))[0]+'\'+(($psise.CurrentFile.DisplayName).Split('.'))[0]+'-'+(get-date -Format 'yyyymmddHHmmss').tostring()+'.ps1'
    $nume_sursa = $psise.CurrentFile.FullPath
 
    $folder_complet =$path+(($psise.CurrentFile.DisplayName).Split('.'))[0]
            if(!(Test-Path -Path $folder_complet)){
                New-Item -ItemType directory -Path $folder_complet
            }
 
    copy $nume_sursa $nume_record
    (get-item $nume_record).Attributes =  "Archive","ReadOnly"
    Write-Host "A fost salvat ca record fisierul '$nume_record'" -ForegroundColor green -BackgroundColor gray
    }

To save the file as record, use:

Save-AsRecord

After you've modified your profile, restart your ISE session to use the functions.