Powershell script to switch current logged in user? - powershell

I am trying to write a Powershell script to create a new Windows user an then log into that new account. I can create the new account like so:
New-LocalUser -Name $username -Description 'SomeAccountName' -Password 'SomePassword' -PasswordNeverExpires -UserMayNotChangePassword
But I am unsure if I am then able to log into the new account from the same script. Is this possible? And if so, how could I go about doing so?

Related

How do I run a command on localhost with saved credentials? -Powershell

I want to run one command with saved credentials on powershell, i have the following script
$user = "test"
$passwd = ConvertTo-SecureString -String "ExtremelyStrongPassword" -AsPlainText -Force
$cred = New-Object System.Management.Automation.PSCredential -ArgumentList $user, $passwd
Copy-Item -Path "C:\Temp\*" "C:\Program Files\Test\" -Credentials $cred
The user doesn't have administrator permissions, but in the localhost we have an user with administrator permissions to run these process.
The error returned is "Access Denied"
How do i pass these parameters to run a command with elevation?
Never pass plain text credentials in a script. Use the Get-Credential cmdlet to collect and use them. Even doing this, the user will get prompted for a password.
This is what the -RunAs switch of Start-Process is for
Or set your script to auto elevate
Or use the credential switch of a cmdlet
Or use a scheduled task with whatever creds you need, and let the user run it.
Use the Requires statement at the top of your script
Store the need creds in the Windows Credential Store and call them
from there
about_Requires - PowerShell | Microsoft Docs
Short description Prevents a script from running without the required
elements.
#Requires -RunAsAdministrator
Start-Process
Example 5: Start PowerShell as an administrator This example starts
PowerShell by using the Run as administrator option.
Start-Process -FilePath "powershell" -Verb RunAs
Using what you have this way:
Copy-Item -Path 'C:\Temp\*' 'C:\Program Files\Test\' -Credentials (Get-Credential -Credential 'Domain\UserName')
With exception of the scheduled task approach, each will prompt the user for a password, which sounds like what you wanting to avoid. So, consider the following:
Accessing Windows Credentials Manager from PowerShell
This simple PowerShell class can be used for working with Credentials
Manager and Password Vault in Windows: checking if account information
is present in the vault, saving credentials to the vault and reading
stored login and password information from the vault.
https://gallery.technet.microsoft.com/scriptcenter/Accessing-Windows-7210ae91
Using the registry to store credentials:
Save Encrypted Passwords to Registry for PowerShell

Create local administrator user account fails in Intune

The PowerShell script below works fine when I run it manually in a machine, but it won't run when deployed using Intune. It simply shows an error.
I have deployed this script using Intune with these settings -
(1) Run this script using the logged on credentials: No. (2)
Enforce script signature check: No. (3)
Run script in 64 bit PowerShell Host: No
Tested the script in a Windows 10 computer by starting CMD as admin, it works fine. Creates the local account if it does not exists, if it exists it changes the password.
PS> PowerShell -Ex ByPass scriptname.ps1
I am not able to find any event log (under DeviceManagement-Enterprise-Diagnostics-Provider) or error under MDMDiagnostics logs in the Intune enrolled Windows 10 computer.
$ExpectedLocalUser = "SUPERMAN"
$Password = ConvertTo-SecureString "P#ssw0rd" -AsPlainText -Force
Function Create_LocalAdmin
{
New-LocalUser $ExpectedLocalUser -Password $Password -FullName "Local Admin" -Description "Local Administrator account."
Add-LocalGroupMember -Group "Administrators" -Member $ExpectedLocalUser
Set-LocalUser -Name $ExpectedLocalUser -PasswordNeverExpires:$true
}
Try
{
## Catch if not found
$LocaAdminUser = Get-LocalUser -Name $ExpectedLocalUser -ErrorAction Stop
## If an account is found update the password
Set-LocalUser -Name $ExpectedLocalUser -Password $Password -PasswordNeverExpires:$true
}
Catch
{
Create_LocalAdmin
}
#mathias-r-jessen Suggestion worked. Changed to start PS in 64 bit host, and it worked.

How to store local administrator username and password in powershell script

I am creating a PowerShell script that a user can just run to edit an entry in registry. My problem is that I cannot figure out how to store local admin username and password in the same script so that the user can just double click the script and run it without having to enter username and password manually.
Here is my code:
$username = "testpc\administrator"
$pasword = get-content C:\Users\test1\documents\testpassword.txt
$credential = new-object -typename system.management.automation.pscredential -argumentlist $username, $password
This does not work at all. Please let me know what I am doing wrong here.
Usually I'd ask for an error, but in this case I'll advise different, just because your approach isn't acceptable.
Don't store passwords unencrpted in script. Never.
Don't store passwords encrypted in scripts, which are meant to be read by someone else, especially not a user with less privileges. Never!
Go, figure other ways to solve your problem. Always!
In this case I see two solutions with the given information:
change the ACL for the registry key that need to be changed by the user
Create a scheduled task which runs as SYSTEM. Make sure the user cannot edit the script.
Actually #vrdse is right.
you can create the script with the KEY as parameter and:
create a scheduled job with the credentials of your user and add the script as task.
give the user the right to execute the job but NOT to edit or to delete
give a shortcut to the scheduled job (or a runner script) to the user and make a how-to document to show him,/her how the parameter should be used.
I use clear text passwords as temporary testing stuff to make sure users CANNOT use my script (so it is exactly the opposite of your action).
You can capture credential during execution:
$cred = get-gredential -message 'This script needs a real admin user'
Enter-PSSession -Credential $cred -ComputerName 127.0.0.127
You can build a credential (do not store privileged user data):
$user = 'SuchAGreatDomainName\IAmLowPrivilegedUserName'
$Password = 'SuperSecretPassEverybodyKnows'
$secpassword = ConvertTo-SecureString $Password -AsPlainText -Force
$credential = New-Object System.Management.Automation.PSCredential($user, $secpassword)
Invoke-RestMethod -Uri $Uri -Credential $Credential

