I am trying to write a powershell script that opens a remote desktop connection for each machine name saved in a text file. When I run the script, it only connects to the first machine in the list and outputs to the console: CMDKEY: Credential added successfully once (not once for each machine). mstcs seems to terminate the process after executing, and I'm not sure I'm adding credentials the right way. Can anyone point me in the right direction?
Here are some tests I've tried to figure out what's going on:
- Print after
mstsc. Doesn't print. Process seems to terminate aftermstcsis called. This seems to be the crux of the issue. cmdkey /listshows all the credentials I have stored and their targets. The output does not include all the targets defined in the text file. Even if I comment outmstsc, thencmdkey /add:$MachineName /user:$User /pass:$Passwordonly seems to execute for the first line, evidenced by the lack of more console outputs andcmdkey /listnot yielding the expected targets. In addition, I have added a print statement after thiscmdkeyline and it prints for each line, so it doesn't terminate after running (which I already knew becausemstcsexecutes after this line when it's not commented out).
# Read from file
$Lines = Get-Content -Path .\machines.txt | Out-String
# For each machine ...
foreach($Line in $Lines){
# Split line, save name and domain
$Tokens = $Line.Split(".")
$MachineName = $Tokens[0]
$Domain = $Tokens[1]
$User = "someDomain\someUsername"
$Password="somePassword"
# Switch username if someOtherDomain
if ($Domain -eq "someOtherDomain"){
$User = "someOtherDomain\someOtherUsername"
}
#set credentials and open connection
cmdkey /add:$MachineName /user:$User /pass:$Password
mstsc /v:$MachineName /console
}
EDIT: I have also tried replacing mstsc /v:$MachineName with Start-Process -FilePath "$env:windir\system32\mstsc.exe" -ArgumentList "/v:$MachineName" -Wait. The result is opening the session and then the script does not finish in the console but nothing additional happens.
This behavior is cause by your use of
Out-String.Get-Contentoutputs multiple strings, one per line in the file - butOut-Stringstitches them back together into a single multi-line string:So your
foreach(){}loop only runs once, and the value of$MachineNameis no longer the name of a single machine, but a multi-line string with all of them at once - which is probably whymstscexits immediately :)Remove
|Out-Stringfrom the first line and your loop will work