I'm not very familiar with stackoverflow nor with Powershell. Sorry for formatting, please let me know how to improve my post for more visibility.
I've been trying to get an invisible powershell script who will check if the account exists before creating it. If the account doesn't exists, then the script would create a local administrator account part of administrator group with a secured password. The account would be forced to change password on next login.
I've already tried a couple of things, i'm having 2 separated scripts, one to create the secured password in a .txt file then i'm calling this file into the main script.
So far the script is not silent (invisible) and the password is not saved. The account is indeed created but when I enter the password it says I have an error. If I set the password in an unsecured way It would work and ask me to change it on next login.
Unfortunately, if the account already exists it doesn't quit the script, instead it changes the password.
Password creation:
Read-Host -Prompt "Saisir mot de passe " -AsSecureString | ConvertFrom-SecureString | Out-File C:\\script2\\init.pwd
Main script:
$Password = cat C:\script2\init.pwd | ConvertTo-SecureString
$group = "Administrators"
$adsi = [ADSI]"WinNT://$env:COMPUTERNAME"
$existing = $adsi.Children | where {$_.SchemaClassName -eq 'user' -and $_.Name -eq $Username }
if ($existing -eq $Username) {
exit
}
else {
NET USER $Username $Password /add /y /expires:never
NET LOCALGROUP $group $Username /add
}
$Username = "su"
$Usrstring = "WinNT://localhost/"+$Username
$usr=[ADSI] $Usrstring
$usr.passwordExpired = 1
$usr.setinfo()
I think you can use the try-catch
method and New-localuser
to do this.
$username = "TestUser"
$Password = cat C:\script2\init.pwd | ConvertTo-SecureString
#Changing this back to what would work for you. I was supplying a plaintext password
#$Password = Read-Host -Prompt "Password" -AsSecureString
try
{
Get-LocalUser -Name $username -ErrorAction Stop
#"User Already exists"
}
catch
{
New-LocalUser -Name $username -Password $Password
Add-LocalGroupMember -Group "Administrators" -Member $username
$usr=[ADSI]"WinNT://localhost/$username"
$usr.passwordExpired = 1
$usr.setinfo()
}
If this is saved as a script say Create-localUser.ps1
you can invoke this from Run
, Task Scheduler
or a logon batch script
using the command
powershell.exe -windowstyle Hidden -file C:\\temp\\create-Localuser.ps1
And keep it hidden from the logged on user. I assumed thats what you meant by invisible.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.