Maintaining user environment variables in Powershell logon script with admin privileges - powershell

I accidentally deleted 180 users from my AD and they aren't recoverable. I have recreated the accounts in AD and what not. This creates a new profile on their laptops when they login because of the new SID. I'm trying to write a script that grants them access to their old profile folder and create a shortcut on their desktop that leads there.
I've got the script working fine with one problem. The environment variables that are used, end up referring back to the admin account that runs the script. The users themselves don't have permission to change security on their old folder. I need to try and have the environment variables refer to the user yet have the privilege of an admin account to rewrite the permissions.
Here is the script so far.. I'm deploying this with Task Scheduler at the moment, which is another can of worms in that I'm not entirely understanding of the credential side of things there. I mean ideally, the task would run as a domain admin, execute the script asap, and have the script resolve the environment variables to the logged on user.
$permission = ":(OI)(CI)M"
$sam = $env:USERNAME
$folderName = "C:\Users\$($sam)"
Invoke-Expression -Command ( 'ICACLS $folderName /grant:r $sam$($permission) /t' )
$WshShell = New-Object -comObject WScript.Shell
$Shortcut = $WshShell.CreateShortcut("$Home\Desktop\Profile Backup.lnk")
$Shortcut.TargetPath = $folderName
$Shortcut.Save()
Its the $env:USERNAME and $home variables that are giving me trouble..
Or is there another way I should be tackling this problem?

You could use query session command to get the login name of the current logged on user. Then create NTAccount object based on that to retrieve SID and win32_userprofile WMI object to find out the profile path. Like this:
$m = query session | Select-String -Pattern "\>console\s*(\S*)\s"
$sam = $m.Matches[0].Groups[1].value
$acc = New-Object System.Security.Principal.NTAccount($sam)
$sid = $acc.Translate([System.Security.Principal.SecurityIdentifier]).Value
$profile = Get-CimInstance -ClassName win32_userprofile -Filter "SID='$sid'"
$folderName = $profile.LocalPath

Edit I have given it second thought over-night so I'll update the answer. You will be required to have domain admin password encrypted and then users will run the script.
It always sucks when something like this happens. I don't have a possibility to try this out, but I think the following approach would be feasible. The script asks user for password encrypts it and run the command as the user.
First phase would be to have a domain admin to encrypt his password to a file:
This is to be prepared by Domain Admin (distributed with the PS script) - I recommend changing password after the recovery is complete:
1) Read-Host -AsSecureString | ConvertFrom-SecureString | Out-File 'C:\<script_path>\admin_passwd.txt'
2) This is to be executed by user (you have to fill in the admin user id and have the password file distributed with the script). The script path can be obtained by (Get-Location).Path. I'm not adding it into the source code so you can decide how to implement it:
$permission = ":(OI)(CI)M"
$admin= "<your_admin_userid>"
$sam = $env:USERNAME
$domain = $env:UserDomain
$folderName = "C:\Users\$($sam)"
# get domain admin password
$encrypted_passwd = get-content 'C:\<script_path>\admin_passwd.txt' | ConvertTo-securestring
# Setting process invocation parameters.
$process_start_info = New-Object -TypeName System.Diagnostics.ProcessStartInfo
$process_start_info.CreateNoWindow = $true
$process_start_info.UseShellExecute = $false
$process_start_info.RedirectStandardOutput = $true
$process_start_info.RedirectStandardError = $true
$process_start_info.UserName = $admin
$process_start_info.Domain = $domain
$process_start_info.Password = $encrypted_passwd
$process_start_info.Verb = 'runas'
$process_start_info.FileName = 'ICACLS'
$process_start_info.Arguments = "$folderName /grant:r $sam$($permission) /t"
# Creating process object.
$process = New-Object -TypeName System.Diagnostics.Process
$process.StartInfo = $process_start_info
# Start the process
[Void]$process.Start()
$process.WaitForExit()
# synchronous output - captures everything
$output = $process.StandardOutput.ReadToEnd()
$output += $process.StandardError.ReadToEnd()
Write-Output $output
$WshShell = New-Object -comObject WScript.Shell
$Shortcut = $WshShell.CreateShortcut("$Home\Desktop\Profile Backup.lnk")
$Shortcut.TargetPath = $folderName
$Shortcut.Save()

Related

Trying to run a script block locally as admin using powershell

