Power Shell issue with create user - powershell

what is here wrong with create a local user?
$user New-LocalUser -Name "test" -NoPassword -AccountNeverExpires -UserMayNotChangePassword -FullName "Test Admin" -Description "Test User Admin " | Set-LocalUser -PasswordNeverExpires $true

Because you pipe the returned object of New-LocalUser directly through to Set-LocalUser, the capturing variable $user will be $null.
As you can see in the docs, the Set-LocalUser cmdlet returns no output
The fix is easy: seperate these two commands in two separate lines.
Also, I would recommend using Splatting on cmdlets that take a lot of parameters to help keep the code readable as opposed to using extremely long code lines.
# create a Hashtable with all parameters and their values
# for use with the New-LocalUser cmdlet
$userParams = #{
Name = "test"
FullName = "Test Admin"
Description = "Test User Admin"
AccountNeverExpires = $true
NoPassword = $true
UserMayNotChangePassword = $true
}
# create the user and afterwards set another property to the user object
$user = New-LocalUser #userParams
$user | Set-LocalUser -PasswordNeverExpires $true
Add-LocalGroupMember -Group "Administrators" -Member $user
Add-LocalGroupMember -Group "Remote Desktop Users" -Member $user
Setting -PasswordNeverExpires $true shouldn't be necessary anyway, because you created the user with option -NoPassWord AND UserMayNotChangePassword

It is not working because of set-Localuser is added in user creation itself.
$user = New-LocalUser -Name "test" -NoPassword -AccountNeverExpires -UserMayNotChangePassword -FullName "Test Admin" -Description "Test User Admin "
$user | Set-LocalUser -PasswordNeverExpires $true
Add-LocalGroupMember -Group "Administrators" -Member $user
Add-LocalGroupMember -Group "Remote Desktop Users" -Member $user

Related

Is there any logic like if else or any other command in powershell to get the powershell script non-interactive?

I am preparing the powershell script to move the local mailbox to online mailbox via powershell script and after migration will assign the license
Below is the sample:
#Created the user in AD , not mentioned here
Enable-Mailbox -Identity "$firstname $lastname" -Database "XXXXXXX"
Start-Sleep -Seconds 10
Set-Mailbox "$firstname.$lastname" -PrimarySmtpAddress "$firstname.$lastname#XXXXXXX" -EmailAddressPolicyEnabled $false
Is there any logic like if-else or something else which i can use here which trigger the below command once the user mailbox is sync from local exchange to online exchange ?So below command is run successfully without any issue or error.
Connect-ExchangeOnline
$Mailbox = "$firstname.$lastname#XXXXXXX"
$Endpoint = "XXXXXXXX"
$TargetDomain = "XXXXXXXXXXX"
$Cred = Get-Credential
New-MoveRequest -Identity $Mailbox -Remote -RemoteHostName $Endpoint -TargetDeliveryDomain $TargetDomain -RemoteCredential $Cred -Batchname "$Mailbox Move to O365"
Is there any logic like if-else or something else which i can use here which trigger the below command once the mailbox migration is done then below command is execute?
#Assign the license once migration is done successfully
Set-MsolUser -UserPrincipalName $Mailbox -UsageLocation US
Set-MsolUserLicense -UserPrincipalName $Mailbox -AddLicenses "XXXXXXXXXXXX"
Note-I can use the Start-Sleep -Seconds XXX in between but sync time is not same everytime
in order to assign a license after the migration of the mailboxes ; you need first to check the status of the move-request within a while loop and execute your commands if the status changed to Completed as follow:
$i = $true
while ($i){
if (Get-MoveRequest -Identity $Mailbox| where {$_.status -eq "Completed"}) {
Set-MsolUser -UserPrincipalName $Mailbox -UsageLocation US
Set-MsolUserLicense -UserPrincipalName $Mailbox -AddLicenses "XXXXXXXXXXXX"
$i = $False
} else {
sleep 10
}
}

New-LocalUser returns null but user account is created

