PoshCode Logo PowerShell Code Repository

New-Script by Joel Bennett 4 years ago
View followups from Joel Bennett | embed code: <script type="text/javascript" src="http://PoshCode.org/embed/167"></script>download | new post

Create a new script from a series of commands in your history… or copy them to the clipboard.

  1. ## New-Script function
  2. ## Creates a new script from the most recent commands in history
  3. ##################################################################################################
  4. ## Example Usage:
  5. ##    New-Script ScriptName 4
  6. ##        creates a script from the most recent four commands
  7. ##    New-Script ScriptName -id 10,11,12,14
  8. ##        creates a script from the specified commands in history
  9. ##    New-Script Clipboard 2
  10. ##        sends the most recent two commands to the clipboard
  11. ##################################################################################################
  12. ## As a tip, I use a prompt function something like this to get the ID into the prompt:
  13. ##
  14. ## function prompt {
  15. ##   return "`[{0}]: " -f ((get-history -count 1).Id + 1)
  16. ## }
  17. ##################################################################################################
  18.  
  19. #function New-Script {
  20. param(
  21.    [string]$script=(Read-Host "A name for your script"),
  22.    [int]$count=1,
  23.    [int]$id=((Get-History -count 1| Select Id).Id)
  24. )
  25.  
  26. if($script -eq "clipboard") {
  27.    if( @(Get-PSSnapin -Name "pscx").Count ) {
  28.       Get-History -count $count -id $id | &{process{ $_.CommandLine }} | out-clipboard
  29.    }elseif(@(gcm clip.exe).Count) {
  30.       Get-History -count $count -id $id | &{process{ $_.CommandLine }} | clip
  31.    }
  32. } else {
  33.    # default to putting it in my "Windows PowerShell\scripts" folder which I have in my path...
  34.    $folder = Split-Path $script
  35.    if(!$folder) {
  36.       $folder = Join-Path (Split-Path $Profile) "Scripts"
  37.    }
  38.    if(!(Test-Path $folder)) {
  39.       Throw (new-object System.IO.DirectoryNotFoundException "Cannot find path '$folder' because it does not exist.")
  40.    }
  41.    # add the ps1 extension if it's not already there ...
  42.    $file = Join-Path $folder (Split-Path $script -leaf)
  43.    if(!(([IO.FileInfo]$file).Extension)) {
  44.       $file = "$file.ps1"
  45.    }
  46.  
  47.    Get-History -count $count -id $id | &{process{ $_.CommandLine }} | set-content $file
  48. }
  49. #}

Submit a correction or amendment below (
click here to make a fresh posting)
After submitting an amendment, you'll be able to view the differences between the old and new posts easily.

Syntax highlighting:


Remember me