New-PSSession to localhost fails - powershell

I have a script that opens a remote session to the localhost.
I need this to install NuGet on some devices from within a logonscript.
$Username = "Admin"
$Password = ConvertTo-SecureString ‘adminPW’ -AsPlainText -Force
$adminCredential = New-Object System.Management.Automation.PSCredential $Username, $Password
$Session = New-PSSession -Credential $adminCredential
Invoke-Command -Session $Session -ScriptBlock {Install-PackageProvider -Name NuGet -Verbose -MinimumVersion 2.8.5.201 -Force}
Every time I try to run this I get the following error:
New-PSSession : [localhost] Connecting to remote server localhost 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 on the
destination to analyze and configure the WinRM service: "winrm quickconfig". For more information, see the about_Remote_Troubleshooting Help topic.
At C:\Users\Mike Holtackers\OneDrive - Foreign Trade Association\Scripts\OutlookSig\getAADconnectionOK.ps1:5 char:12
+ $Session = New-PSSession -ConnectionUri $ConnectionURI -Credential $a ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : OpenError: (System.Manageme....RemoteRunspace:RemoteRunspace) [New-PSSession], PSRemotingTransportException
+ FullyQualifiedErrorId : CannotConnect,PSSessionOpenFailed
Running winrm quickconfig does not change anything...
Following is the output of winrm get winrm/config
PS WSMan:\localhost\Listener\Listener_1084132640> winrm get winrm/config
Config
MaxEnvelopeSizekb = 500
MaxTimeoutms = 60000
MaxBatchItems = 32000
MaxProviderRequests = 4294967295
Client
NetworkDelayms = 5000
URLPrefix = wsman
AllowUnencrypted = false
Auth
Basic = true
Digest = true
Kerberos = true
Negotiate = true
Certificate = true
CredSSP = false
DefaultPorts
HTTP = 5985
HTTPS = 5986
TrustedHosts = *
Service
RootSDDL = O:NSG:BAD:P(A;;GA;;;BA)(A;;GR;;;IU)S:P(AU;FA;GA;;;WD)(AU;SA;GXGW;;;WD)
MaxConcurrentOperations = 4294967295
MaxConcurrentOperationsPerUser = 1500
EnumerationTimeoutms = 240000
MaxConnections = 300
MaxPacketRetrievalTimeSeconds = 120
AllowUnencrypted = false
Auth
Basic = false
Kerberos = true
Negotiate = true
Certificate = false
CredSSP = false
CbtHardeningLevel = Relaxed
DefaultPorts
HTTP = 5985
HTTPS = 5986
IPv4Filter = 194.168.254.1-194.168.254.256 [Source="GPO"]
IPv6Filter [Source="GPO"]
EnableCompatibilityHttpListener = false
EnableCompatibilityHttpsListener = false
CertificateThumbprint
AllowRemoteAccess = true [Source="GPO"]
Winrs
AllowRemoteShellAccess = true
IdleTimeout = 7200000
MaxConcurrentUsers = 2147483647
MaxShellRunTime = 2147483647
MaxProcessesPerShell = 2147483647
MaxMemoryPerShellMB = 2147483647
MaxShellsPerUser = 2147483647

Check if the winrm service is running on your localhost:
PS C:\> Get-Service winrm | ft -AutoSize
Status Name DisplayName
------ ---- -----------
Running winrm Windows Remote Management (WS-Management)
Otherwise PS remoting won't work, though you've configured via winrm and have enabled PS remoting via Enable-PSRemoting.

Issue was someone had tampered with the firewall... Thanx for the help guys!
Basically the firewall GPO was blocking remote management

Following worked in my case:
# NOTE: Following is set by Enable-PSRemoting, it prevents UAC and
# allows remote access to members of the Administrators group on the computer.
Set-ItemProperty -Name LocalAccountTokenFilterPolicy -Value 1 `
-Path HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\Policies\System
For more information about this setting see section in about_Remote_Troubleshooting

Related

NoServiceFoundForGivenName when stop another server's service with invoke-command

I have 2 windows server, Server1 (now 2019) and ServerUpdate (2012 R2)
On each server I have an admin user named: AdminUpdate with the same password.
Im currently switching my Server1 windows server 2012 R2 for a windows server 2019. The following powershell code was working #1 before the switch.
I try to run this powershell on ServerUpdate to stop aservice on Server1
# Obtient une instance du mot passe sécurisé
$passwordCred = ConvertTo-SecureString *SomePassword* -AsPlainText -Force
# Obtient les crédentials
$cred = New-Object -TypeName System.Management.Automation.PSCredential -ArgumentList AdminUpdate, $passwordCred
# Effectue le Stop sur le service
invoke-command -computerName *Server1Ip* -scriptBlock {
# Effectue le stop en local
Stop-Service -Name $args[0] -Force
} -credential $cred -ArgumentList *someServiceName*
For some reason I always got this error:
'*someServiceName*'.
+ CategoryInfo : ObjectNotFound: (*someServiceName*:String) [Stop-Service], ServiceCommandException
+ FullyQualifiedErrorId : NoServiceFoundForGivenName,Microsoft.PowerShell.
Commands.StopServiceCommand
+ PSComputerName : *Server1Ip*
But if i try directly this, its return the service
Get-Service -ComputerName *Server1Ip* -Name *someServiceName*
I have check this https://blog.netspi.com/powershell-remoting-cheatsheet/
I have the PSRemoting Enable
I put the sevice WinRM auto
I put my Server1 ip in the Trustedhosts on the ServerUpdate and same for the Server1, I put the ServerUpdate ip in the Trustedhosts
Did someone know why I got this error?

Remote Powershell session not loading assemblies

I have a powershell script file, that when executed via winrm, wont get executed correctly in some windows environment.
The below script executes fine in that machine.
$ssrsEndpoint = "http://192.168.10.1/ReportServer/ReportService2010.asmx?WSDL"
$ssrsProxy = New-WebServiceProxy -Uri $ssrsEndpoint -Credential (Get-Credential)
$ssrsProxy.CreateFolder("NewFolder", "/", $null)
but, if executed via powershell remoting, it fails. ("localhost" is coming from a variable, so i don't have control over it, if the admin choose to execute the script on the same machine, it becomes localhost. So please don't ask why I'm executing the script on local machine over winrm)
$iisSess = New-PSSession -ComputerName "localhost" -Credential (Get-Credential)
Invoke-Command -Session $iisSess -ScriptBlock { [void][system.Reflection.Assembly]::LoadWithPartialName("System.Net.WebClient") }
Invoke-Command -Session $iisSess -ScriptBlock { $ssrsEndpoint = "http://192.168.10.1/ReportServer/ReportService2010.asmx?WSDL" }
Invoke-Command -Session $iisSess -ScriptBlock { $ssrsProxy = New-WebServiceProxy -Uri $ssrsEndpoint -Credential (Get-Credential) }
Invoke-Command -Session $iisSess -ScriptBlock { $ssrsProxy.CreateFolder("NewFolder", "/", $null) }
`
+ CategoryInfo : ObjectNotFound: (http://192.168.10...e2010.asmx?WSDL:Uri) [New-WebServiceProxy], WebException
+ FullyQualifiedErrorId : WebException,Microsoft.PowerShell.Commands.NewWebServiceProxy
+ PSComputerName : localhost
You cannot call a method on a null-valued expression.
+ CategoryInfo : InvalidOperation: (:) [], RuntimeException
+ FullyQualifiedErrorId : InvokeMethodOnNull
+ PSComputerName : localhost
It looks like the session didn't get the proper assemblies loaded!
Any idea?
Environment
PS C:\deployments\> $PSVersionTable
Name Value
---- -----
PSVersion 5.1.14409.1005
PSEdition Desktop
PSCompatibleVersions {1.0, 2.0, 3.0, 4.0...}
BuildVersion 10.0.14409.1005
CLRVersion 4.0.30319.42000
WSManStackVersion 3.0
PSRemotingProtocolVersion 2.3
SerializationVersion 1.1.0.1
Pretty sure it is not the remoting configurations, see below the command running as a remote command.
[127.0.0.1]: PS C:\Users\Administrator\Documents> winrm get winrm/config
Config
MaxEnvelopeSizekb = 500
MaxTimeoutms = 60000
MaxBatchItems = 32000
MaxProviderRequests = 4294967295
Client
NetworkDelayms = 5000
URLPrefix = wsman
AllowUnencrypted = false
Auth
Basic = true
Digest = true
Kerberos = true
Negotiate = true
Certificate = true
CredSSP = false
DefaultPorts
HTTP = 5985
HTTPS = 5986
TrustedHosts = *
Service
RootSDDL = O:NSG:BAD:P(A;;GA;;;BA)(A;;GR;;;IU)S:P(AU;FA;GA;;;WD)(AU;SA;GXGW;;;WD)
MaxConcurrentOperations = 4294967295
MaxConcurrentOperationsPerUser = 1500
EnumerationTimeoutms = 240000
MaxConnections = 300
MaxPacketRetrievalTimeSeconds = 120
AllowUnencrypted = false
Auth
Basic = false
Kerberos = true
Negotiate = true
Certificate = false
CredSSP = false
CbtHardeningLevel = Relaxed
DefaultPorts
HTTP = 5985
HTTPS = 5986
IPv4Filter = *
IPv6Filter = *
EnableCompatibilityHttpListener = false
EnableCompatibilityHttpsListener = false
CertificateThumbprint
AllowRemoteAccess = true
Winrs
AllowRemoteShellAccess = true
IdleTimeout = 7200000
MaxConcurrentUsers = 2147483647
MaxShellRunTime = 2147483647
MaxProcessesPerShell = 2147483647
MaxMemoryPerShellMB = 2147483647
MaxShellsPerUser = 2147483647
[127.0.0.1]: PS C:\Users\Administrator\Documents>

Powershell RunAs Administrator in a SSIS Package

Am trying to remote connect to a server and run a powershell script to open ports in windows firewall in a SSIS Execute Process task
Here is the Powershell code:
$computername = hostname
$script = {
$FireWallRule_1 = Get-NetFirewallRule
$par1 = #{
DisplayName = "DAC"
LocalPort = 1434
Direction="Inbound"
Protocol ="TCP"
Action = "Allow"
}
$FireWallRule_2 = Get-NetFirewallRule
$par2 = #{
DisplayName = "MSSQLSERVER"
LocalPort = 1433
Direction="Inbound"
Protocol ="TCP"
Action = "Allow"
}
$par1.Localport = 1434
$par1.DisplayName = "DAC"
if (-not $FireWallRule_1.DisplayName.Contains($par1.DisplayName)) {New-NetFirewallRule #par1}
$par2.LocalPort = 1433
$par2.DisplayName = "MSSQLSERVER"
if (-not $FireWallRule_2.DisplayName.Contains($par2.DisplayName)) {New-NetFirewallRule #par2}
}
Invoke-Command -ScriptBlock $script -ComputerName $computername
Here is the error i got:
Connecting to remote server [SERVERNAME] failed with the following error message: Access is denied. For more information, see the
aboute_Remote_Troubleshooting Helptopic.
+ CategoryInfo : OpenError: (SERVERNAME:String) [], PSRemotingTransportException
+ FullyQualifiederrorId : AccessDenied, PSSessionStateBroken
I have tried to run the PS script locally and its working, the account that run ssis is local administrator on the target server. Is it possible to RunAs Administrator in a SSIS Package?
Thanks Håkan

Can not connect to remote pc with powershell

I connect from one computer to another remote computer with powershell.
For this to work I did some configuration on both computer according to this video:
https://technet.microsoft.com/en-us/itmanagement/ff765030.aspx
But still I get an error message when I try to do this on the local computer:
enter-pssession -comp remotePC -credential domain\username
Then I enter the password and hit enter.
I get this error:
Connecting to remote server LocalPC failed with the following error message :
The WS-Management service cannot process the request. The
service is configured to not accept any remote shell requests. For more
CategoryInfo : OpenError: (LocalPC:String) [], PSRemotingTrans
portException + FullyQualifiedErrorId : RemoteSessionDisallowed,PSSessionStateBroken
The "Windows Remote Management"-Service is started on the remote PC.
I totally disabled the firewall for test purpose totally on the remote PC.
I did also enable-psremoting and Set-Item WSMan:\localhost\Client\TrustedHosts *
When I execute on the remote PC:
winrm config it says:
WinRM service is already running on this machine.
WinRM is already set up for remote management on this computer.
What else of that 1000 things do I still have to enable that I can connect to my remote pc with powershell?
UPDATE
PS C:\Windows\system32> winrm get winrm/config/service
Service
RootSDDL = O:NSG:BAD:P(A;;GA;;;BA)(A;;GR;;;IU)S:P(AU;FA;GA;;;WD)(AU;SA;GXGW;;
MaxConcurrentOperations = 4294967295
MaxConcurrentOperationsPerUser = 1500
EnumerationTimeoutms = 240000
MaxConnections = 300
MaxPacketRetrievalTimeSeconds = 120
AllowUnencrypted = false
Auth
Basic = false
Kerberos = true
Negotiate = true
Certificate = false
CredSSP = false
CbtHardeningLevel = Relaxed
DefaultPorts
HTTP = 5985
HTTPS = 5986
IPv4Filter = *
IPv6Filter = *
EnableCompatibilityHttpListener = false
EnableCompatibilityHttpsListener = false
CertificateThumbprint
AllowRemoteAccess = true
PS C:\Windows\system32> winrm e winrm/config/listener
Listener
Address = *
Transport = HTTP
Port = 5985
Hostname
Enabled = true
URLPrefix = wsman
CertificateThumbprint
ListeningOn = xx.xx.xx.xx, 127.0.0.1, ::1, fe80::4c2c:a8d0:6046:764d%11
UPDATE 2
PS C:\Windows\system32> dir WSMan:\localhost\Shell\
WSManConfig: Microsoft.WSMan.Management\WSMan::localhost\Shell
Type Name SourceOfValue Value
---- ---- ------------- -----
System.String AllowRemoteShellAccess GPO false
System.String IdleTimeout 7200000
System.String MaxConcurrentUsers 10
System.String MaxShellRunTime 2147483647
System.String MaxProcessesPerShell 25
System.String MaxMemoryPerShellMB 1024
System.String MaxShellsPerUser 30
As you can see from dir WSMan:\localhost\Shell\ output:
Type Name SourceOfValue Value
---- ---- ------------- -----
System.String AllowRemoteShellAccess GPO false
WS-Management configuration property AllowRemoteShellAccess have value false with source GPO. That means: group policy applied to target computer does disallow remote shell access.

New-PSSession does not work locally

I am trying to connect to the localhost using New-PSSession.
I have
Configured WinRM using
winrm quickconfig
Enabled PS Remoting
Enable-PSRemoting
Added Trusted Host
Set-Item WSMan:\localhost\Client\TrustedHosts * -Force
There is an inbound rule on 8173 port on firewall.
Output of winrm:
PS C:\> winrm get winrm/config/listener?Address=*+Transport=HTTP
Listener
Address = *
Transport = HTTP
Port = 8173
Hostname
Enabled = true
URLPrefix = wsman
CertificateThumbprint
Listening on = 127.0.0.1
I am trying to run the following command:
New-PSSession -ConnectionUri http://localhost:8173/WSMAN
but I get this error:
[localhost] Processing data from remote server failed with the following error message:
Error with error code 14 occurred while calling method WSManPluginReceiveResult. For
more information, see the about_Remote_Troubleshooting Help topic.
+ CategoryInfo : OpenError: (System.Manageme....RemoteRunspace:RemoteRunspace) [], PSRemotingTransportException
+ FullyQualifiedErrorId : PSSessionOpenFailed
EDIT:
The only extra thing that I see is that the network is connected to public
$listenerport = "8173"
winrmwinrm create winrm/config/Listener?Address=*+Transport=HTTP "#{Port="$listenerport"}"
C:\>winrm get winrm/config
Config
MaxEnvelopeSizekb = 1039440
MaxTimeoutms = 60000
MaxBatchItems = 32000
MaxProviderRequests = 4294967295
Client
NetworkDelayms = 5000
URLPrefix = wsman
AllowUnencrypted = true
Auth
Basic = true
Digest = true
Kerberos = true
Negotiate = true
Certificate = true
CredSSP = false
DefaultPorts
HTTP = 8173
HTTPS = 5986
TrustedHosts = *
Service
RootSDDL = O:NSG:BAD:P(A;;GA;;;BA)(A;;GA;;;S-1-5-21-2458768215-3945602940-3262220185-1045)S:P(AU;FA;GA;;;WD)(AU;SA;GWGX;;;WD)
MaxConcurrentOperations = 4294967295
MaxConcurrentOperationsPerUser = 500
EnumerationTimeoutms = 60000
MaxConnections = 25
MaxPacketRetrievalTimeSeconds = 120
AllowUnencrypted = true
Auth
Basic = true
Kerberos = false
Negotiate = true
Certificate = true
CredSSP = false
CbtHardeningLevel = Relaxed
DefaultPorts
HTTP = 5985
HTTPS = 5986
IPv4Filter = *
IPv6Filter = *
EnableCompatibilityHttpListener = false
EnableCompatibilityHttpsListener = false
CertificateThumbprint
Winrs
AllowRemoteShellAccess = true
IdleTimeout = 180000
MaxConcurrentUsers = 5
MaxShellRunTime = 2147483647
MaxProcessesPerShell = 15
MaxMemoryPerShellMB = 150
MaxShellsPerUser = 5
PS C:\> Get-PSSessionConfiguration microsoft.powershell | fl *
xmlns : http://schemas.microsoft.com/wbem/wsman/1/config/PluginConfiguration
Name : Microsoft.PowerShell
Filename : %windir%\system32\pwrshplugin.dll
SDKVersion : 1
XmlRenderingType : text
lang : en-US
PSVersion : 2.0
ResourceUri : http://schemas.microsoft.com/powershell/Microsoft.PowerShell
SupportsOptions : true
ExactMatch : true
Capability : {Shell}
Permission :
Administrators group have permission as I see in the window popup (Set-PSSessionConfiguration -Name Microsoft.PowerShell -showSecurityDescriptorUI)
EDIT 2:
By process of elimination, we can rule out firewall as an issue, as you are only connecting to the loopback address (127.0.0.1). We can also rule out WinRM configuration which looks fine.
The error message suggests that TCP connection to http://localhost:8173/WSMAN is actually successful, but fault occurs while establishing PS session.
This points to Microsoft.PowerShell session configuration.
Looks like there is a discrepancy in the permissions you see when looking at
Set-PSSessionConfiguration -Name Microsoft.PowerShell -showSecurityDescriptorUI
and the permission actually assigned to Microsoft.PowerShell.
The output of
Get-PSSessionConfiguration microsoft.powershell | fl *
should have the "SecurityDescriptorSddl" and "Permission" proprieties listed. Like this:
Name : microsoft.powershell
Filename : %windir%\system32\pwrshplugin.dll
SDKVersion : 1
XmlRenderingType : text
lang : en-US
PSVersion : 2.0
ResourceUri : http://schemas.microsoft.com/powershell/microsoft.powershell
SupportsOptions : true
Capability : {Shell}
xmlns : http://schemas.microsoft.com/wbem/wsman/1/config/PluginConfiguration
Uri : http://schemas.microsoft.com/powershell/microsoft.powershell
ExactMatch : true
SecurityDescriptorSddl : O:NSG:BAD:P(A;;GA;;;BA)S:P(AU;FA;GA;;;WD)(AU;SA;GXGW;;;WD)
Permission : BUILTIN\Administrators AccessAllowed
Try removing and reassigning these permissions.
EDIT:
Based on the information you have provided this is not the main problem. I have also noticed that you have a non standard "RootSDDL" in WinRM service settings.
RootSDDL = O:NSG:BAD:P(A;;GA;;;BA)S:P(AU;FA;GA;;;S-1-5-21-2458768215-3945602940-3262220185-1045)(AU;SA;GWGX;;;WD)
by default this should be
RootSDDL = O:NSG:BAD:P(A;;GA;;;BA)S:P(AU;FA;GA;;;WD)(AU;SA;GWGX;;;WD)
I have recreated this on the test VM and Remoting still works. So I had another look at your WinRM configuration ...
Solution
Your problem is this line
MaxEnvelopeSizekb = 1039440
By setting this value I can replicate the issue you have. I would suggest to set this to something more reasonable, or to default.
winrm set winrm/config '#{MaxEnvelopeSizekb="150"}'
Will fix your problem.
setting the following worked for me after I upgraded to computers from win 10 1607 to 1708
the update changed the following reg key to 1, and setting it back to 0 worked for me
HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\Policies\System
FilterAdministratorToken=dword:0
In a "strict" IPV4 environent, we had the same Problem as well.
The reason was: WinRM (and other services) seem to use the IpV6-Loopback-Address even if ipv6 is disabled everywhere. (Which is no Problem, except with WinRM)
Hence, if there is no WinRM-Listener for the IPV6-Loopback Adress - you can't connect to localhost, even if WinRM is working from a remote-host.