Trying to do mstsc remotely using powershell doesn't work - powershell

I have two server as X and Y. I have a powershell script that I am using for having a remote desktop of X on Y. The powershell script that I have to run on Y is --
$hostname = 'X'
$User = 'u-name'
$Password = 'password'
$ProcessInfo = New-Object System.Diagnostics.ProcessStartInfo
$Process = New-Object System.Diagnostics.Process
$ProcessInfo.FileName = "$($env:SystemRoot)\system32\cmdkey.exe"
$ProcessInfo.Arguments = "/generic:TERMSRV/$hostname /user:$User /pass:$Password"
$Process.StartInfo = $ProcessInfo
$Process.Start()
$ProcessInfo.FileName = "$($env:SystemRoot)\system32\mstsc.exe"
$ProcessInfo.Arguments = "$MstscArguments /v $hostname"
$Process.StartInfo = $ProcessInfo
$Process.Start()
When I run this script locally on Y, it does run and opens the server X in Y.
But I want to trigger it from X only to open X in Y. So I Invoke this powershell script from X as --
$pass = ConvertTo-SecureString -AsPlainText test-password -Force
$cred = New-Object System.Management.Automation.PSCredential -ArgumentList test-uname,$pass
$hostn = hostname
$Use = 'u-name'
$Pass = 'password'
Write-Host "$hostname"
$ScriptBlockContent={
Param ($hostname,$User,$Password)
E:\Script\test.ps1 $hostname $User $Password}
Invoke-Command -ComputerName Y -Credential $cred -Scriptblock $ScriptBlockContent -ArgumentList $hostn,$Use,$Pass
When I am invoking this. It does open mstsc.exe on Y but only for some fraction of seconds and doesn't open the server X on Y. Can somebody please help.. !!
Thanks.

You are trying to launch an application with a GUI in a remote powershell session which has no desktop/display. Even if you use the credentials of a logged in user, the things you launch through Invoke-Command will not be visible to the logged-in user's session.
I think that this is possible with PsExec.exe, but I can't confirm.

Related

Powershell to server finishes but waits a minute before finish

So I use this very simple script (in this case) and script is done in cca 10 seconds, but then it just waits for more than a minute and then finishes
Here is the printscreen of script run locally where script runs for more than a minute
Script local
And here is it on the server, run by same user, and same credentials where script runs around 2 seconds
Script on server
Does anyone have an idea why or what can I do?
$Username = 'xxxxxxx'
$Password = 'xxxxxxx'
$pass = ConvertTo-SecureString -AsPlainText $Password -Force
$Cred = New-Object System.Management.Automation.PSCredential -ArgumentList $Username,$pass
Write-Output 'Start:'
Get-Date
Write-Output 'Server:'
Invoke-Command -ComputerName xxxxxxx.xxx.xxx.xxx-ScriptBlock { Get-Date } -credential $Cred
Write-Output 'Finish:'
Get-Date
Thanks
David V.

PowerShell Install .exe application with Credentials stored in Clixml

Trying to create a Powershell script that installs an application (.exe) with stored credentials (Clixml).
Everything works fine when using:
Start-Process -FilePath "C:\Users\$($env:USERNAME)\Downloads\Software\Software.exe" -ArgumentList '/s' -Credential $credentials
But I would like a more elegant solution:
$startprocessParams = #{
FilePath = "C:\Users\$($env:USERNAME)\Downloads\Software\Software.exe"
ArgumentList = '/s'
Credential = $credentials
Verb = 'RunAs'
PassThru = $true
Wait = $true
}
$proc = Start-Process #startprocessParams
if ($proc.ExitCode -eq 0) {
'Software installed!'
}
else {
"Fail! Exit code: $($Proc.ExitCode)"
}
This works perfectly without the Credential parameter, you then get the "enter credentials/UAC" popup that I would like to avoid. With the Credential parameter I get this error:
Start-Process : Parameter set cannot be resolved using the specified name parameters.
What am I missing here? Appreciate any advice and/or guidance.
EDIT:
I use the following line to import the credentials:
$credentials = Import-Clixml "C:\Users\$Env:USERNAME\AppData\Local\Apps\SOFTWARE\cred.xml"
The credentials is created with a standard:
Get-Credential | Export-Clixml "C:\Users\$Env:USERNAME\AppData\Local\Apps\SOFTWARE\cred.xml"
This works as it should.
you need to set the credentials as PSCredential.
have a look at this solution:
$username = "username"
$password = "password"
$credentials = New-Object System.Management.Automation.PSCredential -ArgumentList #($username,(ConvertTo-SecureString -String $password -AsPlainText -Force))
Start-Process dnscrypt-proxy.exe -WorkingDirectory path_here -Credential ($credentials)
is it stored in PSCredential in the first place?
Start-Process : Parameter set cannot be resolved using the specified name parameters.
The error tells us the set of parameters used is incorrect. Checking the MSDN doc or Get-Help for Start-Process will show that -Credential can not be used with -Verb.