I am trying to write a powershell script that runs a specific code block as a domain admin and moves a computer to a specific OU.
If I run it as a domain admin, it works fine, but the problem is it usually runs it as a local admin; which obviously won't add the computer to the domain.
So I added the credentials as part of the script, but it doesn't seem to be working.
Here is my code:
CLS
$command = {
# Specify, or prompt for, NetBIOS name of computer.
$Name = $env:COMPUTERNAME
# Retrieve Distinguished Name of current domain.
$Domain = [System.DirectoryServices.ActiveDirectory.Domain]::GetCurrentDomain()
$Root = $Domain.GetDirectoryEntry()
$Base = ($Root.distinguishedName)
# Use the NameTranslate object.
$objTrans = New-Object -comObject "NameTranslate"
$objNT = $objTrans.GetType()
# Initialize NameTranslate by locating the Global Catalog.
$objNT.InvokeMember("Init", "InvokeMethod", $Null, $objTrans, (3, $Null))
# Retrieve NetBIOS name of the current domain.
$objNT.InvokeMember("Set", "InvokeMethod", $Null, $objTrans, (1, "$Base"))
$NetBIOSDomain = $objNT.InvokeMember("Get", "InvokeMethod", $Null, $objTrans, 3)
# Retrieve Distinguished Name of specified object.
# sAMAccountName of computer is NetBIOS name with trailing "$" appended.
$objNT.InvokeMember("Set", "InvokeMethod", $Null, $objTrans, (3, "$NetBIOSDomain$Name$"))
$ComputerDN = $objNT.InvokeMember("Get", "InvokeMethod", $Null, $objTrans, 1)
#Bind to computer object in AD.
$Computer = [ADSI]"LDAP://$ComputerDN"
#Specify target OU.
$TargetOU = "OU=Block-Policies,OU=Windows 10,OU=LAPTOPS,OU=COMPUTERS,OU=COMPUTER-SYSTEMS,DC=domain,DC=com"
#Bind to target OU.
$OU = [ADSI]"LDAP://$TargetOU"
# Move computer to target OU.
$Computer.psbase.MoveTo($OU)
}
#Credentials
$domain = "domain.com"
$password = "2093dhqwoe3212" | ConvertTo-SecureString -asPlainText -Force
$username = "$domain\DomainAdmin"
$credential = New-Object System.Management.Automation.PSCredential($username,$password)
#Run the command with escalation
Invoke-Command -Credential credential -ComputerName localhost -ScriptBlock {$command}
I know the credentials work because if I manually type them in and run the script, it works. I have tried using invoke-command as well as
start-job -ScriptBlock {$command} -Credential $credential
Neither seem to be working for me.
The start-job seems to go through, but doesn't actually move the computer. The invoke-command gives me an error.
"[localhost] Connecting to remote server localhost failed with the following error message: The client cannot connect to the destination specified in the request ..."

PowerShell: How to add 1 user to multiple Active Directory Security Groups - Security tab of the security group with write permission

I am trying to add 1 ID to multiple security groups in Active Directory.
The ID needs to be only added to the "Security Tab" of the Security Group and not added as a member.
I need to set "write" permission for this ID.
Is there anyways to do this in Power-Shell?
There are instructions here, although that gives a user full control of the group (including rights to delete), and has some other issues (like a hard-coded username).
I've modified that example for you to only give GenericWrite permissions, and to accept the username as a parameter. This also assumes the user, group, and computer you're running this on are all on the same domain:
function Set-GroupSecurity {
[CmdletBinding()]
param (
[string] $GroupName,
[string] $UserName
)
$dom = [System.DirectoryServices.ActiveDirectory.Domain]::GetCurrentDomain()
$root = $dom.GetDirectoryEntry()
$search = [System.DirectoryServices.DirectorySearcher]$root
$search.Filter = "(&(objectclass=group)(sAMAccountName=$GroupName))"
$search.SizeLimit = 3000
$result = $search.FindOne()
$object = $result.GetDirectoryEntry()
$sec = $object.ObjectSecurity
## set the rights and control type
$allow = [System.Security.AccessControl.AccessControlType]::Allow
$read = [System.DirectoryServices.ActiveDirectoryRights]::GenericRead
$write = [System.DirectoryServices.ActiveDirectoryRights]::GenericWrite
## who does this apply to
$domname = ([ADSI]"").Name
$who = New-Object -TypeName System.Security.Principal.NTAccount -ArgumentList "$domname", $UserName
# apply rules
$readrule = New-Object -TypeName System.DirectoryServices.ActiveDirectoryAccessRule -ArgumentList $who, $read, $allow
$sec.AddAccessRule($readrule)
$writerule = New-Object -TypeName System.DirectoryServices.ActiveDirectoryAccessRule -ArgumentList $who, $write, $allow
$sec.AddAccessRule($writerule)
# tell it that we're only changing the DACL and not the owner
$object.get_Options().SecurityMasks = [System.DirectoryServices.SecurityMasks]::Dacl
# save
$object.CommitChanges()
}
You can paste that into a PowerShell prompt and hit enter. That will make the function available to use. Then you can use it like this:
Set-GroupSecurity -GroupName "TstGroup1" -UserName "someone"

Powershell Verify local Credentials

So in my script I want to not only have the user enter and store credentials in a variable but be able to verify that the password matches the admin password on the target system. So far the only way I have found to do this is by putting the actual password unecrypted in the script and comparing it to the one the user enters. That is a huge security flaw and to remedy it I was wondering if I could get the admin password using a gwmi query (SID?) as an object and compare that to the secure string the user enters.
Here is my flawed code I am using right now.
Do
{
$password = $null
$password = read-host "Enter the Administrator Password" -assecurestring
$AdminPass = ConvertTo-SecureString "adminpassword" -AsPlainText -Force
$pwd1_text = [Runtime.InteropServices.Marshal]::PtrToStringAuto([Runtime.InteropServices.Marshal]::SecureStringToBSTR($password))
$pwd2_text = [Runtime.InteropServices.Marshal]::PtrToStringAuto([Runtime.InteropServices.Marshal]::SecureStringToBSTR($AdminPass))
if ($pwd1_text -cne $pwd2_text) {Write-Host -ForegroundColor Red "Incorrect Password"; $password = $null}
$count ++
$tries = 3 - $count
if ($password -eq $null) {Write-Host -ForegroundColor Yellow "$tries Attempts Remaining"}
if ($count -eq 3) {Write-Host -ForegroundColor Red "$count Unsuccessful Password Attempts. Exiting..."; exit}
}While ($password -eq $null)
$cred = new-object -typename System.Management.Automation.PSCredential -argumentlist "$ComputerName\Administrator",$password
Here's a function I wrote that tests a PSCredential object, against a Domain or a local Machine:
function Test-Credential {
<#
.SYNOPSIS
Takes a PSCredential object and validates it against the domain (or local machine, or ADAM instance).
.PARAMETER cred
A PScredential object with the username/password you wish to test. Typically this is generated using the Get-Credential cmdlet. Accepts pipeline input.
.PARAMETER context
An optional parameter specifying what type of credential this is. Possible values are 'Domain' for Active Directory accounts, and 'Machine' for local machine accounts. The default is 'Domain.'
.OUTPUTS
A boolean, indicating whether the credentials were successfully validated.
.NOTES
Created by Jeffrey B Smith, 6/30/2010
#>
param(
[parameter(Mandatory=$true,ValueFromPipeline=$true)]
[System.Management.Automation.PSCredential]$credential,
[parameter()][validateset('Domain','Machine')]
[string]$context = 'Domain'
)
begin {
Add-Type -AssemblyName System.DirectoryServices.AccountManagement
$DS = New-Object System.DirectoryServices.AccountManagement.PrincipalContext([System.DirectoryServices.AccountManagement.ContextType]::$context)
}
process {
$DS.ValidateCredentials($credential.GetNetworkCredential().UserName, $credential.GetNetworkCredential().password)
}
}
If you want to test against local accounts on a remote machine, you'll need to load this function on the remote machine and test the credential against the 'local' machine via remoting (Invoke-Command), but it should be possible.

Powershell Connect to VSO

I'm trying to use Powershell to connect to VSO. Here is my code:
$tfsServer = New-Object System.Uri("the server is here")
$creds = [System.Net.CredentialCache]::DefaultNetworkCredentials
$tfsCollection = New-Object Microsoft.TeamFoundation.Client.TfsTeamProjectCollection($tfsServer,$creds)
$tfsCollection.Authenticate()
When it reaches the Authenticate line, it pops up a box for me to enter my credentials. I need it to not pop up this box, as this script will be scheduled, and I can't keep entering the credentials. How can I pass the current user's credentials to the TFS object?
Try this:
First, run this command which will prompt you once for your password, and then save it in an encrypted format.
read-host -prompt Password -assecurestring | convertfrom-securestring | out-file .\ps-password.pwd -ErrorAction Stop
Change the $username variable
$Username = 'jdoe'
$Password = Get-Content ".\ps-password.pwd" | ConvertTo-SecureString
$creds = New-Object -typename System.Management.Automation.PSCredential -ArgumentList $Username,$Password
$tfsServer = New-Object System.Uri("the server is here")
$tfsCollection = New-Object Microsoft.TeamFoundation.Client.TfsTeamProjectCollection($tfsServer,$creds)
$tfsCollection.Authenticate()
Use the constructor that just takes a URI. It will default to using the credentials of the current user.
To connect to Visual Studio Online, you have to follow the instructions at Buck's post. Shortly:
enable alternate credentials on the VSO account
set alternate user and password
use code similar to the following
$tfsServer = New-Object System.Uri("the server is here")
$netCred = New-Object NetworkCredential("alternate_user","alternate_password")
$basicCred = New-Object Microsoft.TeamFoundation.Client.BasicAuthCredential($netCred)
$tfsCred = New-Object Microsoft.TeamFoundation.Client.TfsClientCredentials($basicCred)
$tfsCred.AllowInteractive = $false
$tfsCollection = New-Object Microsoft.TeamFoundation.Client.TfsTeamProjectCollection($tfsServer,$tfsCred)
$tfsCollection.EnsureAuthenticated()
I know no way of using current process credentials with VSO, but you must explicitly pass them.
Use EnsureAuthenticated and do not specify credentials.
$tfsCollection = TfsTeamProjectCollectionFactory.GetTeamProjectCollection("the server is here")
$tfsCollection.EnsureAuthenticated()
This way it will use the account running the process.

PowerShell: Update Scheduled Task username and password?

I'm looking for a way to update the credentials on existing scheduled tasks on machines.
Schtasks doesn't work for AT created scheduled tasks
Win32_ScheduledJob only works for AT created jobs
Schedule.Service COM object - not sure
It appears that I can use RegisterTask and RegisterTaskDefinition to CREATE scheduled tasks but I'm not clear if I can update the existing credentials with those methods. Please advise. Thx.
I would recommend having a look at the managed TaskScheduler API, which is a .NET wrapper for the TaskScheduler COM API. It's an open-source project available on CodePlex.
http://taskscheduler.codeplex.com/
The project author has this to say about updating passwords:
If you are trying to create a task using the credentials of the
current user and you only want it to run when that user is logged in,
you need to call the RegisterTaskDefinition method as in the end of
the Complex example with the InteractiveToken parameter. If you need
to create as another specific user, then use that same method, but
supply the username, password, and set the TaskLogonType to
InteractiveTokenOrPassword or Password. There are some triggers that
are specific to a user, like the LogonTrigger where you can also
supply a user credential.
The appropriate overload for RegisterTaskDefinition is defined in TaskFolder.cs.
http://taskscheduler.codeplex.com/SourceControl/changeset/view/75611#19440
public Task RegisterTaskDefinition(string Path, TaskDefinition definition
, TaskCreation createType, string UserId, string password = null
, TaskLogonType LogonType = TaskLogonType.S4U, string sddl = null)
I had this task come up recently. I know this post is old but wanted to put this script somewhere for people to find hopefully help them. This is pure power shell so no extra setup required. I had tried using the Set-ScheduledTask but had issues setting domain user. I ended up using schtasks instead. You may need to run this script as administrator.
$domainUsername = "domain\user"
$password= "somePassword"
$tasks = Get-ScheduledTask | Where-Object { $_.Principal.UserId -eq $domainUsername }
foreach ($task in $tasks) {
$myTask = $task.TaskPath+$task.TaskName
echo changing $myTask
schtasks /change /s $env:COMPUTERNAME /tn $myTask /ru $domainUsername /rp $password
}
Here is another example of how to push out to multiple servers. THe sessionCredentials are the credentials used to connect to the servers the domain user and new password are the name and password to be set to the tasks
$sessionCredentials = Get-Credential
$taskDomainUsername = "DOMAIN\SOMEACCOUNT"
$NewPassword = "somePassword"
$computerNames = #(
"someNameServer1",
"someNameServer2"
)
$serverSession = New-CimSession -ComputerName $computerNames -Credential $sessionCredentials
$tasks = Get-ScheduledTask -CimSession $serverSession | Where-Object { $_.Principal.UserId -eq $taskDomainUsername }
foreach($task in $tasks) {
echo updating $task
$specificSession = $serverSession | Where-Object { $_.ComputerName -eq $task.PSComputerName}
$taskFullName = $task.TaskPath+$task.TaskName
Set-ScheduledTask -CimSession $specificSession -TaskName $taskFullName -User $taskDomainUsername -Password $NewPassword
}