PortValhalla/scripts/Common/Config/powershell/lib.ps1

66 lines
1.9 KiB
PowerShell
Raw Normal View History

#!/bin/pwsh
$null = New-Module {
function Add-PowerShellProfileStatement() {
param (
[string]$HomeDir = "~",
[string]$Category = $null,
[Parameter(Position=0, Mandatory=$true)]
[string]$Statement,
2024-03-20 21:56:04 +00:00
[switch]$Overwrite
)
[System.Collections.Generic.List[string]] $shells = @();
[System.Collections.Generic.List[string]] $profiles = @();
2024-03-20 15:55:19 +00:00
if (Get-Command pwsh -ErrorAction SilentlyContinue) {
$shells.Add("pwsh");
}
2024-03-20 15:55:19 +00:00
if (Get-Command powershell -ErrorAction SilentlyContinue) {
$shells.Add("powershell");
}
foreach ($shell in $shells) {
$path = & $shell -NoProfile -c '$PROFILE';
$profiles.Add($path);
}
Push-Location ~;
$profiles = $profiles | ForEach-Object { [System.IO.Path]::GetRelativePath($(Get-Location), $_); };
if ($Category) {
2024-03-20 21:56:04 +00:00
if (-not $($Overwrite.IsPresent)) {
$Overwrite = $true;
}
$profiles = $profiles | ForEach-Object { Join-Path (Split-Path -Parent $_) "profile.d" "$Category.ps1"; };
}
$profiles | ForEach-Object {
$fileName = "$HomeDir/$_";
$dirName = Split-Path -Parent $fileName;
if (-not (Test-Path -PathType Container $dirName)) {
$null = New-Item -ItemType Directory -Force $dirName;
}
if ((Test-Path -PathType Leaf $fileName) -and (-not $Overwrite)) {
Add-Content -Force "$fileName" "`n$Statement";
} else {
Set-Content -Force "$fileName" "$Statement";
}
};
Pop-Location;
}
function Get-ScriptInitializer() {
param (
[Parameter(Position=0, Mandatory=$true)]
$Initializer
)
return ". ([scriptblock]::Create(($Initializer) -join `"``n`"))";
}
}