How to connect to remote server using powershell - powershell

I am trying to connect to a remote server but getting the following error
[my ip] Connecting to remote server "my ip" failed with the following error message : The WinRM client cannot process the request. Default authentication may be used with an IP address under the following conditions: the transport is HTTPS or the destination is in the TrustedHosts list, and explicit credentials are provided. Use winrm.cmd to configure TrustedHosts. Note that computers in the TrustedHosts list might not be authenticated. For more information on how to set TrustedHosts run the following command: winrm help config. For more information, see the about_Remote_Troubleshooting Help topic.
CategoryInfo : OpenError: (my ip:String) [], PSRemotingTransportException
FullyQualifiedErrorId : CannotUseIPAddress,PSSessionStateBroken
I am using this command to run a PowerShell script from my local machine on a remote PC
This is my script
$serverName = 'my ip'
$pwd = convertto-securestring "password12" -asplaintext -force
$cred=new-object -typename System.Management.Automation.PSCredential -argumentlist
".\Administrator",$pwd
Invoke-Command -computername $serverName {$("C:\_Projects\test.ps1")}
Edit:
my local pc and remote computer are not on the same domain . for example my local pc says mypc.test.local and remote computer says workgroup. Can some one help how to sort the above error by not changing the settings on remote computer, because its a UAT server.

You need to add -credential $cred to your Invoke-command command. You may also need to remove the .\ from the Administrator name--I don't have a workgroup server to test with, so I can't be sure if that will work.
Invoke-Command -credential $cred -computername $serverName {$("C:\_Projects\test.ps1")}

Related

Remote Execution of a PowerShell script results in "The WinRM client cannot process the request. [...] HTTPS transport must be used [...]"

I have written a PowerShell script which uninstall a program and install a newer version of the program on my servers (Update Programs). Now I want to create another script which run the aforementioned script on the servers. Consider that I have to connect to my servers through using IPs, UserName and password and using domain is not an option.
How is this possible?
PowerShell version is 4
I have tried this code to simply get date:
$User = "administrator"
$PWord = ConvertTo-SecureString -String "Password1234" -AsPlainText -Force
$Credential = New-Object -TypeName "System.Management.Automation.PSCredential" -ArgumentList $User, $PWord
$session = New-PSSession -ComputerName '10.60.60.100' -Credential $Credential
Invoke-Command -Session $session -ScriptBlock {Get-Date}
and I got this error:
New-PSSession : [10.60.60.100] Connecting to remote server 10.60.60.100 failed with the following error message : The WinRM client cannot process the request. If the authentication scheme is different from Kerberos, or if the client computer is not joined to a domain, then HTTPS transport must be used or the destination machine must be added to the TrustedHosts configuration setting. Use winrm.cmd to configure TrustedHosts. Note that computers in the TrustedHosts list might not be authenticated. You can get more information about that by running the following command: winrm help config. For more information, see the about_Remote_Troubleshooting Help topic.
This is because you’re not running your command from a trusted host, or because the remote computers wsman service isn’t configured properly. I’d start by running the following command to configure wsman on the remote machine:
wsman quickconfig
If that doesn’t fix the problem, then you need to add your computer to the remote machines trusted hosts. You can do that by running the following:
winrm s winrm/config/client '#{TrustedHosts="RemoteComputer"}'

Using Powershell to remotely invoke commands in Azure

