How to pre-fill RDP username & domain using mstsc in powershell - powershell

Currently, have two domains in which our users will have machines existing in either or. I am writing a powershell script in which I collect the user name and machine name. I think perform a test-connection to determine which domain the machine resides by pinging $computer.domain.com then if fails ping $computer.otherdomain.com.
Once I determine the domain I then take the username and place "domain\" + $username to prefill the domain name. I do the same with the provided and stored $machinename by performing this: $machinename + ".domain.com".
I don't want to store user's passwords
I've been trying to use cmdkey to associate the username with the machine and call mstsc (see example below):
cmdkey /generic:TERMSRV/$computername /user:"username"
mstsc /v:$computername
however when i run this, I get a logon attempt failure which isn't ideal.
I thought about trying to use the /prompt field after mstsc /v:$computername so:
mstsc /v:$computername /prompt
but this won't use the stored username, it will instead use the user profile i am currently running the command under.
I simply want my script to take the user's username and machine name, test and confirm which domain the machine resides in the back round, then have prefilled the username with the domain and just prompting the user to enter their password to continue.
Any advice on this would be greatly appreciated!
Here is the code i am working on below: ******
#Storing the provided username within variable $Username
$UserName = $UsernameTextbox.Text
Write-host "Username entered =" $UserName
#Storing the user's provided comuter name into $Machinename
$MachineName = $HostnameTextbox.Text
Write-host "Machinename entered =" $MachineName
#Deletes any previously stored cmdkeys that may interfere with the
cmdkey /list | ForEach-Object{if($_ -like "*Target:*"){cmdkey /del:($_ -
replace " ","" -replace "Target:","")}}
if (Test-Connection -ComputerName "$MachineName.domain.com" -Quiet ) {
$User = "domain\" + $UserName
$MachineName = $MachineName + ".domain.com"
Write-Host "Computer responded in domain"
}
else {
$User = "domain2\" + $UserName
$MachineName = $MachineName + ".domain2.com"
Write-Host "Computer is most likely in domain2"
}
cmdkey /add:$MachineName /user:$user
Write-host "Username with discovered domain name =" $User
Write-host "machine name after domain check =" $MachineName
$argumentslist = "/v:$MachineName " #took out /prompt
Start-Process -FilePath C:\Windows\System32\mstsc.exe -ArgumentList
"$argumentslist"

Related

Using credentials with ADSI to reset a remote local computer account password

