PowerShell_Scripts/base/Edit-TextFile.ps1

44 lines
1.1 KiB
PowerShell
Raw Normal View History

2020-09-29 20:50:19 +00:00
[CmdletBinding(SupportsShouldProcess)]param(
[switch]$sudo,
[Parameter(Position = 0, ValueFromPipelineByPropertyName, ValueFromPipeline, ValueFromRemainingArguments = $true)]
2020-09-29 20:50:19 +00:00
[string[]]$Path
)
begin {
$PathForEditor = @()
2020-09-29 20:50:19 +00:00
}
process {
foreach( $local:P in $Path ) {
$PathForEditor += $P | Get-Path -Expand
}
}
end {
$local:editors = $env:EDITOR,'nvim','code'
$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( $editor -match 'code(\.exe)?$' ) {
if( -not (Get-Process -Name 'code' -ErrorAction SilentlyContinue) ) {
Invoke-ExpressionEx -sudo:$sudo $editor
}
}
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"
}
}