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

96 lines
2.9 KiB
PowerShell
Raw Normal View History

#!/bin/pwsh
$null = New-Module {
function Add-PowerShellProfileStatement() {
param (
[Parameter(ParameterSetName="Global", Mandatory)]
[switch]$System,
[Parameter(ParameterSetName="DefaultUser", Mandatory)]
[switch]$DefaultUser,
[Parameter(ParameterSetName="Home")]
[string]$HomeDir = "~",
[Parameter(ParameterSetName="Global", Mandatory)]
[Parameter(ParameterSetName="DefaultUser")]
[Parameter(ParameterSetName="Home")]
[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]] $profiles = @();
if ($System) {
$configRoot;
if ($IsWindows) {
$configRoot = "$env:ProgramData";
} else {
$configRoot = "/etc";
}
2024-03-20 23:00:33 +00:00
$profiles = @("$configRoot/powershell/.");
} else {
[System.Collections.Generic.List[string]] $shells = @();
if ($DefaultUser) {
if ($IsWindows) {
$HomeDir = "C:/Users/Default";
} else {
$HomeDir = "/etc/skel"
}
}
if (Get-Command pwsh -ErrorAction SilentlyContinue) {
$shells.Add("pwsh");
}
if (Get-Command powershell -ErrorAction SilentlyContinue) {
$shells.Add("powershell");
}
foreach ($shell in $shells) {
$path = & $shell -NoProfile -c '$PROFILE';
$profiles.Add($path);
}
Push-Location ~;
2024-03-20 23:10:54 +00:00
$profiles = $profiles |
ForEach-Object { [System.IO.Path]::GetRelativePath($(Get-Location), $_); } |
ForEach-Object { "$HomeDir/$_" };
}
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 $_) "conf.d" "$Category.ps1"; };
}
2024-03-20 23:10:54 +00:00
$profiles | ForEach-Object {
2024-03-21 03:30:07 +00:00
$dirName = Split-Path -Parent $_;
2024-03-20 23:10:54 +00:00
if (-not (Test-Path -PathType Container $dirName)) {
$null = New-Item -ItemType Directory -Force $dirName;
}
2024-03-21 03:30:07 +00:00
if ((Test-Path -PathType Leaf $_) -and (-not $Overwrite)) {
Add-Content -Force "$_" "`n$Statement";
2024-03-20 23:10:54 +00:00
} else {
2024-03-21 03:30:07 +00:00
Set-Content -Force "$_" "$Statement";
2024-03-20 23:10:54 +00:00
}
};
Pop-Location;
}
function Get-ScriptInitializer() {
param (
[Parameter(Position=0, Mandatory=$true)]
$Initializer
)
return ". ([scriptblock]::Create(($Initializer) -join `"``n`"))";
}
}