PowerShell_Scripts/base/Edit-TextFile.ps1

36 lines
981 B
PowerShell

[CmdletBinding(SupportsShouldProcess)]param(
[switch]$sudo,
[Parameter(Position = 0, ValueFromRemainingArguments = $true)]
[string[]]$Path
)
$local:editors = $env:EDITOR,'nvim','code'
$local:editor = $null
foreach( $local:testEditor in $editors ) {
if( $(try{Get-Command -Type Application $testEditor -ErrorAction SilentlyContinue}catch{}) ) {
$editor = $testEditor
break;
}
}
if( $editor -match 'vim?$' ) {
$editor += ' -p'
}
if( $editor -match 'code(\.exe)?$' ) {
if( -not (Get-Process -Name 'code' -ErrorAction SilentlyContinue) ) {
Invoke-ExpressionEx -sudo:$sudo $editor
}
}
$local:arguments = $($Path | ForEach-Object {
if ($Path -match '\*|\?|~') {
Get-ChildItem -Path $_ | Select-Object -ExpandProperty FullName
} else { $_ }
} ) -join "' '"
if( $Path ) { $arguments = "'$arguments'" }
if( $PSCmdlet.ShouldProcess( "Edit ($editor): $arguments" ) ) {
Invoke-ExpressionEx -sudo:$sudo $editor "$arguments"
}