Reset all Windows 10 user passwords [duplicate]

This question already has answers here:
How do I get the result of a command in a variable in windows? [duplicate]
(13 answers)
Closed 6 years ago.
I am deploying Airwatch to my organization. On company-owned laptops, I would like to lock them down if/when the device is ever un-enrolled. There is no built-in method of doing this, so I am looking for a script to do it. My relevant background: I know very little batch, some powershell, a lot of vbscript (for classic ASP).
I would like one or both of the following:
Reset all user passwords on the laptop to something preset
Create a specific local admin and then disable all other local users
I know I can use "net user" to get a list of users, but I do not know how to use that list to actually disable the users or change their passwords. The batch commands to fit this logic would be ideal:
net user NewAdmin Password /add
net localgroup administrators NewAdmin /add
UserList = net user output
For each UserName in UserList
If UserName <> "NewAdmin" Then
net user UserName NewPassword
net user UserName /active:no
End If
Next
If you are using Windows 10 Vs.1607 or newer, you can use something like this PowerShell script:
$AdminPwd = ConvertTo-SecureString -string "foobar2016!" -AsPlainText -Force
$UserPwd = ConvertTo-SecureString -string "foobar2016!" -AsPlainText -Force
$NewAdmin = "NewAdmin"
New-LocalUser -Name $NewAdmin -FullName "New Admin" -Password $AdminPwd
Add-LocalGroupMember -Member $NewAdmin -Group "Administrators"
Get-LocalUser | ForEach-Object {
if ($_.Name -ne $NewAdmin)
{
$_ | Set-LocalUser -Password $UserPwd
$_ | Disable-LocalUser
}
}
Be careful when testing it, it disables all users except the new one.
The LocalUser cmdlets are new in PowerShell Vs. 5.1

PowerShell: Create Local User Account

I need to create a new local user account, and then add them to the local Administrators group. Can this be done in PowerShell?
EDIT:
# Create new local Admin user for script purposes
$Computer = [ADSI]"WinNT://$Env:COMPUTERNAME,Computer"
$LocalAdmin = $Computer.Create("User", "LocalAdmin")
$LocalAdmin.SetPassword("Password01")
$LocalAdmin.SetInfo()
$LocalAdmin.FullName = "Local Admin by Powershell"
$LocalAdmin.SetInfo()
$LocalAdmin.UserFlags = 64 + 65536 # ADS_UF_PASSWD_CANT_CHANGE + ADS_UF_DONT_EXPIRE_PASSWD
$LocalAdmin.SetInfo()
I have this, but was wondering if there is anything more PowerShell-esque.
Another alternative is the old school NET USER commands:
NET USER username "password" /ADD
OK - you can't set all the options but it's a lot less convoluted for simple user creation & easy to script up in Powershell.
NET LOCALGROUP "group" "user" /add to set group membership.
As of PowerShell 5.1 there cmdlet New-LocalUser which could create local user account.
Example of usage:
Create a user account
New-LocalUser -Name "User02" -Description "Description of this account." -NoPassword
or Create a user account that has a password
$Password = Read-Host -AsSecureString
New-LocalUser "User03" -Password $Password -FullName "Third User" -Description "Description of this account."
or Create a user account that is connected to a Microsoft account
New-LocalUser -Name "MicrosoftAccount\usr name#Outlook.com" -Description "Description of this account."
Try using Carbon's Install-User and Add-GroupMember functions:
Install-User -Username "User" -Description "LocalAdmin" -FullName "Local Admin by Powershell" -Password "Password01"
Add-GroupMember -Name 'Administrators' -Member 'User'
Disclaimer: I am the creator/maintainer of the Carbon project.
As of 2014, here is a statement from a Microsoft representative (the Scripting Guy):
As much as we might hate to admit it, there are still no Windows
PowerShell cmdlets from Microsoft that permit creating local user
accounts or local user groups. We finally have a Desired State
Configuration (DSC ) provider that can do this—but to date, no
cmdlets.
Import-Csv C:\test.csv |
Foreach-Object {
NET USER $ _.username $ _.password /ADD
NET LOCALGROUP "group" $_.username /ADD
}
edit csv as username,password
and change "group" for your groupname
:) worked on 2012 R2
$sec_pass = ConvertTo-SecureString -String "SomePasword" -AsPlainText -Force
New-LocalUser -Name username -FullName username -PasswordNeverExpires -Password $sec_pass
Add-LocalGroupMember -Group Administrators -Member username