Refactor user creation script

This commit is contained in:
Manuel Thalmann 2024-03-23 15:47:31 +01:00
parent 0246633c68
commit 04c6ef125f

View file

@ -9,6 +9,9 @@ $uacDisablerTriggerProperty = "UACDisablerTrigger";
function New-PersonalUser([Context] $context, [string] $userName)
{
$userStageProperty = "UserStage";
$creationStage = "Create";
$disableUACStage = "DisableUAC";
$adminRemovalStage = "RemoveAdmin";
$null = New-Module {
Get-UserStage {
@ -21,9 +24,12 @@ function New-PersonalUser([Context] $context, [string] $userName)
}
}
if (-not (Get-LocalUser $userName -ErrorAction SilentlyContinue))
{
Write-Host "Creating Personal User";
switch (Get-UserStage) {
{ $_ -in $null,$creationStage } {
Set-UserStage $creationStage;
if (-not (Get-LocalUser $userName -ErrorAction SilentlyContinue)) {
Write-Host "Creating Personal User ``$userName``";
while ($true) {
Write-Host (
@ -49,7 +55,10 @@ function New-PersonalUser([Context] $context, [string] $userName)
Write-Information "Renaming the new User to $userName";
Rename-LocalUser $user $userName;
Add-LocalGroupMember -Group "Administrators" -Member $user && Set-LocalUser $context.AdminName -Password (ConvertTo-SecureString -AsPlainText "Admin") && Disable-LocalUser $context.AdminName;
Add-LocalGroupMember -Group "Administrators" -Member $user &&
Set-LocalUser $context.AdminName -Password (ConvertTo-SecureString -AsPlainText "Admin") &&
Disable-LocalUser $context.AdminName;
Write-Host "Registering setup script for all new users";
$context.RegisterNewUserReboot();
@ -59,23 +68,23 @@ function New-PersonalUser([Context] $context, [string] $userName)
Write-Information "Disabling Auto login";
$context.RemoveAutologin();
Set-UserStage "DisableUAC";
Set-UserStage $disableUACStage;
Restart-Computer -Force;
exit;
}
switch (Get-UserStage) {
"DisableUAC" {
}
$disableUACStage {
Enable-PersonalUserAutologon $context $userName;
$context.RegisterReboot();
Set-UserStage "RemoveAdmin";
Set-UserStage $adminRemovalStage;
Start-EventDrivenTask $context.Get($uacDisablerTriggerProperty);
exit;
}
"RemoveAdmin" {
$adminRemovalStage {
Write-Information "Removing Admin Account";
Get-CimInstance -ClassName "Win32_UserProfile" -Filter "SID = '$((Get-LocalUser $context.AdminName).SID)'" | Remove-CimInstance;
$context.Remove($userStageProperty);
break;
}
}
}