PortValhalla/scripts/Windows/Scripts/Users.ps1

111 lines
4.2 KiB
PowerShell
Raw Normal View History

2024-08-08 15:49:43 +00:00
using namespace System.Management.Automation.Host;
$null = New-Module {
. "$PSScriptRoot/../../Common/Scripts/Config.ps1";
[string] $userOption = "SetupUser";
<#
.SYNOPSIS
Creates the configured users.
#>
function Start-ValhallaUserSetup {
[int] $current = Get-SetupOption $userOption;
[string[]] $users = Get-Users;
function Add-MicrosoftAccount {
param(
[string] $Name
)
$newUser = & {
while ($true) {
$currentUsers = Get-LocalUser | ForEach-Object { $_.Name };
Write-Host (
@(
"So… Windows is too dumb to create users which are bound to a Microsoft Account.",
"Thus, you have to do it by yourself.",
"So sorry…") -join "`n");
Write-Host "Create a user for ``$Name`` manually (because Windows is too stupid)…";
2024-08-09 00:20:27 +00:00
$null = Read-Host "Hit enter once you're done";
2024-08-08 15:49:43 +00:00
$newUsers = @(Get-LocalUser | Where-Object { -not ($currentUsers -contains $_.Name) });
if ($newUsers.Count) {
if ($newUsers.Count -eq 1) {
$newUser = $newUsers[0];
Write-Host "Found new user ``$newUser``";
if (
$Host.UI.PromptForChoice(
"Confirm",
"Is ``$newUser`` your user?",
[ChoiceDescription[]]@(
[ChoiceDescription]::new("&No", "``$newUser`` is not your user"),
[ChoiceDescription]::new("&Yes", "``$newUser`` is your user")),
0) -eq 1) {
return $newUser;
}
} else {
$result = $Host.UI.PromptForChoice(
"Select your User",
"Which one is your user?",
[ChoiceDescription[]](
& {
[ChoiceDescription]::new("&None", "None of these users is yours");
for ($i = 0; $i -lt $newUsers.Count; $i++) {
$name = "$($newUsers[$i])";
[ChoiceDescription]::new("&$($i + 1) - ``$name``", "Your user is ``$name``");
}
}), 0);
if ($result -gt 0) {
return $newUsers[$result - 1];
}
}
2024-08-09 00:00:18 +00:00
} else {
Write-Host "";
2024-08-08 15:49:43 +00:00
Write-Host "Unable to determine the new user";
Write-Host "Retrying…";
}
}
};
Write-Host "Renaming the new user to ``$Name``";
Rename-LocalUser $newUser $Name;
}
for ($i = $current ?? 0; $i -lt $users.Count; $i++) {
Set-SetupOption $userOption $i;
$name = $users[$i];
Write-Host "Creating personal user ``$name``";
if (Get-UserConfig -UserName $name "microsoftAccount") {
Add-MicrosoftAccount $name;
} else {
$displayName = Get-UserConfig -UserName $name "displayName";
$userArguments = @{
name = $name;
};
if ($displayName) {
$userArguments.fullName = $displayName;
}
2024-08-09 00:58:01 +00:00
New-LocalUser -Disabled -NoPassword @userArguments;
2024-08-08 15:49:43 +00:00
Set-LocalUser $name -PasswordNeverExpires $true;
Set-LocalUser $name -PasswordNeverExpires $false;
}
if (-not (Get-UserConfig -UserName $name "microsoftAccount")) {
net user $name /logonpasswordchg:yes;
}
}
}
};