PowerShell_Scripts/base/Edit-TextFile.ps1

57 lines
1.8 KiB
PowerShell

[CmdletBinding(SupportsShouldProcess)]param(
[switch]$sudo,
[Parameter(Position = 0, ValueFromPipelineByPropertyName, ValueFromPipeline, ValueFromRemainingArguments = $true)]
[string[]]$Path,
[string[]]$PreferredEditors
)
begin {
$global:WaitForEditor = (($WaitForEditor, -1 -ne $null)[0], 5 -ne -1)[0]
$PathForEditor = @()
}
process {
foreach ( $local:P in $Path ) {
$PathForEditor += $P | Get-Path -Expand
}
}
end {
$local:editors = $PreferredEditors + @(
$env:EDITOR, 'nvim', 'vim', 'vi', 'codium', 'code', 'notepad'
) | Where-Object { $_ }
$local:editor = $null
foreach ( $local:testEditor in $editors ) {
if ( $(try { Get-Command -ListImported -Type Application $testEditor -ErrorAction SilentlyContinue }catch {}) ) {
$editor = "`"$testEditor`""
break;
}
}
if ( $editor -match 'vim"$' ) {
$editor += ' -p'
}
if ( $EditorProcessName ) {
if ( -not (Get-Process -Name $EditorProcessName -ErrorAction SilentlyContinue) ) {
Invoke-ExpressionEx -sudo:$sudo "& $editor"
while ( -not (Get-Process -Name $EditorProcessName -ErrorAction SilentlyContinue) ) {
Start-Sleep -Seconds 1
}
Write-Host -ForegroundColor DarkCyan "Please wait, initializing editor..."
Start-Sleep -Seconds $WaitForEditor
if ( Test-Path variable:EditorWaitStopWatch ) {
$EditorWaitStopWatch.Restart()
}
}
}
Write-Verbose $($Path | Out-String)
$local:arguments = $PathForEditor | Foreach-Object { "'$_'" }
if ( $Path ) { $arguments = "$arguments" }
if ( $PSCmdlet.ShouldProcess( "Edit ($editor): $arguments" ) ) {
Invoke-ExpressionEx -sudo:$sudo "& $editor $arguments"
}
}