PowerShell_Scripts/Edit-MyScript.ps1

84 lines
2.4 KiB
PowerShell

[CmdletBinding(SupportsShouldProcess)]param(
[ArgumentCompleter({ param (
$commandName,
$parameterName,
$wordToComplete,
$commandAst,
$fakeBoundParameters
)
[FunctionName]::_GetValidValues($wordToComplete,$true)
})]
[string[]]$ImportFunction,
[ArgumentCompleter({ param (
$commandName,
$parameterName,
$wordToComplete,
$commandAst,
$fakeBoundParameters
)
[SystemName]::_GetValidValues($wordToComplete,$false,$true)
})]
[string]$System,
[switch]$ForceImport,
[Parameter(Position = 0, ValueFromRemainingArguments = $true)]
[ArgumentCompleter({ param (
$commandName,
$parameterName,
$wordToComplete,
$commandAst,
$fakeBoundParameters
)
$local:possibleValues = [MyScript]::_GetValidValues($wordToComplete,$true)
if( $fakeBoundParameters.ContainsKey("System") ) {
$possibleValues = $possibleValues | Where-Object { $_ -match "^sys\.$($fakeBoundParameters.System)" } | ForEach-Object { $_ -replace "^sys\.$($fakeBoundParameters.System).",'' }
}
$possibleValues
})]
[string[]]$ScriptName
)
$local:EditRootPath=$MyPSScriptRoot
if( $System ) {
$EditRootPath = Join-Path $EditRootPath "sys.$System"
}
$local:ScriptPaths = @()
foreach( $local:p in $ImportFunction ) {
$local:f = Get-Command $p -Type Function
if( $f ) {
$local:sp = Join-Path $EditRootPath "$p`.ps1"
if( $ForceImport -or -not (Test-Path $sp) ) {
Export-FunctionSource $p -NoHeader > $sp
} elseif ( -not $ForceImport ) {
throw "$p already exists in Script, to import the function again, use the -Force"
}
$ScriptPaths += $sp
}
}
foreach( $local:p in $ScriptName ) {
$local:sp = Join-Path $EditRootPath "$p`.ps1"
$ScriptPaths += $sp
}
if( -not $ScriptPaths ) {
$ScriptPaths += $EditRootPath
}
foreach( $local:p in $ScriptPaths ) {
$local:parentPath = Split-Path -Parent $p;
if( -not (Test-Path $p) -and -not (Test-Path $parentPath) ) {
Write-Verbose "Creating missing path $parentPath..."
New-Item -Type Directory $parentPath
}
}
$local:sw = [System.Diagnostics.Stopwatch]::StartNew();
Edit-TextFile $ScriptPaths
$sw.Stop();
if( $sw.Elapsed.TotalSeconds -lt 1 ) {
$null = Read-Host "Waiting before refreshing. Press <Enter> when you're done editing ( don't forget to save ;) )..."
}
Get-Command Reload-MyScripts -ErrorAction SilentlyContinue |
ForEach-Object { . $_.Definition }