I'm writing a series of automation scripts that will allow our developers to stand up a simple development environment in Azure. This environment has 3 primary properties:
There is a client machine (Windows 10) where dev tools like their IDE and code will live.
There is a server machine (Windows Server 2016) where that their scripts will target.
Both of these machines live in the same domain, and 1 Domain Admin user is available for use.
I have steps 1 and 2 scripted out, but 3 is currently a mess. Since the script is designed to work from the Developer's local workstation, I need to have the script remote in to the Windows Server and run a few commands to set up the Domain Controller.
Here is my code currently:
Invoke-Command -ComputerName "$RGName-$VMPurpose" -ScriptBlock
{
$ADFeature = Install-WindowsFeature AD-Domain-Services
If ($ADFeature.Success -eq $true)
{
Import-Module ADDSDeployment
Install-ADDSForest -CreateDnsDelegation:$false -DatabasePath
"C:\Windows\NTDS" -DomainMode "Win2016R2" -DomainName "$project.com" -
DomainNetbiosName "$project" -ForestMode "Win2016R2" -InstallDns:$true -
LogPath "C:\Windows\NTDS" -NoRebootOnCompletion $false -sysvolpath
"C:\Windows\SYSVOL" -force $true
$domUserPassword = ConvertTo-SecureString "Th1s is a bad password" -
AsPlainText -Force
New-ADUser -Name "$VMPurpose-DomAdm" -AccountPassword
$domUserPassword
Add-ADGroupMember -Name "Administrators" -Member {Get-ADUser
"$VMPurpose-DomAdm"}
}
} -Credential $Cred
When I attempt to run this I get an error showing that WinRM cannot connect, specifically this error:
[Foo] Connecting to remote server Foo failed with the following error
message : WinRM cannot process the request. The following error with
errorcode 0x80090311
occurred while using Kerberos authentication: There are currently no logon
servers available to service the logon request.
Possible causes are:
-The user name or password specified are invalid.
-Kerberos is used when no authentication method and no user name are
specified.
-Kerberos accepts domain user names, but not local user names.
-The Service Principal Name (SPN) for the remote computer name and port
does not exist.
-The client and remote computers are in different domains and there is no
trust between the two domains.
After checking for the above issues, try the following:
-Check the Event Viewer for events related to authentication.
-Change the authentication method; add the destination computer to the
WinRM TrustedHosts configuration setting or use HTTPS transport.
Note that computers in the TrustedHosts list might not be authenticated.
-For more information about WinRM configuration, run the following
command: winrm help config. For more information, see the
about_Remote_Troubleshooting Help topic.
+ CategoryInfo : OpenError: (Foo:String) [],
PSRemotingTransportException
+ FullyQualifiedErrorId : AuthenticationFailed,PSSessionStateBroken
I added the target machine (Foo) to the TrustedHosts configuration setting in WinRM (I actually added the IP address to make sure that there wasn't any DNS problem happening), and then I get this error:
[Foo's IP] Connecting to remote server <Foo's IP> failed with the following
error message : WinRM cannot complete the operation. Verify that the
specified computer name is valid, that the
computer is accessible over the network, and that a firewall exception for
the WinRM service is enabled and allows access from this computer. By
default, the WinRM firewall exception for public
profiles limits access to remote computers within the same local subnet. For
more information, see the about_Remote_Troubleshooting Help topic.
+ CategoryInfo : OpenError: (Foo's Ip[:String) [],
PSRemotingTransportException
+ FullyQualifiedErrorId : WinRMOperationTimeout,PSSessionStateBroken
Any thoughts here? Am what I trying simply not ever going to work via Powershell?
According to your error message, we can use this PowerShell script to invoke command to Azure:
$username = 'jason'
$pass = ConvertTo-SecureString -string 'password' -AsPlainText -Force
$cred = New-Object -typename System.Management.Automation.PSCredential -argumentlist $username, $pass
$s = New-PSSession -ConnectionUri 'http://23.99.82.2:5985' -Credential $cred -SessionOption (New-PSSessionOption -SkipCACheck -SkipCNCheck -SkipRevocationCheck)
Invoke-Command -Session $s -ScriptBlock {Get-Process PowerShell}
PowerShell result like this:
More information about invoke command, please refer to this answer.

New-PSSession - Connecting to remote server failed

I have two Windows 7 Pro systems, one host system and one in a VM one the host system. I am trying to create a New PSSession on the host system to control the guest, both of which run Powershell 4.0.
As we have a DHCP setup in the office the first thing I do is establish the IP adress of each. Then I run the code below on both machines -
Set-Item wsman:\localhost\client\trustedhosts "$relevantIP" -Force
I then test that the systems are ready using WSMan on the host -
Test-WSMan $remoteIP
wsmid : http://schemas.dmtf.org/wbem/wsman/identity/1/wsmanidentity.xsd
ProtocolVersion : http://schemas.dmtf.org/wbem/wsman/1/wsman.xsd
ProductVendor : Microsoft Corporation
ProductVersion : OS: 0.0.0 SP: 0.0 Stack: 3.0
All this works perfectly well. At this point I used to create a new PSSession using the following
$credObject =
$Host.ui.PromptForCredential(
"Need credentials",
"Please enter password for the following IP $remoteIP",
$remoteUsername,
""
)
$remoteSession = New-PSSession -ComputerName $remoteIP -Credential $credObject
New-PSSession : [10.141.114.91] Connecting to remote server
10.141.114.91 failed with the following error message : The WinRM client cannot process the request. Default authentication may be used
with an IP address under the following conditions: the transport is
HTTPS or the destination is in the TrustedHosts list, and explicit
credentials are provided. Use winrm.cmd to configure TrustedHosts.
Note that computers in the TrustedHosts list might not be
authenticated. For more information on how to set TrustedHosts run
the following command: winrm help config. For more information, see
the about_Remote_Troubleshooting Help topic. At line:1 char:18
+ $remoteSession = New-PSSession -ComputerName "10.141.114.91" -Credential "SESA40 ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : OpenError: (System.Manageme....RemoteRunspace:RemoteRunspace) [New-PSSession],
PSRemotingTransportException
+ FullyQualifiedErrorId : CannotUseIPAddress,PSSessionOpenFailed
I have no idea why it has started doing this when trying to connect to the VM from the host system. I can create a new PSSession on the host machine from within the guest but no longer the other way around.
The error message says that "Default
authentication may be used with an IP address under the following conditions: ... the destination is in the TrustedHosts list and explicit credentials are provided." I have already added the correspoding IP to each WSMan TrustedHosts fields and provide explicit credentials.
Any help would be greatly appreciated as I am scratching my head trying to think of what could be wrong.
Update
After following the suggestion of one commentor I tried using different authentification methods.
$remoteSession = New-PSSession -ComputerName "10.141.114.91" -Credential "Test" -ErrorAction Stop -Authentication Basic
The WinRM client cannot process the request. Unencrypted traffic is currently
disabled in the client configuration. Change the client configuration and try the request again.
So I ran set-item WSMan:\localhost\Client\allowunencrypted $true on both machines. Now trying to get a PSSession gives the error
Get-PSSession -ComputerName "10.141.114.91" -Credential "Test" -Authentication Basic
The WinRM client cannot process the request. If the authentication scheme is
different from Kerberos, or if the client computer is not joined to a domain, then HTTPS transport must be used or the destination machine must be added to the TrustedHosts configuration setting.
** Update 2 **
In case anyone has the same problem and comes across this - my problem turned out to be a combination of a network fault and then with my playing around somehow creating a list of IP addresses for wsman:\localhost\client\trustedhosts which missed a comma between IP's.

Cannot create remote powershell session after Enable-PSRemoting

I can not remote into any machine to save my life! I have tried everything I can find. If anyone could troubleshoot or guide me, I'd appreciate it as this would be a great tool to add on my domain.
SETUP:
Client machine inside domain
Server machine inside or outside domain - Virtualized and utilized for WSUS Computername: wsustest
CLIENT SERVER MACHINE physical- computername: epizzi-pc
STEPS:
enable-pssremoting done! on all machines
trustedhosts configured with * or client machine added
Firewalls with public profile off just in case
Enter-PSSession -ComputerName wsustest -Credential wsustest\administrator
Enter-PSSession -ComputerName epizzi-pc -Credential epizzi-pc\administrador
Enter-PSSession : Connecting to remote server epizzi-pc failed with the following error message : WinRM cannot process the request. The following error with errorcode 0x80090311
occurred while using Kerberos authentication: There are currently no logon servers available to service the logon request.
Possible causes are:
-The user name or password specified are invalid.
-Kerberos is used when no authentication method and no user name are specified.
-Kerberos accepts domain user names, but not local user names.
-The Service Principal Name (SPN) for the remote computer name and port does not exist.
-The client and remote computers are in different domains and there is no trust between the two domains.
After checking for the above issues, try the following:
-Check the Event Viewer for events related to authentication.
-Change the authentication method; add the destination computer to the WinRM TrustedHosts configuration setting or use HTTPS transport.
Note that computers in the TrustedHosts list might not be authenticated.
-For more information about WinRM configuration, run the following command: winrm help config. For more information, see the about_Remote_Troubleshooting Help topic.
At line:1 char:1
+ Enter-PSSession -ComputerName epizzi-pc -Credential epizzi-pc\administrador
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidArgument: (epizzi-pc:String) [Enter-PSSession], PSRemotingTransportException
+ FullyQualifiedErrorId : CreateRemoteRunspaceFailed
Enter-PSSession -ComputerName wsustest -UseSSL -Credential wsustest\administrator
*Enter-PSSession : Connecting to remote server wsustest failed with the following error message : WinRM cannot complete the operation. Verify that the specified computer name is
valid, that the computer is accessible over the network, and that a firewall exception for the WinRM service is enabled and allows access from this computer. By default, the WinRM
firewall exception for public profiles limits access to remote computers within the same local subnet. For more information, see the about_Remote_Troubleshooting Help topic.
At line:1 char:1
+ Enter-PSSession -ComputerName wsustest -UseSSL -Credential wsustest\administrato ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidArgument: (wsustest:String) [Enter-PSSession], PSRemotingTransportException
+ FullyQualifiedErrorId : CreateRemoteRunspaceFailed*
ERRORs:
I was receiving the same problem when remoting to a server and found this blog post very helpful - http://jeffgraves.me/2013/10/14/powershell-remoting/
For my specific case I did the following:
On the Local machine
winrm quickconfig (although this was already configured)
winrm s winrm/config/client '#{TrustedHosts="myservername.domain"}'
On the Remote machine
enable-psremoting -force
Set-PSSessionConfiguration -ShowSecurityDescriptorUI -Name Microsoft.PowerShell -Force
I got around this problem by using a fully qualified logon. Instead of "netbiosdomain\accountname", I used fqdn\accountname, as in Microsoft.com\myaccount in the get-credential prompt. May not work for everyone, but it's worth a shot.
This is how I do it. I use this on my scripts.
# This is only done once
Read-Host -AsSecureString | ConvertFrom-SecureString | Out-File
c:\Windows\temp\securepass.txt
# Setup credentials
$SecureString = Get-Content c:\Windows\temp\securepass.txt | ConvertTo-SecureString
$mycredentials = New-Object -TypeName System.Management.Automation.PSCredential
-ArgumentList "yourDomain\userID",$SecureString
# Open remote session:
$MyRSession = New-PSSession -ComputerName Computer1 -Credential $mycredentials
-Authentication default
# Use remote session:
Enter-PSSession $MyRSession
Get rid of -UseSSL. I enabled PSRemoting and had problems with using that. I guess I could look at it later but for now it doesn't matter.
If there is no trust between the client and server computers, you have to enable basic authentication on the server side. Do this by toggling the correct properties on the WSMAN: drive on the server. You'll obviously have to do this interactively on the console or via remote desktop, due to the chicken and egg problem :) Also, this may come into play too:
http://www.nivot.org/blog/post/2009/10/30/PowerShell20EnablingRemotingWithVirtualXPModeOnWindows7
I was getting that same error currently no logon servers available.
The issue was resolved by using instead of Domain\Username as credentials the user UPN or Username#Domain.
I have achieved a remote session with Enter-pssession command, had to follow these exact parameters
$creds = get-credential (the -credential parameter in enter-pssession does not work properly, thus u must previously enter the object at another variable)
Enter-pssession -computername wsustest -authentication Default -credentials $creds
i Also had to set both client and remote server in the trusted hosts wsman: space
another solution which surely wouldve worked but i havent tried, wouldve been setting https: which is harder to do.
thx to all, your comments certainly led to the solution!

Unable to use PowerShell Enter-PSSession to connect to remote server

I am having problems connecting to a remote server using PowerShell where the remote machine uses a non-default port number. The setup is as follows: I have a virtual host server with several virtual machines. All of these virtual machines have the same IP address but are accessed with a different port, for example:
a.b.c.d:3000
a.b.c.d:3001
etc
So, the PowerShell script I have so far is:
$password = ConvertTo-SecureString "<MyPassword>" -AsPlainText -Force
$cred= New-Object System.Management.Automation.PSCredential ("<Domain\UserName>", $password)
Enter-PSSession -ComputerName <IPAddress> -Port <PortNumber> -Credential $cred
The bits inside the "<>" are specific to the individual machines. When running this script I get the following error:
Enter-PSSession : Connecting to remote server failed
with the following error message : The client cannot connect to the
destination specified in the request. Verify that the service on the
destination is running and is accepting requests. Consult the logs and
documentation for the WS- Management service running on the
destination, most commonly IIS or WinRM. If the destination is the
WinRM service, run the following command o n the destination to
analyze and configure the WinRM service: "winrm quickconfig". For more
information, see the about_Remote_Troubleshooting H elp topic. At
C:\PowerShell\Test7.ps1:25 char:16
+ Enter-PSSession <<<< -ComputerName -Port -Credential $cred
+ CategoryInfo : InvalidArgument: (:String) [Enter-PSSession], PSRemotingTransportException
+ FullyQualifiedErrorId : CreateRemoteRunspaceFailed
Another variant I tried is as follows:
$password = ConvertTo-SecureString "<MyPassword>" -AsPlainText -Force
$cred= New-Object System.Management.Automation.PSCredential ("<Domain\UserName>", $password)
$powershell_uri = "http://<IPAddress>:<PortNumber>"
Enter-PSSession -ConnectionUri $powershell_uri -Credential $cred
but this gave the following error:
Enter-PSSession : Connecting to remote server failed with the
following error message : The client cannot connect to the destination
specified in the request. Verify that the service on the destination
is running and is accepting requests. Consult the logs and
documentation for the WS- Management service running on the
destination, most commonly IIS or WinRM. If the destination is the
WinRM service, run the following command o n the destination to
analyze and configure the WinRM service: "winrm quickconfig". For more
information, see the about_Remote_Troubleshooting H elp topic. At
C:\PowerShell\Test7.ps1:21 char:16
+ Enter-PSSession <<<< -ConnectionUri $powershell_uri -Credential $cred # -ComputerName -Port -Credential
$cred
+ CategoryInfo : InvalidArgument: (http://:/:Uri) [Enter-PSSession],
PSRemotingTransportException
+ FullyQualifiedErrorId : CreateRemoteRunspaceFailed
I have set the TrustedHosts on my local machine (winrm set winrm/config/client #{TrustedHosts=""}) and on the remote machine I have run the "winrm quickconfig" command. On the remote machine I have also run the "winrm create winrm/config/listener?Address=*+Transport=HTTP #{Port=""}" command.
Any assistance on how I can establish a connection within PowerShell to these machines would be greatly appreciated.
On the remote computer:
In: Control Panel\Network and Internet\Network and Sharing CenterMake sure the remote computer is not in the public location, but set it to work or private
Start PowerShell in administrator mode and enter the command:
Enable-PSRemoting
exit
Goto Control Panel -> System and Security ->Windows Firewall and click advanced Settings
Add the ip-range of your managing computer to windows remote management(http-In) both in the private and in the domain inbound rules.
On the managing computer:
Start PowerShell in administrator mode and enter the command:
Set-Item WSMan:\localhost\Client\TrustedHosts -Concatenate remotecomputer.domain.suffix -Force
using your complete remote computer's network path.
This adds the remote computer network name to your trusted hosts.
That should do the trick.