EzDevInfo.com

winrm interview questions

Top winrm frequently asked interview questions

What is the difference between PowerShell and cmd.exe command syntax?

I am running the following command in PowerShell:

PS C:\Users\adminaccount> winrm s winrm/config/service @{AllowUnencrypted="true";
MaxConcurrentOperationsPerUser="4294967295"}
Error: Invalid use of command line. Type "winrm -?" for help.

Which gives me error, as you could see. But the same command in cmd.exe works fine:

C:\Users\adminaccount>winrm s winrm/config/service @{AllowUnencrypted="true";
MaxConcurrentOperationsPerUser="4294967295"}
Service
...

So, what should I know about PowerShell syntax to get this working there?


Source: (StackOverflow)

How to add more than one machine to the trusted hosts list using winrm

To run powershell commands on a machine from a remote machine we have to add the remote machine to the trusted hosts list of the host machine.

I am adding machine A to machine B's trusted hosts using the following command :

winrm set winrm/config/client ‘@{TrustedHosts="machineA"}’

How to add more machines say machine C, machine D to trusted hosts list of machine B?


Source: (StackOverflow)

Advertisements

Send files over PSSession

I just burned a couple of hours searching for a solution to send files over an active PSSession. And the result is nada, niente. I'm trying to invoke a command on a remote computer over an active session, which should copy something from a network storage. So, basically this is it:

icm -Session $s {
Copy-Item $networkLocation $PCLocation }

Because of the "second hop" problem, I can't do that directly, and because I'm running win server 2003 I cant enable CredSSP. I could first copy the files to my computer and then send/push them to the remote machine, but how? I tried PModem, but as I saw it can only pull data and not push.

Any help is appreaciated.


Source: (StackOverflow)

Powershell remoting - Policy does not allow the delegation of user credentials

I'm new to powershell and I'm having troubles using credentials delegation. I have the following script:

$session = New-PSSession myserver -Authentication CredSSP -Credential DOMAIN\Administrator
Invoke-Command -Session $session -ScriptBlock { <Some PowerShell Command> }

Before running it, I did the following:

  1. Run Enable-PSRemoting on myserver.
  2. Run Enable-WSManCredSSP Server on myserver.
  3. Run Restart-Service WinRM on myserver.
  4. Run Enable-WSManCredSSP Client –DelegateComputer myserver on the client.
  5. Rebooted both the server and the client.

But once I run the script, I get the following error message:

[myserver] Connecting to remote server failed with the following error message : The WinRM client cannot process the request. A computer policy does not allow the delegation of
 the user credentials to the target computer. Use gpedit.msc and look at the following policy: Computer Configuration -> Administrative Templates -> System -> Credentials Delega
tion -> Allow Delegating Fresh Credentials.  Verify that it is enabled and configured with an SPN appropriate for the target computer. For example, for a target computer name "m
yserver.domain.com", the SPN can be one of the following: WSMAN/myserver.domain.com or WSMAN/*.domain.com. For more information, see the about_Remote_Troubleshooting Help topic.
    + CategoryInfo          : OpenError: (System.Manageme....RemoteRunspace:RemoteRunspace) [], PSRemotingTransportException
    + FullyQualifiedErrorId : PSSessionOpenFailed

I checked the policies as mentioned in the error message but everything seems to be fine. What else could be blocking me?


Source: (StackOverflow)

Connecting to remote server failed using WinRM from PowerShell

I am trying to run powershell code from my computer to vm on my computer, but i keep getting this error:

Connecting to remote server 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.

my code:

  string runasUsername = @"\aaa";
    string runasPassword = "aaa";
    SecureString ssRunasPassword = new SecureString();
    foreach (char x in runasPassword)
        ssRunasPassword.AppendChar(x);
    PSCredential credentials = new PSCredential(runasUsername, ssRunasPassword);

    var connInfo = new WSManConnectionInfo(new Uri("http://10.0.5.35/PowerShell"),
        "http://schemas.microsoft.com/powershell/Microsoft.Exchange",credentials);
    connInfo.AuthenticationMechanism = AuthenticationMechanism.Basic;

    var runspace = RunspaceFactory.CreateRunspace(connInfo);


    var domainName = "domainName.COM";
    var password = "ActiveDirectoryPassword1234";
    var ssPassword = new SecureString();
    foreach (char c in password)
        ssPassword.AppendChar(c);


    var command = new Command("New-Mailbox");

    command.Parameters.Add("FirstName", firstName);
    command.Parameters.Add("LastName", lastName);
    command.Parameters.Add("Password", ssPassword);
    command.Parameters.Add("ResetPasswordOnNextLogon", false);
    command.Parameters.Add("OrganizationalUnit", "NeumontStudents");

    runspace.Open(); <--//error here
    var pipeline = runspace.CreatePipeline();
    pipeline.Commands.Add(command);


    var results = pipeline.Invoke();

    runspace.Dispose();

What am I missing?


Source: (StackOverflow)

Configure and listen successfully using WinRM in powershell

I'm testing WinRM connection using Command Prompt on my local and remote machine and my question is devided into two parts.

PART I

I tested TCP/IP connectivity by using ping command to ping : IP Address of local computer and remote computer, default gateway and DNS Server and it runs perfectly on both local and remote computer.

But when testing using WinRM commands, I used this command to locate listeners and addresses

winrm e winrm/config/listener

It gives me this output for my local machine

Listener
Address = *
Transport = HTTP
Port = 5985
Hostname
Enabled = true
URLPrefix = wsman
CertificateThumbprint
ListeningOn =<IP Address>,127.0.0.1, ::1,fe80::100:7f:fffe%13,fe80::803:5e43:50ef:c50%11

But the same command when I run on remote machine gives me an output with everything else the same, except

Listener[Source="GPO"]
.
.
.
ListeningOn=null

I want to configure it to make it listen correctly.

PART II

And when I run these commands one by one on my remote machine

winrm id -r:<machine name>
winrm get winrm/config -r:<machine name>
winrm get wmicimv2/Win32_Service?Name = WinRM -r:<machine name>

It gives a WSMan Fault with an error message as :

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 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 analyse and configure the WinRM service:
"winrm quickconfig". 

Whereas, same commands when I run on my local machine run correctly.

winrm id 
winrm get winrm/config
winrm get wmicimv2/Win32_Service?Name = WinRM

At most, all the problems I'm facing is on my remote machine. What is causing this to happen and how can I configure it to listen and connect successfully? Thank You.


Part II, I am now able to run these on one of my other remote machines with correct output.

I made some changes in this particular remote machine for which I had posted the question and so, it wouldn't run these commands until I fix the part I but besides that if nothing has been altered it will run just like it does on my other remote machines.

I would still appreciate if someone could help me with part I in which I have to get rid of

Listener[Source=GPO]
..
.
ListeningOn=null

when I run the command

winrm e winrm/config/listener

because this is what is causing issues but I'm not sure how to disable/remove Group Policy Settings.


Source: (StackOverflow)

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: Permissions


Source: (StackOverflow)

Error PSRemoting using Session and CredSSP

I use Windows 8.1 Enterprise 64 bit and Powershell 4.0.

I want execute powershell remoting and using authentication CredSSP.

I open Console Powershell, run as Administrator, and execute Enter-PSSession command to connect to remote computer.

But I get error about connection.

PS C:\Documents and Settings\kiquenet> Enter-PSSession -ComputerName DC -credential devrsg.com\Administrator

Anyways, I test command from Windows XP and Windows 7, and connection is OK.

PS C:\Documents and Settings\kiquenet> Enter-PSSession -ComputerName DC -credential devrsg.com\Administrator
[dc]: PS C:\Users\Administrator\Documents> exit

Now, I test in Windows 8.1.

I test command enable-psremoting and I get error:

PS C:\Windows\system32> Enable-PSRemoting -force

WinRM ya está configurado para recibir solicitudes en este equipo.
WinRM has been updated to receive requests.
Set-WSManQuickConfig : <f:WSManFault xmlns:f="http://schemas.microsoft.com/wbem/wsman/1/wsmanfault" Code="2"
Machine="localhost"><f:Message><f:ProviderFault provider="Config provider"
path="%systemroot%\system32\WsmSvc.dll"><f:WSManFault xmlns:f="http://schemas.microsoft.com/wbem/wsman/1/wsmanfault"
Code="2" Machine="MYCOMPUTERW8.mycompany.net"><f:Message>Unable to check the status of the firewall.
</f:Message></f:WSManFault></f:ProviderFault></f:Message></f:WSManFault>
En línea: 69 Carácter: 17
+                 Set-WSManQuickConfig -force
+                 ~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : InvalidOperation: (:) [Set-WSManQuickConfig], InvalidOperationException
    + FullyQualifiedErrorId : WsManError,Microsoft.WSMan.Management.SetWSManQuickConfigCommand

Same error using the command Enable-PSRemoting -force -SkipNetworkProfileCheck.

I test command winrm quickconfig and I get error:

PS C:\Windows\system32> winrm quickconfig  -force
WinRM service is already running on this machine.
WSManFault
    Message
        ProviderFault
            WSManFault
                Message = Unable to check the status of the firewall.

Nº de error:  -2147024894 0x80070002
The system cannot find the file specified.

I have SmartScreen and Firewall disabled in my Windows 8.1. (I have Symantec Endpoint protection disabled)

Any suggestions?

update:

I test those commads:

PS C:\> Enable-PSRemoting -SkipNetworkProfileCheck -Force

PS C:\>Set-NetFirewallRule –Name "WINRM-HTTP-In-TCP-PUBLIC" –RemoteAddress Any

but I get error:

PS C:\Windows\system32> Set-NetFirewallRule -Name "WINRM-HTTP-In-TCP-PUBLIC" -RemoteAddress Any
Set-NetFirewallRule : No se encontraron objetos MSFT_NetFirewallRule cuya propiedad 'InstanceID' sea igual a
'WINRM-HTTP-In-TCP-PUBLIC'. Compruebe el valor de la propiedad e inténtelo de nuevo.
En línea: 1 Carácter: 1
+ Set-NetFirewallRule -Name "WINRM-HTTP-In-TCP-PUBLIC" -RemoteAddress Any
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : ObjectNotFound: (WINRM-HTTP-In-TCP-PUBLIC:String) [Set-NetFirewallRule], CimJobException
    + FullyQualifiedErrorId : CmdletizationQuery_NotFound_InstanceID,Set-NetFirewallRule

Reference: http://technet.microsoft.com/en-us/library/hh849694.aspx

Update 2

Now,I execute Net stop MPSSVC (Windows Firewall Service), and I get this error

Enter-PSSession -ComputerName DC -credential dersg.com\Administrator
Enter-PSSession : Connecting to remote server DC failed with the following error message : Access is denied. For more information, see the about_Remote_Troubleshooting Help topic.
En línea: 1 Carácter: 1
+ Enter-PSSession -ComputerName DC -credential devrsg.com\Administrator
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : InvalidArgument: (DC:String) [Enter-PSSession], PSRemotingTransportException
    + FullyQualifiedErrorId : CreateRemoteRunspaceFailed

Update 3.

