Const.ps1
|
<#PSScriptInfo .VERSION 1.0.0 .GUID 00de1149-8e9b-481b-9e8c-dc3e933fb5d1 .AUTHOR BaldCat .COPYRIGHT (c) 2026 BaldCat. All rights reserved. .TAGS Constant Const .LICENSEURI https://github.com/baldcat18/PSConst/blob/main/LICENSE .PROJECTURI https://github.com/baldcat18/PSConst #> <# .SYNOPSIS Create a constant. .DESCRIPTION Create a constant. The constant cannot be deleted or changed. .PARAMETER Name Specifies a name for the new constant. .PARAMETER Value Specifies the value of the constant. .PARAMETER Description Specifies a description of the constant. .PARAMETER Global Indicates that the script creates a constant in the global scope are accessible everywhere in a PowerShell process. .PARAMETER Private Indicates that the script creates a constant is available only in the current scope. .PARAMETER Force Indicates that the script creates a constant with the same name as an existing variable. .PARAMETER PassThru Returns an object representing the created constant. By default, this script does not generate any output. .OUTPUTS NONE By default, this script returns no output. PSVariable When you use the PassThru parameter, this cmdlet returns a PSVariable object representing the new constant. .EXAMPLE PS > Const.ps1 name 'Bill' PS > $name Bill PS > $name = 'Steve' Cannot overwrite variable name because it is read-only or constant. PS > Remove-Variable name Remove-Variable : Cannot remove variable name because it is constant or read-only. #> [CmdletBinding(SupportsShouldProcess)] [OutputType([psvariable])] param( [Parameter(Mandatory, Position = 0)][ValidateNotNullOrEmpty()] [string]$Name, [Parameter(Position = 1)] $Value, [string]$Description, [switch]$Global, [switch]$Private, [switch]$Force, [switch]$PassThru ) # スクリプトに渡した引数が壊れないようコピーする $nvArgs = [hashtable]$PSBoundParameters $nvArgs['Option'] = 'Constant' if ($Private) { $nvArgs.Remove('Private') $nvArgs['Option'] += ', Private' } $nvArgs['Scope'] = 1 if ($Global) { $nvArgs.Remove('Global') $nvArgs['Scope'] = 'Global' } # $PSCmdlet.ShouldProcess()とNew-Variable自身で2回確認プロンプトが出るのを防ぐ $nvArgs['Confirm'] = $false $nvArgs['WhatIf'] = $false # エラー処理をやりやすくするため一旦終了するエラーにする if ($ErrorActionPreference -eq 'Continue') { $nvArgs['ErrorAction'] = 'Stop' } try { if ($PSCmdlet.ShouldProcess("Name: $Name Value: $Value", 'New constant')) { return New-Variable @nvArgs } } catch { if ($ErrorActionPreference -eq 'Stop') { $PSCmdlet.ThrowTerminatingError($Error[0]) } else { $PSCmdlet.WriteError($Error[0]) } } |