Public/mni.ps1
|
function mni { <# .SYNOPSIS Creates a file and optionally opens it in an editor. .DESCRIPTION Creates missing parent directories and the requested file. Existing files are preserved. If the editor command is unavailable, the file is still returned and a warning is emitted. .PARAMETER Path Path of the file to create. .PARAMETER EditorCommand Executable used to open the file. Defaults to code. .PARAMETER NoOpen Creates the file without launching an editor. .EXAMPLE mni -Path './src/example.ps1' -NoOpen #> [CmdletBinding(SupportsShouldProcess = $true)] [OutputType([System.IO.FileInfo])] param( [Parameter(Mandatory = $true)] [string]$Path, [string]$EditorCommand = 'code', [switch]$NoOpen ) $fullPath = Resolve-Path -LiteralPath $Path -ErrorAction SilentlyContinue if (-not $fullPath) { if ([System.IO.Path]::IsPathRooted($Path)) { $fullPath = [System.IO.Path]::GetFullPath($Path) } else { $fullPath = [System.IO.Path]::GetFullPath( (Join-Path -Path (Get-Location).Path -ChildPath $Path) ) } } else { $fullPath = $fullPath.Path } $action = if (Test-Path -LiteralPath $fullPath) { 'Open existing file' } else { 'Create file and optionally open it' } if (-not $PSCmdlet.ShouldProcess($fullPath, $action)) { return } $directory = Split-Path -Path $fullPath -Parent if (-not (Test-Path -LiteralPath $directory)) { New-Item -ItemType Directory -Path $directory -Force | Out-Null } if (-not (Test-Path -LiteralPath $fullPath)) { New-Item -ItemType File -Path $fullPath -Force | Out-Null } $file = Get-Item -LiteralPath $fullPath if (-not $NoOpen) { $editor = Get-Command -Name $EditorCommand -CommandType Application -ErrorAction SilentlyContinue if ($editor) { & $editor.Source $file.FullName } else { Write-Warning "File created, but editor command '$EditorCommand' was not found." } } return $file } |