Public/New-PstScript.ps1
function New-PstScript { <# .SYNOPSIS Creates a new script file from a base template. .DESCRIPTION This function takes a name parameter, copies a script template, and saves it with the specified name. .PARAMETER Name (Required) The name for the new script file. .EXAMPLE New-PstScript -Name MyScript This example creates a new script file named MyScript.ps1 based on the template. .NOTES Ensure that the template file Script.ps1 exists in the same directory as this script. .LINK For more information on PowerShell scripting, visit: https://docs.microsoft.com/en-us/powershell/scripting/overview #> [CmdletBinding(SupportsShouldProcess)] param ( [Parameter(Mandatory = $true, Position = 0, HelpMessage = "The name for the new script file.")] [ValidatePattern('^[A-Za-z][A-Za-z0-9\-_]*$')] [string]$Name, [Parameter(Mandatory = $false)] [switch]$Force ) begin { Write-Debug -Message "Begin '$($MyInvocation.MyCommand.Name)' at '$(Get-Date)'" $templatePath = $Samples["Script.ps1"] $newFilePath = "$Name.ps1" if (-not (Test-Path $templatePath)) { throw "Template file not found: $templatePath" }else { Write-Verbose "Template file found: $templatePath" } } process { try { # Check if we're in automation mode - inline check to avoid scope issues $isAutomationMode = $Force -or ($Global:PstAutomationMode -eq $true) -or ($env:CI -eq 'true') -or ($env:GITHUB_ACTIONS -eq 'true') -or ($Host.Name -eq 'ServerRemoteHost') -or (-not [Environment]::UserInteractive) -or ($global:ConfirmPreference -eq 'None') # Check if file already exists if ((Test-Path $newFilePath) -and -not $isAutomationMode) { if (-not $PSCmdlet.ShouldProcess($newFilePath, "Overwrite existing script file")) { Write-Warning "Operation cancelled by user." return } } elseif ((Test-Path $newFilePath) -and $isAutomationMode -and -not $Force) { Write-Warning "File '$newFilePath' already exists. Use -Force to overwrite in automation mode." return } # Proceed with file creation - skip ShouldProcess in automation mode if ($isAutomationMode -or $PSCmdlet.ShouldProcess($newFilePath, "Create new script file")) { Write-Information -Message "Copy-Item -Path '$($templatePath)' -Destination '$(Join-Path (Get-Location) $newFilePath)'" Copy-Item -Path $templatePath -Destination $newFilePath Write-Output "New script file created: $newFilePath" } else { Write-Verbose "Operation cancelled or skipped." } } catch { if ($_.Exception -and $_.Exception.Message) { Write-Error "An error occurred: $($_.Exception.Message)" } else { Write-Error "An error occurred, but no additional information is available." } } } end { if ($?) { Write-Debug -Message "End '$($MyInvocation.MyCommand.Name)' at '$(Get-Date)'" } } } |