How to run Command as a different user with Powershell?

I'm trying to make a script that changes the HostnameAlias for a given dns record.
But only certain users have access to editing these records, for example ADMIN can edit it but CURRENTUSER cannot.
Currently I have this piece of code:
param(
[ValidateNotNull()]
[System.Management.Automation.PSCredential]
$Credential = $(Get-Credential)
)
$Command = "Set-DnsServerResourceRecord -NewInputObject $($NewObject) -OldInputObject $($OldObject) -ZoneName $($ZoneName)"
Start-Process -FilePath PowerShell -NoNewWindow -Credential $Credential -ArgumentList $Command
But i just keep getting Start-Process : This command cannot be run due to the error: The user name or password is incorrect even though I am absolutely sure they are indeed correct.
What am I doing wrong here.
Ps, I have looked at all the related questions, none seem to answer my question.
You can call System.Management.Automation.PSCredential object to specify any credentials you want and run with it in any process
$User = 'yourdomain\youruser'
$Password = 'yourpassword'
$Secure_Password = ConvertTo-SecureString $Password -AsPlainText -Force
$Credential = New-Object System.Management.Automation.PSCredential($User, $Secure_Password)
$Command = "Set-DnsServerResourceRecord -NewInputObject $($NewObject) -OldInputObject $($OldObject) -ZoneName $($ZoneName)"
Start-Process -FilePath PowerShell -NoNewWindow -Credential $Credential -ArgumentList $Command
You can use this:
#Get User credential
$Credential = Get-Credential Domain\UserNameYouWant
#Use System.Diagnostics to start the process as User
$ProcessInfo = New-Object System.Diagnostics.ProcessStartInfo
#With FileName we're basically telling powershell to run another powershell process
$ProcessInfo.FileName = "powershell.exe"
#CreateNoWindow helps avoiding a second window to appear whilst the process runs
$ProcessInfo.CreateNoWindow = $true
#Note the line below contains the Working Directory where the script will start from
$ProcessInfo.WorkingDirectory = $env:windir
$ProcessInfo.RedirectStandardError = $true
$ProcessInfo.RedirectStandardOutput = $true
$ProcessInfo.UseShellExecute = $false
#The line below is basically the command you want to run and it's passed as text, as an argument
$ProcessInfo.Arguments = "The command you want"
#The next 3 lines are the credential for User as you can see, we can't just pass $Credential
$ProcessInfo.Username = $Credential.GetNetworkCredential().username
$ProcessInfo.Domain = $Credential.GetNetworkCredential().Domain
$ProcessInfo.Password = $Credential.Password
#Finally start the process and wait for it to finish
$Process = New-Object System.Diagnostics.Process
$Process.StartInfo = $ProcessInfo
$Process.Start() | Out-Null
$Process.WaitForExit()
#Grab the output
$GetProcessResult = $Process.StandardOutput.ReadToEnd()
# Print the Job results
$GetProcessResult
Just a mistake on my part, forgot to specify domain before username when entering credentials.
Can solve it like this Get-Credential Domain\