I am creating a local user by running below command.
$LocalAccount = New-LocalUser "myaccount" -Password "*****" -FullName "My Account" -Description "My Account" -AccountNeverExpires -PasswordNeverExpires
According to Microsoft documentation, New-LocalUser command is supposed to return a LocalUser object.
Right after that, I am adding that account to Administrators group but it fails as $LocalAccount is null even though I can see that the account is created.
if ((Get-LocalGroupMember -Group "Administrators" -Member $LocalAccount).Count -eq 0)
{
Add-LocalGroupMember -Group "Administrators" -Member $LocalAccount
}
This happens only when I run this as part of a script. If I just run $LocalAccount = New-LocalUser "myaccount" -Password "*****" -FullName "My Account" -Description "My Account" -AccountNeverExpires -PasswordNeverExpires, it works fine and I can see $LocalAccount has new user info.
What am I missing here?
I think the problem is Get-LocalGroupMember which doesn't give you any output when run within the script. This means your If statement will always return false and the Add-LocalGroupMember is not getting executed.
Alternatively, you can add the user to the group at the time of account creation:
$LocalAccount = New-LocalUser "myaccount" -Password $Secure_String_Pwd -FullName "My Account" -Description "My Account" -AccountNeverExpires -PasswordNeverExpires -Verbose | Add-LocalGroupMember -Group "Administrators" -Verbose
if you want to keep your original script they try using write-output:
$LocalAccount = New-LocalUser "myaccount" -Password $Secure_String_Pwd -FullName "My Account" -Description "My Account" -AccountNeverExpires -PasswordNeverExpires -Verbose
if ((Get-LocalGroupMember -Group "Administrators" -Member $LocalAccount -Verbose -ErrorAction SilentlyContinue| Write-Output).Count -eq 0)
{
Add-LocalGroupMember -Group "Administrators" -Member $LocalAccount -Verbose
}
Your if statement is not helping because the account is freshly created using New-LocalUser so no need to check if it is part of the Administrators group.
Firstly, you must pass an encrypted password to New-LocalUser, so that is probably why you are not getting a return object. Also you need to use the .Name portion of the object when you perform the Add-LocalGroupMember or Get-LocalGroupMember. Also instead of '-eq 0' (which works), it's always better to use '-lt 1'. Lastly consider using 'measure' if you are trying to get a count.
Rough working example:
$passwd = ("thepassword" | ConvertTo-SecureString -AsPlainText -Force)
$AddObj = (New-LocalUser "myaccount" -Password $passwd -FullName "My Account" -Description "My Account" -AccountNeverExpires -PasswordNeverExpires)
if ((Get-LocalGroupMember -Group "Administrators" | where-object Name -match "\\${AddObj.Name}$" | measure).Count -lt 1)
{
Add-LocalGroupMember -Group "Administrators" -Member $AddObj.Name
}
Note this is just a rough example, you need to check for the user first and also it's better to use a variable for the account id and not the object IMO.

create user with respone if success and two inputs of the password

i want to create a local admin account. how can i realize a output if the operation was successfull or not? and how can i realize that i need to input the same password twice for safety reasons for example i made a mistake? if the passwords are incorrect i need to type them again
$admin = read-host "Name"
$Password = Read-Host "Passwort" -AsSecureString
New-LocalUser -Name "$admin" -password $password -Description "$admin" -FullName "$admin"
Add-LocalGroupMember -Name "administrators" -Member "$admin"
Set-LocalUser -Name "$admin" -PasswordNeverExpires 1 -AccountNeverExpires -UserMayChangePassword 0
You can do that in a endless loop.
Something like below:
$userName = Read-Host "Name"
$securePassword = Read-Host "Password" -AsSecureString
$plainTextPassword = [System.Net.NetworkCredential]::new("someone", $securePassword).Password
while ($true) {
$securePassword2 = Read-Host "Retype the password. Leave empty to cancel." -AsSecureString
# convert the SecureString to plain text
$plainTextPassword2 = [System.Net.NetworkCredential]::new("someone", $securePassword2).Password
if ([string]::IsNullOrWhiteSpace($plainTextPassword2)) { return } # cancel: exit the script
if ($plainTextPassword -ceq $plainTextPassword2) { break } # both passwords are equal, break the loop
}
try {
$newUser = New-LocalUser -Name $userName -Password $securePassword -Description $userName -FullName $userName -ErrorAction Stop
$newUser | Set-LocalUser -PasswordNeverExpires $true -UserMayChangePassword $false -AccountNeverExpires -ErrorAction Stop
Add-LocalGroupMember -Group "Administrators" -Member $userName -ErrorAction Stop
}
catch {
throw $_.Exception.Message
}

Windows 10 Local User Creation via PowerShell - How to make it interactive?