Trying to change a remote Windows Password using explicit credentials with PowerShell.
I've been able to make this work using the ADSI interface, but the script is running from a non-elevated account, and therefore does not have permissions. I need to ask the user for an elevated account, and then use that account when making the connection.
This works:
$server = "Server1"
$adminID = "Administrator"
$Password = "NewPassword"
$OldPassword = "OldPassword"
([ADSI] "WinNT://$server/$adminID").SetPassword($Password)
But, I need to also include the old password for the account, so that I have permissions to make the change.
Is there a way to make the connection to the server as $AdminD with the $OldPassword, and then change it to $NewPassword?
Found a solution.
$credential = New-Object System.Management.Automation.PSCredential($($server + "\" +$AdminID),$Oldpassword)
$pth = "\\$($server)\admin$"
write-host "Making connection to server with creds." -nonewline
# test for the drive, and remove if present.
if (![bool]([string]::IsNullOrEmpty($(get-psdrive x -ErrorAction SilentlyContinue).root)))
{
remove-PSDrive -Name X
write-host "Drive unmapped," -nonewline
}
New-PSDrive -Name X -PSProvider filesystem -Root $pth -Credential $credential | out-null
write-host " PS Drive established.. " -nonewline
([ADSI] "WinNT://$server/$adminID").SetPassword($Password)
By making a connection to the server first, the second call to reset the password uses the same credentials that are already established.
When done, I call the following to disconnect the drive..
# test for the drive, and remove if present.
if (![bool]([string]::IsNullOrEmpty($(get-psdrive x -ErrorAction SilentlyContinue).root)))
{
remove-PSDrive -Name X
write-host "Drive unmapped."
}
If there is a better way, I'd love to know what it is.. But this at least seemed to work.

How to validate local admin credentials against a set of servers

I have 60 servers, VMs to be particular. And I have a local admin username and password. Instead of logging on to 60 servers using these local admin creds, it would be better if there is a script to check if I could log on to these servers as a local admin using the local admin creds. To be precise, I want to check.if I can use this local admin creds to successfully log on to all 60 VMs.
I have googled but no luck. I know stackoverflow is not a place to directly ask for a piece of code, but in this case I am forced to. Even if you dont have a direct answer please direct me somewhere.
gc serverlist.txt | % {
$admin_share = '\\' + $_ + '\admin$'
if (Test-Path $admin_share) {
Write-Host "Access test passed on $($_)"
} else {
Write-Host "Access test failed on $($_)"
}
}
This is a variation of your attempt.
It assumes the same username and password for all computers.
#Get list of cserver names from file
$Servers = Get-Content -Path serverlist.txt
#Prompt user foe credentials
$Cred = Get-Credential
foreach ($Svr in $Servers)
{
#path to share (\\ServerName\Admin$)
$Path = '\\' + $Svr + '\Admin$'
Try
{
#Map admin share as PS Drive (NOT visable in the GUI)
#ErrorAction stop will jump to catch block if the connection is unsuccessfull
New-PSDrive -Name TEST -PSProvider FileSystem -Root $Path -Credential $Cred -ErrorAction Stop
#Success Message
Write-Output "Connection Successful $Svr"
#Remove drive before next loop
Remove-PSDrive -Name TEST
}
Catch
{
#Error message if connection fails
Write-Warning -Message "Connect failed $Svr"
}
}
If you have ICMP enabled, you could use Test-Connection cmdlet with the Credential switch. You can see more details in example 3 here:
https://learn.microsoft.com/en-us/powershell/module/microsoft.powershell.management/test-connection?view=powershell-6

Invoke-command doesn't need credentials

I have 2 servers (windows server 2012 R2) in the same domain.
I execute a command on server01:
Invoke-Command -ComputerName server02 -Credential Administrator -ScriptBlock {Get-Culture}
I give the password of my Administrator (of server2) and it works well.
But when I try:
Invoke-Command -ComputerName server02 -ScriptBlock {Get-Culture}
It also seems to work. Probably because the 2 servers are in the same domain. While I only want it to work when you can provide the right credentials. Can someone help me with it?
You are probably doing this by Domain Admin account or account that it's in Domain Admins group or so.
In any case this results because your account has privelegies on that computer.
With which user do you execute the script on server01? Does that user have permissions on server02 too? If your user has admin permission on server01 and server02 then no credentials are neccessary... (as far as I know)
To check if the provided credentials are valid have a look here:
https://gallery.technet.microsoft.com/scriptcenter/Test-Credential-dda902c6
Or something like this:
$cred = Get-Credential #Read credentials
$username = $cred.username
$password = $cred.GetNetworkCredential().password
# Get current domain using logged-on user's credentials
$CurrentDomain = "LDAP://" + ([ADSI]"").distinguishedName
$domain = New-Object System.DirectoryServices.DirectoryEntry($CurrentDomain,$UserName,$Password)
if ($domain.name -eq $null)
{
write-host "Authentication failed - please verify your username and password."
exit #terminate the script.
}
else
{
write-host "Successfully authenticated with domain $domain.name"
}
Which was found here (but I haven't tested it):
https://serverfault.com/questions/276098/check-if-user-password-input-is-valid-in-powershell-script

Connecting to multiple servers through PowerShell

I'm trying to make a script, or just find a way, to use a .txt file that has a list of servers, and go through the list connected to each, or try to connect to each to see which servers belong to me. If I can connect, they're mine, if not then I need to send that server name to a file. There are 600+ servers so I can't enter credentials and have been trying to find a way using New-SSHSession that doesn't ask for -Username or -Password. What I have so far is below, I've just started PowerShell so my knowledge is limited, what you see is what I've been trying to get working before finally coming here.
#$pass = Get-Content C:\securestring.txt | ConvertTo-SecureString
$pass = Read-Host -AsSecureString "Enter Password"
$pass2 = [Runtime.InteropServices.Marshal]::PtrToStringAuto(
[Runtime.InteropServices.Marshal]::SecureStringToBSTR($pass))
ForEach ($cname in Get-Content "C:\testingconnections\testconnect.txt")
{
New-SshSession -ComputerName $cname -Username $env:USERNAME -Password $pass2 *>> 'C:\testingconnections\error.txt'
Remove-SshSession $cname
}

Looping through all my domains an changing pwd- access denied SET-QADUSER

I have several domains and one admin account in each one. It is a great pain to log into each domain to change password every month..
I have therefore written a script that will connect to all domains and check to see if I have already changed the password or if I am still using the old one.
If I am using the old one the script should update it.
I connect to the domains (sequentially) with
$oldPassword = Read-Host "Enter old password" -AsSecureString
$newPassword = Read-Host "Enter new password" -AsSecureString
$oldCredentials = new-object -typename System.Management.Automation.PSCredential -argumentlist "$domain\$adminusername",$oldPassword
Connect-QADService -Service $domain -Credential $oldCredentials
and if I get a successfull connection with $oldcredentials I try to change pwd with
GET-QADUSER $adminusername | SET-QADUSER -UserPassword $newPassword
I am guessing that I am not passing the secure string correctly to SET-QADUSER but I've found no documentation on another way to do it.
Please advice:)
SET-QADUSER -UserPassword accept [string] type not [System.Security.SecureString].
Try to pass just a string as password.