I execute this command (http://stackoverflow.com/a/22816386/206730)

Set-PSSessionConfiguration -ShowSecurityDescriptorUI -Name Microsoft.PowerShell

Now, I execute the command and all is OK

PS C:\Documents and Settings\kiquenet> Enter-PSSession -ComputerName DC -credential devrsg.com\Administrator
[dc]: PS C:\Users\Administrator\Documents> exit

Now, I enable CredSSP in server and in client:

Enable-WSManCredSSP -Role Server –Force

Enable-WSManCredSSP -Role Client -DelegateComputer * -Force

Now, I test command using CredSSP:

$serverName = "DC"
$username = "devrsg\Administrator"
$password = "xxxxxx"   

$adjPwd = $password | ConvertTo-SecureString -asPlainText -Force
$testCred = (New-Object System.Management.Automation.PSCredential($username,$adjPwd))   

$scriptBlock = {
  Write-Host ("hello, world: {0}, {1}" -f $env:USERNAME, (hostname))
}

Invoke-Command $scriptBlock -computername $serverName -credential $testCred  -Authentication Credssp

and I get the error:

PS C:\> .\testRemoteCredSSP.ps1
[DC] Error de conexión al servidor remoto DC. Mensaje de error: El cliente WinRM no puede procesar la solicitud. Una
directiva de equipo no permite delegar credenciales de usuario en el equipo de destino porque éste no es de confianza.
La identidad del equipo de destino se puede comprobar si configura el servicio WSMAN para usar un certificado válido
con el siguiente comando: winrm set winrm/config/service '@{CertificateThumbprint="<huellaDigital>"}'  O bien puede
comprobar en el Visor de eventos si hay un evento que especifique que no se pudo crear el siguiente SPN:
WSMAN/<FQDNdelEquipo>. Si encuentra este evento, puede crear manualmente el SPN con setspn.exe .  Si el SPN existe,
pero CredSSP no puede usar Kerberos para validar la identidad del equipo de destino y desea permitir la delegación de
credenciales de usuario en el equipo de destino, use gpedit.msc y mire la siguiente directiva: Configuración del
equipo -> Plantillas administrativas -> Sistema -> Delegación de credenciales -> Permitir credenciales nuevas con
autenticación solo NTLM de servidor.  Compruebe que esté habilitada esta opción y configurada con el correspondiente
SPN para el equipo de destino. Por ejemplo, para un nombre de equipo de destino "miservidor.dominio.com", el SPN puede
ser alguno de los siguientes: WSMAN/miservidor.dominio.com o WSMAN/*.dominio.com. Pruebe de nuevo la solicitud después
de realizar estos cambios. Para obtener más información, consulte el tema de la Ayuda about_Remote_Troubleshooting.
    + CategoryInfo          : OpenError: (DC:String) [], PSRemotingTransportException
    + FullyQualifiedErrorId : -2144108124,PSSessionStateBroken

English message:

Enter-PSSession : Connecting to remote server failed with the following error me
ssage : The WinRM client cannot process the request. 
A computer policy does not allow the delegation of the user credentials to the target computer because the computer is not trusted. The identity of the target computer can be verified if you configure the WSMAN service to use a valid certificate using the following command: winrm set winrm/config/service '@{CertificateThumbprint="<thumbprint>"}' 

Or you can check the Event Viewer for an event that specifies that the following SPN could not be created: WSMAN/<computerFQDN>. If you find this event, you can manually create the SPN using setspn.exe .  

If the SPN exists, but CredSSP can not use Kerberos to validate the identity of the target computer and you still want to allow the delegation of the user credentials to the target computer, use gpedit.msc and look at the following policy: Computer Configuration -> Administrative Templates -> System -> Credentials Delegation -> Allow Fresh Credentials with NTLM-only Server Authentication.  

Verify that it is enabled and configured with an SPN appropriate for the target computer. 
For example, for a target computer name "myserver.domain.com", the SPN can be one of the following: WSMAN/myserver.domain.com or WSMAN/*.domain.com. 

Try the request again after these changes. 
    For more information, see the about_Remote_Troubleshooting Help topic.

Source: (StackOverflow)

WinRM cannot process the request - fails only over a specific domain

Some of ours servers (W2K8 R2) were moved to the cloud last week, once done that my powerswhell script started to fail (was working fine before), the exception is thrown on the line where the connection is trying to be established,

$ExSession = New-PSSession –ConfigurationName Microsoft.Exchange –ConnectionUri     "http://$g_strExchangeServer/PowerShell" `
-Credential $Credentials –Authentication Kerberos

With the following message,

[subd.staging.com] Connecting to remote server failed with the following error message : 
**WinRM cannot process the request**. The following error occured 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 onfig. For more information, see the about_Remote_Troubleshooting Help topic.
+ CategoryInfo          : OpenError: (System.Manageme....RemoteRunspace:RemoteRunspace) [], PSRemotingTransportException
+ FullyQualifiedErrorId : PSSessionOpenFailed

this happens only if I try to target our testing domain, if I point the script to our production domain then it works.

The same error is displayed on all the servers that were already moved to cloud.

Notice that all the servers which have not already moved to cloud are able to run the script on both domains without any problem.

I've tried the following, but no luck.

//Add the destination computer to the WinRM TrustedHosts configuration setting. 
c:\>WinRM set winrm/config/client @{TrustedHosts="stagingserver"} 


//Confirm that WinRM is properly configured.  
c:\>Winrm quickconfig  

//Make sure that the remote server allows commands from any machine. 
PS c:\>Set-item wsman:localhost\client\trustedhosts -value * 

Using Powershell v2 and WinRM v2

Any comments are welcome.


Source: (StackOverflow)

Stuck trying to bootstrap Windows server using Chef

I am a mac girl, working on connecting with knife-windows trough Opscode's managed Chef to my Rackspace Windows servers. (I know, it sounds exotic, but these Windows servers are a customer requirment).

I tried to Chef for a spin but I am stuck in trying to bootstrap the Windows 2008 Server on Rackspace with the knife-windows command.

I am working on OSX, using rvm, ruby 2.1.0 and a local gemset with chef + knife-windows.

I was trying to follow the steps from: https://github.com/opscode/knife-windows

I have configured the winrm service. I have set up a rule to allow inbound connections in my firewall on port 5985,and I verified that I can connect with telnet.

In addition to the Learn Chef screen casts, I have tried to follow the guide: http://developer.rackspace.com/blog/step-by-step-walkthrough-to-using-chef-to-bootstrap-windows-nodes-on-the-rackspace-cloud.html

I configured winrm like this:

winrm quickconfig -q
winrm set winrm/config/winrs '@{MaxMemoryPerShellMB="300"}'
winrm set winrm/config '@{MaxTimeoutms="1800000"}'
winrm set winrm/config/service '@{AllowUnencrypted="true"}'
winrm set winrm/config/service/auth '@{Basic="true"}'
netsh advfirewall firewall add rule name="WinRM 5985" protocol=TCP dir=in localport=5985 action=allow
netsh advfirewall firewall add rule name="WinRM 5986" protocol=TCP dir=in localport=5986 action=allow
net stop winrm
sc config winrm start=auto
net start winrm

I am using knife like this: knife bootstrap windows winrm 168.** -x Administrator -P '**'

I get back this strange log, no success report, no instance appearing in the chef management console .... I see that its trying to insert the character '#39' many times ?

WARNING: Could not load IOV methods. Check your GSSAPI C library for an update
WARNING: Could not load AEAD methods. Check your GSSAPI C library for an update
Bootstrapping Chef on 162.13.15.241
162.13.15.241 "Rendering "C:\Users\ADMINI~1\AppData\Local\Temp\bootstrap-47130-1392751156.bat" chunk 1" 
162.13.15.241 "Rendering "C:\Users\ADMINI~1\AppData\Local\Temp\bootstrap-47130-1392751156.bat" chunk 2" 
162.13.15.241 '#39' is not recognized as an internal or external command,
162.13.15.241 operable program or batch file.
162.13.15.241 "Rendering "C:\Users\ADMINI~1\AppData\Local\Temp\bootstrap-47130-1392751156.bat" chunk 3" 
162.13.15.241 '#39' is not recognized as an internal or external command,
162.13.15.241 operable program or batch file.
162.13.15.241 "Rendering "C:\Users\ADMINI~1\AppData\Local\Temp\bootstrap-47130-1392751156.bat" chunk 4" 
162.13.15.241 '#39' is not recognized as an internal or external command,
162.13.15.241 operable program or batch file.
162.13.15.241 '#39' is not recognized as an internal or external command,
....
162.13.15.241  echo. 
162.13.15.241  echo.$webClient = new-object System.Net.WebClient;  
162.13.15.241  echo. 
162.13.15.241  echo.$webClient.DownloadFile($remoteUrl, $localPath); 
162.13.15.241 ) 1>C:\chef\wget.ps1 
162.13.15.241 C:\Users\Administrator>)

I tried to follow the advice from knife bootstrap windows winrm from Mac OS X workstation fails, and downgraded knife-windows to version 0.5.10, but the result is the same.

My gemset is as follows:

akami (1.2.1)
bigdecimal (1.2.3)
builder (3.2.2)
bundler (1.5.3)
bundler-unload (1.0.2)
chef (11.10.0)
chef-zero (1.7.3)
coderay (1.1.0)
diff-lcs (1.2.5)
em-winrm (0.5.4)
erubis (2.7.0)
eventmachine (1.0.0.beta.3)
excon (0.31.0)
executable-hooks (1.3.1)
ffi (1.9.3)
fog (1.20.0)
formatador (0.2.4)
gem-wrappers (1.2.4)
gssapi (1.0.3)
gyoku (1.1.1)
hashie (2.0.5)
highline (1.6.20)
httpclient (2.3.4.1)
httpi (0.9.7)
io-console (0.4.2)
ipaddress (0.8.0)
json (1.8.1)
knife-rackspace (0.9.0)
knife-windows (0.5.10)
little-plugger (1.1.3)
logging (1.8.2)
method_source (0.8.2)
mime-types (1.25.1)
mini_portile (0.5.2)
minitest (4.7.5)
mixlib-authentication (1.3.0)
mixlib-cli (1.4.0)
mixlib-config (2.1.0)
mixlib-log (1.6.0)
mixlib-shellout (1.3.0)
moneta (0.6.0)
multi_json (1.8.4)
net-scp (1.1.2)
net-ssh (2.8.0)
net-ssh-gateway (1.2.0)
net-ssh-multi (1.2.0)
nokogiri (1.6.1)
nori (1.1.5)
ohai (6.20.0)
pry (0.9.12.6)
psych (2.0.2)
puma (1.6.3)
rack (1.5.2)
rake (10.1.0)
rdoc (4.1.0)
rest-client (1.6.7)
rubygems-bundler (1.4.2)
rubyntlm (0.1.1)
rvm (1.11.3.9)
savon (0.9.5)
slop (3.4.7)
systemu (2.5.2)
test-unit (2.1.0.0)
uuidtools (2.1.4)
wasabi (1.0.0)
winrm (1.1.3)
yajl-ruby (1.2.0)

Any advice? Is this an OS X thing? Windows Server thing? Chef thing???

With last shreds of hope, Agata


Source: (StackOverflow)

SQL Server setup fails with "Unable to generate a temporary class" when through chef-solo on vagrant

Over the past week I've been trying to address Chef COOK-1172 without much success. I'm trying to install SQL Server 2008 R2 Developer Edition (in my case) through Vagrant using the Chef-Solo provisioner.

I've been able to reproduce the issue outside of Chef by going directly through the Ruby WinRM gem and then fix it using a custom PowerShell script which uses the passed along credentials to start the setup.exe process on the guest Windows vagrant box. In other words, WinRM gem invokes a remote PS script which starts the SQL Server setup.exe under the specified credentials, and this works.

However, running the same exact script through chef-solo on the guest fails with with an InvalidOperationException: Unable to generate a temporary class.

The Ruby script and the embedded PowerShell script I'm using for testing, which is invoked from my OS X host:

require 'winrm'

endpoint = 'http://localhost:5985/wsman'
user = password = 'vagrant'
ps = <<EOH

function ps-runas ([String] $cmd, [String] $arguments)
{
  Write-Host "ps-runas cmd: $cmd"
  Write-Host "ps-runas args: $arguments"

  $secpasswd = ConvertTo-SecureString "vagrant" -AsPlainText -Force

  $process = New-Object System.Diagnostics.Process
  $setup = $process.StartInfo
  $setup.FileName = $cmd
  $setup.Arguments = $arguments
  $setup.UserName = "vagrant"
  $setup.Password = $secpasswd
  $setup.Verb = "runas"
  $setup.UseShellExecute = $false
  $setup.RedirectStandardError = $true
  $setup.RedirectStandardOutput = $true
  $setup.RedirectStandardInput = $false

  # Hook into the standard output and error stream events
  $errEvent = Register-ObjectEvent -InputObj $process `
    -Event "ErrorDataReceived" `
    -Action `
    {
        param
        (
            [System.Object] $sender,
            [System.Diagnostics.DataReceivedEventArgs] $e
        )
        Write-Host $e.Data
    }
  $outEvent = Register-ObjectEvent -InputObj $process `
    -Event "OutputDataReceived" `
    -Action `
    {
        param
        (
            [System.Object] $sender,
            [System.Diagnostics.DataReceivedEventArgs] $e
        )
        Write-Host $e.Data
    }

  Write-Host "ps-runas starting: $cmd"

  if (!$process.Start())
  {
    Write-Error "Failed to start $cmd"
  }

  $process.BeginOutputReadLine()
  $process.BeginErrorReadLine()

  # Wait until process exit
  $process.WaitForExit()

  $process.CancelOutputRead()
  $process.CancelErrorRead()
  $process.Close()
}

EOH

cmd = ps

# Fails - Running through chef-solo fails - cannot compile a serialization assembly
cmd << "ps-runas \"c:\\opscode\\chef\\bin\\chef-solo.bat\" \"-c c:\\tmp\\vagrant-chef-1\\solo.rb -j c:\\tmp\\vagrant-chef-1\\dna.json\""

# Succeeds - Running setup directly works
#cmd << "ps-runas \"c:\\vagrant\\sql2008r2\\setup.exe\" \"/Q /ConfigurationFile=c:\\vagrant\\ConfigurationFile.ini\""

winrm = WinRM::WinRMWebService.new(endpoint, :plaintext, :user => user, :pass => password, :basic_auth_only => true)
winrm.set_timeout(60*20)

winrm.powershell(cmd) do |stdout, stderr|
  STDOUT.print stdout
  STDERR.print stderr
end

puts 'Done!'

From the sql installation logs:

013-03-03 22:44:50 Slp: Exception type: Microsoft.SqlServer.Chainer.Infrastructure.ChainerInfrastructureException
2013-03-03 22:44:50 Slp:     Message: 
2013-03-03 22:44:50 Slp:         Unable to generate a temporary class (result=1).
2013-03-03 22:44:50 Slp:         error CS0583: Internal Compiler Error (0xc0000017 at address 000007FEFD00AA7D): likely culprit is 'IMPORT'.
2013-03-03 22:44:50 Slp:         error CS0584: Internal Compiler Error: stage 'IMPORT' symbol 'System.Xml.Serialization.XmlSerializationReader'
2013-03-03 22:44:50 Slp:         error CS0584: Internal Compiler Error: stage 'IMPORT' symbol 'Microsoft.Xml.Serialization.GeneratedAssembly.XmlSerializationReaderClusterNodesStatusPublicConfigObject'
2013-03-03 22:44:50 Slp:         error CS0584: Internal Compiler Error: stage 'PREPARE' symbol 'Microsoft.Xml.Serialization.GeneratedAssembly.XmlSerializationReaderClusterNodesStatusPublicConfigObject'
2013-03-03 22:44:50 Slp:         error CS0584: Internal Compiler Error: stage 'PREPARE' symbol 'Microsoft.Xml.Serialization.GeneratedAssembly'
2013-03-03 22:44:50 Slp:         error CS0584: Internal Compiler Error: stage 'PREPARE' symbol 'Microsoft.Xml.Serialization'
2013-03-03 22:44:50 Slp:         error CS0584: Internal Compiler Error: stage 'PREPARE' symbol 'Microsoft.Xml'
2013-03-03 22:44:50 Slp:         error CS0584: Internal Compiler Error: stage 'PREPARE' symbol 'Microsoft'
2013-03-03 22:44:50 Slp:         error CS0584: Internal Compiler Error: stage 'PREPARE' symbol '<global namespace>'
2013-03-03 22:44:50 Slp:         error CS0586: Internal Compiler Error: stage 'PREPARE'
2013-03-03 22:44:50 Slp:         error CS0587: Internal Compiler Error: stage 'PREPARE'
2013-03-03 22:44:50 Slp:         error CS0587: Internal Compiler Error: stage 'BEGIN'
2013-03-03 22:44:50 Slp:         
2013-03-03 22:44:50 Slp:     Stack: 
2013-03-03 22:44:50 Slp:         at Microsoft.SqlServer.Chainer.Infrastructure.DataStoreService.DeserializeObject(String rootPath, Type type, String elementXPath)
2013-03-03 22:44:50 Slp:         at Microsoft.SqlServer.Chainer.Infrastructure.DataStoreService.DeserializeObject(String rootPath, Type type)
2013-03-03 22:44:50 Slp:         at Microsoft.SqlServer.Configuration.SetupExtension.FinalCalculateSettingsAction.ExecuteAction(String actionId)
2013-03-03 22:44:50 Slp:         at Microsoft.SqlServer.Chainer.Infrastructure.Action.Execute(String actionId, TextWriter errorStream)
2013-03-03 22:44:50 Slp:         at Microsoft.SqlServer.Setup.Chainer.Workflow.ActionInvocation.ExecuteActionHelper(TextWriter statusStream, ISequencedAction actionToRun)
2013-03-03 22:44:50 Slp:     Inner exception type: System.InvalidOperationException
2013-03-03 22:44:50 Slp:         Message: 
2013-03-03 22:44:50 Slp:                 Unable to generate a temporary class (result=1).
2013-03-03 22:44:50 Slp:                 error CS0583: Internal Compiler Error (0xc0000017 at address 000007FEFD00AA7D): likely culprit is 'IMPORT'.
2013-03-03 22:44:50 Slp:                 error CS0584: Internal Compiler Error: stage 'IMPORT' symbol 'System.Xml.Serialization.XmlSerializationReader'
2013-03-03 22:44:50 Slp:                 error CS0584: Internal Compiler Error: stage 'IMPORT' symbol 'Microsoft.Xml.Serialization.GeneratedAssembly.XmlSerializationReaderClusterNodesStatusPublicConfigObject'
2013-03-03 22:44:50 Slp:                 error CS0584: Internal Compiler Error: stage 'PREPARE' symbol 'Microsoft.Xml.Serialization.GeneratedAssembly.XmlSerializationReaderClusterNodesStatusPublicConfigObject'
2013-03-03 22:44:50 Slp:                 error CS0584: Internal Compiler Error: stage 'PREPARE' symbol 'Microsoft.Xml.Serialization.GeneratedAssembly'
2013-03-03 22:44:50 Slp:                 error CS0584: Internal Compiler Error: stage 'PREPARE' symbol 'Microsoft.Xml.Serialization'
2013-03-03 22:44:50 Slp:                 error CS0584: Internal Compiler Error: stage 'PREPARE' symbol 'Microsoft.Xml'
2013-03-03 22:44:50 Slp:                 error CS0584: Internal Compiler Error: stage 'PREPARE' symbol 'Microsoft'
2013-03-03 22:44:50 Slp:                 error CS0584: Internal Compiler Error: stage 'PREPARE' symbol '<global namespace>'
2013-03-03 22:44:50 Slp:                 error CS0586: Internal Compiler Error: stage 'PREPARE'
2013-03-03 22:44:50 Slp:                 error CS0587: Internal Compiler Error: stage 'PREPARE'
2013-03-03 22:44:50 Slp:                 error CS0587: Internal Compiler Error: stage 'BEGIN'
2013-03-03 22:44:50 Slp:                 
2013-03-03 22:44:50 Slp:         Stack: 
2013-03-03 22:44:50 Slp:                 at System.Xml.Serialization.Compiler.Compile(Assembly parent, String ns, XmlSerializerCompilerParameters xmlParameters, Evidence evidence)
2013-03-03 22:44:50 Slp:                 at System.Xml.Serialization.TempAssembly.GenerateAssembly(XmlMapping[] xmlMappings, Type[] types, String defaultNamespace, Evidence evidence, XmlSerializerCompilerParameters parameters, Assembly assembly, Hashtable assemblies)
2013-03-03 22:44:50 Slp:                 at System.Xml.Serialization.TempAssembly..ctor(XmlMapping[] xmlMappings, Type[] types, String defaultNamespace, String location, Evidence evidence)
2013-03-03 22:44:50 Slp:                 at System.Xml.Serialization.XmlSerializer.GenerateTempAssembly(XmlMapping xmlMapping, Type type, String defaultNamespace)
2013-03-03 22:44:50 Slp:                 at System.Xml.Serialization.XmlSerializer..ctor(Type type, String defaultNamespace)
2013-03-03 22:44:50 Slp:                 at Microsoft.SqlServer.Chainer.Infrastructure.DataStoreService.DeserializeObject(String rootPath, Type type, String elementXPath)

My first suspicion is that I'm running into some sort of permission problem with my temp directory, but I've tried running ProcMon and haven't found any ACCESS DENIED results while running setup. Additionally, I'm explicitly running as a local administrator (vagrant) because of the PowerShell script and UAC is turned off.


Source: (StackOverflow)

bootstrap windows winrm fails with network error

I am trying to bootstrap a windows winrm using knife command.

I have enabled the tcp port 5985. But i still get the following error:

ERROR: Network Error: Connection refused - connect(2) (http://:5985)

I am able to remotely login to the machine as well by providing username and password

I could not resolve. Has anyone come across this problem and found a solution?


Source: (StackOverflow)

Checks about WinRM service in remote machine

I have seen great article
PowerShell 2.0 remoting guide: Part 8 – remoting scenarios and troubleshooting
http://www.ravichaganti.com/blog/?p=1181

I have this issue: I have two computers in domain, in network.

First Test OK: Remoting to a computer in domain from a computer in domain

COMPANY_DOMAIN\desmonitor is Domain User.
Domain COMPANY_DOMAIN
Computer: iis01

PS C:\Users\myUser> Enter-PSSession -Computername iisw01 -Credential COMPANY_DOMAIN\desmonitor
[desiisw01]: PS C:\Users\desmonitor\Documents> exit

Second Test Wrong: : Remoting to a computer in domain from a computer in domain, using local administrator user

iis01\instalador is Local User for machine iis01
Computer: iis01

PS C:\Users\myUser> Enter-PSSession -Computername iis01 -Credential iis01\instalador Enter-PSSession : Connecting to remote server failed with the following error message : The WinRM client cannot process the request.

In machine ii01 using Terminal Server (Remote Desktop) using COMPANY_DOMAIN\desmonitor, I open PS Console and I execute

PS C:\Users\desmonitor> winrm quickconfig
WinRM already is set up to receive requests on this machine.
WinRM already is set up for remote management on this machine.
PS C:\Users\desmonitor>

Then, I try again but I get same error:

PS C:\Users\myUser> Enter-PSSession -Computername iis01 -Credential iis01\instalador Enter-PSSession : Connecting to remote server failed with the following error message : The WinRM client cannot processthe request.

Using this command:

PS C:\Users\myUser> Set-Item WSMan:\localhost\Client\TrustedHosts -Value "*" -Force PS C:\Users\myUser>

Now, I get access:

PS C:\Users\myUser> Enter-PSSession -Computername iis01 -Credential iis01\instalador [iiw01]: PS C:\Users\instalador\Documents> $Host

Name             : ServerRemoteHost
Version          : 1.0.0.0
InstanceId       : 6905896f-e6c7-4603-82f0-20183f71b1ec
UI               : System.Management.Automation.Internal.Host.InternalHostUserInterface
CurrentCulture   : es-ES
CurrentUICulture : es-ES
PrivateData      :
IsRunspacePushed :
Runspace         :

In my company, there are many computers to connect to iis01.

Each compute need execute the command for adding the remote computer to local computer’s trusted hosts list ??

I have several questions about it ¿

How can I get list about TrustedHosts (WSMan:\LocalHost\Client ) in local computer ?
How can I know if WinRM service is enabled in a computer ?
How can I know if WinRM service is running in a computer ?
How can I know if WinRM is set up to receive request in a computer ?
How can I know if WinRM is set up for remote management on this machine?.


Source: (StackOverflow)

Connect to remote server using winrm without adding the server to TrustedHosts

I have been struggling to deal with winrm and TrustedHosts but to no avail. After some experimenting I found out the this field of winrm/config/client is limited up to 1023 symbols which is way not enough especially if adding hosts by their ipv6. I quote from Installation and Configuration for Windows Remote Management: A trusted hosts list should be set up when mutual authentication cannot be established.

Also in the same file the text says: Other computers in a workgroup or computers in a different domain should be added to this list. So I thought that this implies that as long as two computers are in the same domain, I should be able to access one of them from the other using winrm.

I tried to add two computers to a test domain and the executed:

winrm get winrm/config/client -r:192.168.100.1 -u:user -p:pass

From one of them to the other, but this failed with the error:

WSManFault
    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 ad
ded to the TrustedHosts configuration setting. Use winrm.cmd to configure Truste
dHosts. You can get more information about that by running the following command
: winrm help config.

Error number:  -2144108316 0x803380E4
The WinRM client cannot process the request. If the authentication scheme is dif
ferent 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 Tru
stedHosts configuration setting. Use winrm.cmd to configure TrustedHosts. You ca
n get more information about that by running the following command: winrm help c
onfig.

After adding 192.168.100.1 to TrustedHosts the query above succeeds. So my question is: is it possible to use winrm between two hosts without modifying TrustedHosts? Setting Trusted hosts to * is not an option for me.


Source: (StackOverflow)

Remote Access with Powershell and Jenkins

I am trying to run a powershell script on a remote (Windows 2008 Server R2) machine. The following code works great when executed directly from powershell. (I.e. everything is set up correctly, WinRM services are running, Hosts trust each other, login is correct...)

However, when I execute the exact same code from a Jenkins instance (running on the same machine where I tested) I get a PSSessionStateBroken connection failure, . (Not posting full error because it is in German on my machine.)

I suppose that means Jenkins is using powershell differently or has different powershell/winrm settings or insufficient privileges. Any ideas?

$computer = "<some ip>"
$user = "Administrator"
$password = "<secretpassword>"
$securepassword = ConvertTo-SecureString -String $password -AsPlainText -Force
$cred = New-Object -TypeName System.Management.Automation.PSCredential -ArgumentList $user, $securepassword
Invoke-Command -ComputerName $computer -ScriptBlock { Get-ChildItem C:\ } -Credential $cred

Edit: Managed to fix it by running jenkins service as Administrator. Works for me, but does not feel right...


Source: (StackOverflow)