PowerShell_Scripts/Reload-MyScripts.ps1

89 lignes
2.9 KiB
PowerShell

[CmdletBinding(SupportsShouldProcess)]param()
try { Get-Alias Get-MyAliases -ErrorAction Stop | ForEach-Object { Remove-Item "Alias:$($_.Name)" } } catch {}
function Get-MyAliases {
[CmdletBinding(SupportsShouldProcess)]param([switch]$ScriptsOnly)
$local:allAliases = @()
$MyAliasScope = 0
$local:_scope = 0
$local:_done = $false
do {
try {
$local:newAliases += Get-Alias -Scope $_scope |
Where-Object {
($_.Definition -match "^$MyPSScriptRoot") -or (-not $ScriptsOnly -and ($_.Description -match '#MyAlias'))
}
if( $newAliases ) {
$allAliases += $newAliases
$MyAliasScope = $_scope;
Write-Verbose "`$MyAliasScope is now set to $MyAliasScope"
}
} catch {
Write-Verbose "catch: $($_.Exception.Message)"
$_done = $_.Exception.Message -match 'The scope .* exceeds'
}
$_scope += 1
} until ( $_done )
$allAliases
}
function getScriptName{param([string]$FullPath)
$FullPath -replace '\.ps1$','' -replace "^$([regex]::Escape($MyPSScriptRoot)).",''
}
$local:myAliases = [ordered]@{}
if( Test-Path $(Join-Path $MyPSScriptRoot Aliases) ) {
Get-ChildItem $(Join-Path $MyPSScriptRoot Aliases) | ForEach-Object {
$myAliases[$_.BaseName] = Get-Content $_.FullName
}
}
$local:IsVerbose = [bool]($PSBoundParameters['Verbose'])
$script:MyAliasScope = 0
$local:oldAliases = Get-MyAliases
$oldAliases = Get-Alias -Scope $MyAliasScope |
Where-Object Name -in $($oldAliases.Name + $myAliases.Keys)
if( $oldAliases -and $IsVerbose ) {
Write-Verbose "Removing: $($oldAliases.Name -join ', ')"
}
if( Get-Command Remove-Alias -ErrorAction SilentlyContinue ) {
$oldAliases | Remove-Alias -Scope $MyAliasScope
} else {
$oldAliases | ForEach-Object { Remove-Item "Alias:$($_.Name)" }
}
if( $(. Get-ScopeDepth) -gt 0 ) { Write-Host -ForegroundColor Red "Try sourcing Reload-MyScripts instead of just running it" }
Get-ChildItem $(Join-Path $MyPSScriptRoot profile.d) -Filter '*.ps1' | ForEach-Object {
Write-Verbose "Loading $(getScriptName $_.FullName)...";
". '$($_.FullName)';"
} | Invoke-Expression
$local:CommandsToAlias = (
@( $MyPSScriptRoot ) + $(
[SystemName]::_GetValidValues("",$true,$true) | ForEach-Object {
Join-Path $MyPSScriptRoot "sys.$_"
}
)) | ForEach-Object {
if( Test-Path $_ ) {
Get-ChildItem (Join-Path $_ '*.ps1') | Where-Object Name -notmatch '\.inc\.ps1$'
}
}
$CommandsToAlias | ForEach-Object {
Write-Verbose "Creating alias for $(getScriptName $_.FullName) Script..."
Set-Alias $($_.BaseName) $_.FullName -Scope $MyAliasScope
}
foreach( $local:alias in $myAliases.Keys ) {
Write-Verbose "Adding $($alias) alias..."
Set-Alias -Name $alias -Value $myAliases[$alias] -Description '#MyAlias' -Scope $MyAliasScope
}