Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
function New-LocalUserAccount {
[CmdletBinding()]
param (
[Parameter(
ValueFromPipeline = $true,
ValueFromPipelineByPropertyName = $true
)]
[string] $Computer = $env:COMPUTERNAME,
[Parameter(Mandatory = $true)]
[string] $Name,
[Parameter(Mandatory = $true)]
[string] $DisplayName,
[Parameter(Mandatory = $true)]
[string] $Password
)
[ADSI] $host = [string]::Format("WinNT://{0}", $Computer)
if (![string]::IsNullOrEmpty($Name)) {
$user = $host.Create("User", $Name)
if ($user -ne $null) {
$user.SetPassword($password);
$user.SetInfo()
}
}
}
function New-RandomPassword {
[CmdletBinding()]
param (
[Parameter(Mandatory = $false)]
[int] $Length = 12,
[Parameter(Mandatory = $false)]
[string] $RegEx = '[\w\$\%\&\/\(\)\=\?\!\\,\.\-_\:;\]\+\*\~<>\|]'
)
[string] $password = -join ( [char[]](0..127) -match $RegEx | Get-Random -Count $length )
return $password
}
function Remove-AdmPwdExpirationTime {
$Searcher = New-Object DirectoryServices.DirectorySearcher
$Searcher.Filter = '(&(sAMAccountName=' + $env:ComputerName + '$))'
$computerObject = New-Object DirectoryServices.DirectoryEntry ($Searcher.FindAll()).Path
if ($computerObject.servicePrincipalName -match ($env:ComputerName + '.' + (Get-ItemProperty -path 'HKLM:\\SYSTEM\CurrentControlSet\Services\Tcpip\Parameters' -Name 'Domain').Domain)) {
if ($computerObject.'ms-Mcs-AdmPwdExpirationTime') {
$computerObject.'ms-Mcs-AdmPwdExpirationTime'.Remove($($computerObject.'ms-Mcs-AdmPwdExpirationTime'))
$computerObject.setInfo()
}
}
}
$AdminAccountName = (Get-ItemProperty -Path 'HKLM:\SOFTWARE\Policies\Microsoft Services\AdmPwd' -Name 'AdminAccountName' -ErrorAction SilentlyContinue).AdminAccountName
If (($AdminAccountName) -and ((Get-ItemProperty -Path 'HKLM:\SOFTWARE\Policies\Microsoft Services\AdmPwd' -Name 'AdmPwdEnabled' -ErrorAction SilentlyContinue).AdmPwdEnabled) -eq '1' -and (Get-Item -Path ($env:ProgramFiles + '\LAPS\CSE\AdmPwd.dll') -ErrorAction SilentlyContinue)) {
New-LocalUserAccount -Name $AdminAccountName -DisplayName $AdminAccountName -Password (New-RandomPassword -Length 24)
Remove-AdmPwdExpirationTime
Start-Process -FilePath ($env:windir + '\system32\gpupdate.exe') -ArgumentList '/force'
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment