PowerShell_Scripts/base/Edit-MyScript.ps1

95 lines
2.8 KiB
PowerShell
Raw Normal View History

[CmdletBinding(SupportsShouldProcess)]param(
[ArgumentCompleter({ param (
$commandName,
$parameterName,
$wordToComplete,
$commandAst,
$fakeBoundParameters
)
[FunctionName]::_GetValidValues($wordToComplete,$true)
})]
[string[]]$ImportFunction,
[ArgumentCompleter({ param (
$commandName,
$parameterName,
$wordToComplete,
$commandAst,
$fakeBoundParameters
)
$local:NotAll = $true
if( $fakeBoundParameters.ContainsKey("All") ) { $NotAll = -not $fakeBoundParameters.All }
[Packagesz]::_GetValidValues($wordToComplete,$NotAll,$true)
})]
[string]$Package,
[switch]$ForceImport,
[switch]$All,
[Parameter(Position = 0, ValueFromRemainingArguments = $true)]
[ArgumentCompleter({ param (
$commandName,
$parameterName,
$wordToComplete,
$commandAst,
$fakeBoundParameters
)
$local:NotAll = $true
$local:Pkg = [string]::Empty
if( $fakeBoundParameters.ContainsKey("All") ) { $NotAll = -not $fakeBoundParameters.All }
if( $fakeBoundParameters.ContainsKey("Package") ) { $Pkg = Join-Path $fakeBoundParameters.Package '' }
$local:possibleValues = [MyScript]::_GetValidValues($wordToComplete,$NotAll,$true)
if( $Pkg ) {
$possibleValues = $possibleValues |
Where-Object { $_ -match "^$Pkg" } |
ForEach-Object { $_.Replace($Pkg,'') }
}
$possibleValues
})]
[string[]]$ScriptName,
[switch]$WaitNotRequired = $env:WAIT_NOT_REQUIRED
)
$local:EditRootPath=$MyPSScriptRoot
if( $Package ) {
$EditRootPath = Join-Path $EditRootPath $Package
}
$local:ScriptPaths = @()
foreach( $local:p in $ImportFunction ) {
$local:f = Get-Command -ListImported $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 -ListImported Reload-MyScripts -ErrorAction SilentlyContinue |
ForEach-Object { . $_.Definition }