Run code as different user to have elevated privileges

I'm deploying a monitoring system, and even though it has a large number of plugins, some need to run as a different user to run right.
So I switched to powershell, but the problem is the same, I have some code that give me access denied, because the user has no elevated privileges.
My question how can I run this code as different user, I tried this
$usuario = "myuser#mydomain"
$pass = get-content C:\credential.txt`
$spass = $pass | Convertto-SecureString`
pass = "securepass"`
spass = $pass | ConvertTo-SecureString -AsPlainText -Force`
write-host $pass
$cred = new-object System.Management.Automation.PSCredential -argumentlist $usuario, $spass
$UpdateSession = New-Object -ComObject Microsoft.Update.Session
$UpdateSearcher = ($UpdateSession.CreateupdateSearcher())
$Updates = $UpdateSearcher.Search("IsAssigned=1 and IsHidden=0 and IsInstalled=0").updates
$total = $Updates | measure
$total.count
Then how can I pass the credentials to the variables. The problem access denied come from this line
$Updates = $UpdateSearcher.Search("IsAssigned=1 and IsHidden=0").updates
$args = ' -file path-to-script.ps1'
Start-Process -FilePath powershell.exe -Credential $creds -ArgumentList $args -Verb RunAs
Powershell also has -Command which you can use to call a function or cmdlet instead of another script.

Powershell Invoke-Command executing on local, rather than remote server

I have a script that copies another script to a remote server then executes the 2nd script. This was working ok last week but today execution of the first script failed saying the 2nd script couldn't be found. As part of troubleshooting I created a simple version of the 2nd script (containing only Write-Host "Wrong Server!) on the local server. Now when I run the 1st script, the dummy 2nd script is executed on the local server!
I have pasted by test-harness script below:
$DeploymentFolderOnTargetServer = "c:\biztalkdeployment"
$TargetServer = "d-vasbiz01"
$Username = "TFS_Service"
$Password = "x"
$SecPass = ConvertTo-SecureString $Password -AsPlainText -Force
$Cred = New-Object -typename System.Management.Automation.PSCredential -argumentlist $Username,$SecPass
$Session = New-PSSession -ComputerName $TargetServer -Authentication CredSSP -Credential $Cred
$Environment = "Dev"
$ExecuteScriptFilePath = join-path "$DeploymentFolderOnTargetServer" "ExecuteBizTalkAppMSI.ps1"
$MSI = "bin\debug\x.int.mis-3.0.0.msi"
$InstallFolderOnTargetServer = "C:\Program Files (x86)\x.Int.MIS for BizTalk 2010\3.0"
Write-Host "Session = $Session"
Write-Host "ExecuteScriptFilePath = $ExecuteScriptFilePath"
Write-Host "MSI = $MSI"
Write-Host "InstallFolderOnTargetServer = $InstallFolderOnTargetServer"
Write-Host "Environment = $Environment"
Write-Host "DeploymentFolderOnTargetServer = $DeploymentFolderOnTargetServer"
Invoke-Command -Session $Session -FilePath $ExecuteScriptFilePath -argumentlist $MSI, $InstallFolderOnTargetServer, $Environment, $DeploymentFolderOnTargetServer
The output from the test is as follows:
Session = System.Management.Automation.Runspaces.PSSession
ExecuteScriptFilePath = c:\biztalkdeployment\ExecuteBizTalkAppMSI.ps1
MSI = bin\debug\x.int.mis-3.0.0.msi
InstallFolderOnTargetServer = C:\Program Files (x86)\Vasanta.Int.MIS for BizTalk 2010\3.0
Environment = Dev
DeploymentFolderOnTargetServer = c:\biztalkdeployment
Wrong Server!
If I run get-session then the Computer Name for the session is correctly pointing at the 2nd Server.
Any ideas?
The -FilePath parameter to Invoke-Command is specifying a local path to a script - not a path on the target computer. Invoke-Command will take care of getting the local script file over to the target computer so that it can execute there.