I'm not sure if my problem has been described and resolved in another post, but I haven't found it...
I'm trying to create a PowerShell script to get a Local User Account created on Windows 10 machines that are not in AD nor domain. I want to have the possibility to enter the "first" and "last" names of the new user or at least the "username" and not need to modify this in the PS script file every time before running it.
I tried this code but it doesn't create any new users...
$FirstName = Read-Host -Prompt 'Enter User First Name:'
$LastName = Read-Host -Prompt 'Enter User Last Name:'
$Username=$FirstName.substring(0,1)+$LastName
New-LocalUser $Username -Description "INT-G-MAT Local User" -NoPassword
You could use
New-LocalUser -FullName "Fullname" -AccountNeverExpires $True -Description "Something"
By using ScriptBlock, you can create useraccounts on remote machines.
For example
Invoke-Command -ComputerName $Computername -ScriptBlock { # Start ScriptBlock
New-LocalUser -FullName "Fullname" -AccountNeverExpires $True -Description "Something"
} # End Scriptblock
If you want to check what accounts are on the remote machine,
Get-WmiObject -Class Win32_UserProfile
I would start something like this and then test until I think is acceptable in this script
Invoke-Command -ComputerName "Computername" -ScriptBlock { # Start ScriptBlock
$Fullname = Read-Host -Prompt "Enter User First Name:"
New-LocalUser -FullName $Fullname -AccountNeverExpires $True -Description "Something" -PasswordNeverExpires $True
} # End Scriptblock

Powershell create new user copy group membership

I'm trying to successfully execute a script which has cmdlets from a win8.1 machine to a 2003 domain controller. I set up ADWS on the 2003 domain controller and can now use cmdlets on it remotely from my win8.1 machine.
What I'm trying to do with this script is to get the group membership details from a pre-existing user ($UserOne), create a new user ($UserTwo), create a foreach loop which copies the group membership details from the pre-existing ($UserOne) user to the new user ($UserTwo) that was created.
Currently the script works up until the point of creating the new user ($UserTwo), however the foreach loop afterwards doesn't seem to execute.
Would any of you know what the issue with my code is? I suspect it's how I've entered the foreach loop in directly after creating a user. I also tried creating a new session using Invoke-Command after creating the new user in order to copy the group membership, however none of my cmdlets would work in the scriptblock since the remote server is Windows 2003.
Help would be greatly appreciated, I'm still very much new to Powershell. My code is as follows:
$serv = "SERVERNAME"
$cred = "admin\admin"
$secureString = convertto-securestring "Password" -asplaintext -force
$FirstUser = "NameOne"
$SecondUser = "NameTwo"
$UserOne = Get-ADUser -Identity $FirstUser -Properties memberOf -Server $serv
New-ADUser -SAMAccountName $SecondUser -UserPrincipalName "blah#blah.com" -DisplayName $SecondUser -Enabled $true -AccountPassword $secureString -Credential $cred -Server $serv -PassThru
$UserTwo = Get-ADUser -Identity $SecondUser -Properties memberOf -Server $serv
foreach($group in $UserOne.memberof)
{
Add-ADGroupMember -Identity $group -Member $SecondUser -Server $serv
write-output $group
}
Turned out it happened to be a permissions issue, it's just that I wasn't getting any feedback via error messages!
Thanks for the posts though guys.
I see a number of issues here..
$serv = "SERVERNAME"
$cred = "admin\admin"
$secureString = convertto-securestring "Password" -asplaintext -force
$FirstUser = "NameOne"
$SecondUser = "NameTwo"
$UserOne = Get-ADUser -Identity $FirstUser -Properties memberOf -Server $serv
New-ADUser -SAMAccountName $SecondUser -UserPrincipalName "blah#blah.com"`
-DisplayName $SecondUser -Enabled $true -AccountPassword $secureString`
-Credential $cred -Server $serv -PassThru
Why add the -pasthru if your not going to use it? This will just needlessly output data to the screen (unless that is what you want).
If you assign the resulting value of the command to null, again you will get less screen junk.
Try
$null = New-ADUser -SAMAccountName $SecondUser -UserPrincipalName "blah#blah.com" -DisplayName $SecondUser -Enabled $true -AccountPassword $secureString -Credential $cred -Server $serv
and
$UserTwo = Get-ADUser -Identity $SecondUser -Properties memberOf -Server $serv
Why are you doing this? You already know the user won't be a member of any groups (except default USERS) since you just created the account. Then you never use the value $usertwo in the script.
write-host "Adding user $SecondUser to AD groups."
foreach($group in $UserOne.memberof)
{
Add-ADGroupMember -Identity $group -Member $SecondUser -Server $serv
write-output $group
}