Remote Powershell session not loading assemblies - powershell

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>

Related

Configuring Remote Desktop Services remotely via powershell

Trying to manage our Remote Desktop Services installation using PowerShell and we're running into an issue where the commands in the RemoteDeskop module and the RemoteDesktopServices module do not appear to work when being run via Invoke-Command. Basically it appears that these functions do not work when run in a remote session.
The script below gets the following error:
The RD Connection Broker server is not available. Verify that you can
connect to the RD Connection Broker server.
+ CategoryInfo : NotSpecified: (:) [Write-Error], WriteErrorException
+ FullyQualifiedErrorId : Microsoft.PowerShell.Commands.WriteErrorException,Get-RDServer
+ PSComputerName : AWSELABSDevX13.LABSDEV.com
$server = "OUR_SERVER"
$connection_broker = "OUR_SERVER"
$collectionName ="COLLECTION"
$admin_user = "FULLY_QUALIFIED_DOMAIN_USER"
$password = "PASSWORD"
$password_sec = ConvertTo-SecureString $password -AsPlainText -Force
$cred = New-Object System.Management.Automation.PSCredential ($admin_user, $password_sec)
$sb =
{
function Test-IsAdmin {
([Security.Principal.WindowsPrincipal] [Security.Principal.WindowsIdentity]::GetCurrent()).IsInRole([Security.Principal.WindowsBuiltInRole] "Administrator")
}
if (Test-IsAdmin) {
""
"You are running with Administrator access."
""
} else {
""
"You do not have admin access."
""
}
whoami /priv
Import-Module RemoteDesktop
Import-Module RemoteDesktopServices
Get-RDServer
}
Invoke-Command -Credential $cred -ComputerName $connection_broker -ScriptBlock $sb

New-PSSession to localhost fails

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

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.

New-PSsession not working in Script

I have a strange problem with one of my servers :
I am trying to open a PSsession with it.
If I copy my script directly in powershell everything works fine, but if i run it via a .ps1 file I get a access denied error.
The same sript works on multiple machines except this one.
Additonal information:
Executing Server : Server 2012
Target Server2003SP2
Another Server2003SP2 is working fine without a Problem
the Client Server was configured using :
Enable-PSRemoting -Force
Set-Item wsman:\localhost\client\trustedhosts MY2012Server -concatenate -force
Restart-Service WinRM
And the Error Message:
New-PSSession : [Server2003SP2] Connecting to remote server Server2003SP2 failed with the following error message : Access is denied. For more information,
Help topic.
At C:\Users\Administrator\Desktop\Script.ps1:23 char:13
+ $Session = New-PSSession -ComputerName $Servername -credential $Cred #-sessionO ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : OpenError: (System.Manageme....RemoteRunspace:RemoteRunspace) [New-PSSession], PSRemotingTransportException
+ FullyQualifiedErrorId : AccessDenied,PSSessionOpenFailed
Edit : My full SCript as requested :
$Password = "Hereismypasswordwith#and€init"
$Username = "Servername\Administrator"
$Servername = "Servername"
$Language = {
$oscode = Get-WmiObject Win32_OperatingSystem -ErrorAction continue
$oscode = $oscode.oslanguage
$switch = switch ($oscode){
1031 {"Deutsch"};
1033 {"English"};
default {"English"};
}
write-host $switch
return $switch
}
$SecurePassWord = ConvertTo-SecureString -AsPlainText $Password -Force
$Cred = New-Object -TypeName "System.Management.Automation.PSCredential" -ArgumentList $Username, $SecurePassWord
$pssessionoption = new-pssessionoption -operationtimeout 7200000 -IdleTimeout 7200000
$Session = New-PSSession -ComputerName $Servername -credential $Cred -sessionOption $pssessionoption
Invoke-Command -Session $Session -Scriptblock $Language
Remove-PSSession -Session $Session
UPDATE :
it seems to be something within the Char encoding.
the password in the ps1 file produces a difrent output for the € in it :
in the ps1. ¬
in the ps window : ?
if i pass the Password as a Paramter it also works.
$password.gethash() also prouces difrent outputs. codepage is the same though (chcp)
the script was created in notepad++
Changing / Converting to ansi from UTC without BOM fixed the issue.. jesus crist who thinks about stuff like that / why the hell was it set to this value..