Skip to content

Instantly share code, notes, and snippets.

@Locoxella
Created January 29, 2025 22:33
Show Gist options
  • Save Locoxella/4847dd327e0e48163fe5f4bd10c843ea to your computer and use it in GitHub Desktop.
Save Locoxella/4847dd327e0e48163fe5f4bd10c843ea to your computer and use it in GitHub Desktop.
Param(
[Parameter(Mandatory=$true)]
[string]$Username,
[int]$ExpirationDays = 1,
[bool]$Override = $false
)
if (Get-LocalUser -Name \$Username -ErrorAction SilentlyContinue) {
\$existingUser = Get-LocalUser -Name \$Username
if (-not $existingUser.Enabled -or $Override) {
Write-Host "User exists and is either disabled or override is enabled - recreating..."
Remove-LocalUser -Name $Username -Confirm:$false
Get-CimInstance Win32_UserProfile | Where-Object { $_.LocalPath -like "*\$Username" } | Remove-CimInstance
}
else {
Write-Error \"User '\$Username' exists and is enabled. Use -Override \$true to recreate\"
exit 1
}
}
# Generate password
Add-Type -AssemblyName System.Web
do {
\$password = [System.Web.Security.Membership]::GeneratePassword(12, 3)
} until (\$password -match '[a-z]' -and \$password -match '[A-Z]' -and \$password -match '\d' -and \$password -match '[\\W_]')
# Create user
New-LocalUser -Name \$Username -Password (ConvertTo-SecureString \$password -AsPlainText -Force) -AccountNeverExpires
Add-LocalGroupMember -Group \"Remote Desktop Users\" -Member \$Username
# Set expiration
net user \$Username /expires:((Get-Date).AddDays(\$ExpirationDays).ToString('MM/dd/yyyy')) | Out-Null
Write-Host \"Created user: \$Username\"
Write-Host \"Password: \$password\"
Write-Host \"Expiration: \$((Get-Date).AddDays(\$ExpirationDays))\""
--parameters "[
{
'name': 'Username',
'value': '$(Username)'
},
{
'name': 'ExpirationDays',
'value': '1'
},
{
'name': 'Override',
'value': 'false'
}
]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment