New-PSSession - WinRM cannot process the request - powershell

I am trying to list all the websites in IIS on a remote server using PowerShell scripting. Below is how I am trying to connect to the server:
$s = New-PSSession -ComputerName $Server
But when I run the script I am getting the following error:
New-PSSession : [Server] Connecting to remote server Server failed with the
following error message : WinRM cannot process the request. The following error
occurred while using Kerberos authentication: Cannot find the computer Server.
Verify that the computer exists on the network and that the name provided is
spelled correctly. For more information, see the about_Remote_Troubleshooting
Help topic.
At C:\AppServers\Application.ps1:8 char:8
+ $s = New-PSSession -ComputerName Server
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : OpenError: (System.Manageme....RemoteRunspace:RemoteRunspace) [New-PSSession], PSRemotingTransportException
+ FullyQualifiedErrorId : NetworkPathNotFound,PSSessionOpenFailed
The server is already enabled to receive remote requests.
Update:
Below is the full function that i am trying to run:
function audit-servers {
if (Test-path "ApplicationsOnTheServer.txt") {Remove-Item "ApplicationsOnTheServer.txt"}
if (Test-Path "ServersList.txt") {
foreach ($server in Get-Content .\ServersList.txt) {
"Application Server : $server`n" | out-file -FilePath "ApplicationsOnTheServer.txt" -Append
"Applications list:" | out-file -FilePath "ApplicationsOnTheServer.txt" -Append
$s = New-PSSession -ComputerName $server -Credential domainabc\myname
Invoke-Command -Session $s -ScriptBlock {Import-Module WebAdministration;Get-iissite} | out-file -FilePath "ApplicationsOnTheServer.txt" -Append
}
} else {
"ServersList.txt file is missing"
break;
}
"`nAll Done!`n"}
The ServersList.txt has atstappvmabc.tsteag.com

The error message clearly states that you wanted to connect to the server named Server not to the server which name is stored in $Server variable (text in bold is actually the name of the server you try to connect to):
New-PSSession : [Server] Connecting to remote server Server failed
If you tried to connect to the server named for example MyServer01.example.com you'd receive the error like below (truncated):
PS C:\> New-PSSession -ComputerName "MyServer01.example.com"
New-PSSession : [MyServer01.example.com] Connecting to remote server MyServer01.example.com failed (...)
Even though you state that you try to execute
$s = New-PSSession -ComputerName $Server
You actually execute (notice missing dollar sign)
$s = New-PSSession -ComputerName Server
The above was also taken from the error message you pasted. I'd suggest to first skip the variable and try to enter server path in the command itself to verify it's working:
$s = New-PSSession -ComputerName "MyServer01.example.com"
And then, if it works, put the path in variable and test again.

The error you're receiving FullyQualifiedErrorId : NetworkPathNotFound generally means that the name you're passing to the -ComputerName parameter can't be resolved.
Perhaps try running Test-Connection $Server to troubleshoot what's happening there.

Your variable $Server contains wrong value. You have to assign valid computer name to $Server.

Related

Test-Path Access denied Error - To check if Directory Exists on Shared Drive/Folder using powershell with credentials

I am trying to check if folder exists on network location using Test-Path powershell script with different credential having access to the Network Server but I am getting access denied error. Below is my script which I am trying to execute on local from where I am trying to connect to Network server:
$username="username"
$pass = "#Passw0rd" | ConvertTo-SecureString -AsPlainText -Force
$cred = New-Object -TypeName System.Management.Automation.PSCredential -ArgumentList $username,$pass
$pathExists = Invoke-Command -ComputerName . -Credential $cred -ScriptBlock {
Test-Path "\\serverName\Folder"
}
Write-Host $pathExists
I am getting below error:
Access is denied
+ CategoryInfo : PermissionDenied: (\serverName\Folder:String) [Test-Path], UnauthorizedAccessException
+ FullyQualifiedErrorId : ItemExistsUnauthorizedAccessError,Microsoft.PowerShell.Commands.TestPathCommand
+ PSComputerName : localhost
Note: Admin access for the account is given which is used for accessing Network path and directory
Any help will be much appreciated
The issue most likely is because the credentials stored in $cred don't have Admin privileges on your localhost, hence cannot impersonate your invocation.
Here I'm trying something similar to what you're trying, the user stored in $cred is an Administrator on remote host but does not have any permissions on my laptop (I'm obfuscating for obvious reasons):
PS C:\> icm remoteServer -Credential $cred {test-path \\remoteServer\c$\users}
True
PS C:\> icm remoteServer -Credential $cred {test-path \\localhost\c$\users}
True
PS C:\> icm -computername . -Credential $cred {test-path \\localhost\c$\users}
[localhost] Connecting to remote server localhost failed with the following error message : Access is denied. For more
information, see the about_Remote_Troubleshooting Help topic.
+ CategoryInfo : OpenError: (localhost:String) [], PSRemotingTransportException
+ FullyQualifiedErrorId : AccessDenied,PSSessionStateBroken
Edit:
Here is another solution to your problem, Start-Process using the remote credentials and save the results to a file (again obfuscating the name of the remote server):
$argument="-c `"`$path='\\remoteServer\c$\users';'Attempting Test-Path '+`$path;'Result is: '+(Test-Path `$path)`""
$initHash=#{
FilePath='powershell.exe'
Credential=$cred
ArgumentList=$argument
RedirectStandardOutput="$HOME\Documents\testPath.txt"
WindowStyle='Hidden'
}
Start-Process #initHash
PS C:\> gc "$HOME\Documents\testPath.txt"
Attempting Test-Path \\remoteServer\c$\users
Result is: True

Unresolved parameters (Invoke-Command)

When running the code below I get the error message
Invoke-Command : Missing an argument for parameter 'ComputerName'. Specify a
parameter of type 'System.String[]' and try again.
At line:11 char:16
+ Invoke-Command -ComputerName -ScriptBlock $scriptblock -Credential $Cred -Argum ...
+ ~~~~~~~~~~~~~
+ CategoryInfo : InvalidArgument: (:) [Invoke-Command],
ParameterBindingException
+ FullyQualifiedErrorId : MissingArgument,Microsoft.PowerShell.Commands.InvokeCommandCommand
The code:
$item = "1337"
$username = "username"
$password = "password"
$Cred = New-Object -TypeName System.Management.Automation.PSCredential -ArgumentList $username, ($password | ConvertTo-SecureString -AsPlainText -Force)
$scriptblock = {
New-PSDrive -Name SampleDC -PSProvider FileSystem -Root \\sampleDC\scripts
."C:\scripts\sample.ps1" # include global functions scripts
new_user $args[0] # new_user is a function in global functions
}
Invoke-Command -ScriptBlock $scriptblock -Credential $Cred -ArgumentList $item
You cannot run Invoke-Command with different credentials without specifying a computer. The error you're getting is because you used the parameter -ComputerName without an argument.
To have Invoke-Command run the scriptblock on the local computer use either of the following commands:
Invoke-Command -Computer . -ScriptBlock $scriptblock -Credential $Cred ...
Invoke-Command -Computer localhost -ScriptBlock $scriptblock -Credential $Cred ...
Invoke-Command -Computer $env:COMPUTERNAME -ScriptBlock $scriptblock -Credential $Cred ...
Note that if the user whose credentials you're passing does not have admin privileges you'll be getting an error like this:
[localhost] Connecting to remote server localhost failed with the following
error message : Access is denied. For more information, see the
about_Remote_Troubleshooting Help topic.
+ CategoryInfo : OpenError: (localhost:String) [], PSRemotingTransportException
+ FullyQualifiedErrorId : AccessDenied,PSSessionStateBroken
In that case you need to enable PowerShell Remoting for them first. Run the following command in an elevated PowerShell console and add the user or group in the dialog that pops up.
Set-PSSessionConfiguration Microsoft.PowerShell -ShowSecurityDescriptorUI
From the documentation:
HOW TO ENABLE REMOTING FOR NON-ADMINISTRATIVE USERS
ERROR: ACCESS IS DENIED
To establish a PSSession or run a command on a remote computer, the user must have permission to use the session configurations on the remote computer.
By default, only members of the Administrators group on a computer have permission to use the default session configurations. Therefore, only members of the Administrators group can connect to the computer remotely.
To allow other users to connect to the local computer, give the user Execute permissions to the default session configurations on the local computer.
The following command opens a property sheet that lets you change the security descriptor of the default Microsoft.PowerShell session configuration on the local computer.
Set-PSSessionConfiguration Microsoft.PowerShell -ShowSecurityDescriptorUI
The computername parameter is missing. I believe you need to be at an elevated prompt to invoke-command on localhost.

PSCredential variable stops working for WinRM function after being passed to get-winevent

I am seeing WinRM Client errors when reusing a Credential object, but only if I'm using it on Get-WinEvent, before I used it on Get-WindowsFeature.
If I replace the Get-WindowsFeature with an Invoke-Command calling Get-WindowsFeature against the server and using the same credentials object then things work as expected, but that causes other issues with different parts of my script, and I'd rather understand why it's not working.
I've stripped things down to the bare minimum to demonstrate the error and got to this.
$Cred = Get-Credential
$Name = "server01"
Get-WindowsFeature -ComputerName $Name -Credential $Cred
Get-winEvent -ComputerName $Name -Credential $Cred -MaxEvents 1
Get-WindowsFeature -ComputerName $Name -Credential $Cred
Expected Results
List of Windows features and their status on server01
The most recent event log entry on server01
List of Windows features and their status of server01
Actual Results
List of Windows features and their status on server01
The most recent event log entry on server01
Get-WindowsFeature : The WinRM client cannot process the request. Requests must include user name and password when Basic or Digest authentication mechanism is used. Add the
user name and password or change the authentication mechanism and try the request again.
At line:1 char:1
+ Get-WindowsFeature -ComputerName $Name -Credential $Cred
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : NotSpecified: (:) [Get-WindowsFeature], CimException
+ FullyQualifiedErrorId : Microsoft.Management.Infrastructure.CimException,Microsoft.Windows.ServerManager.Commands.GetWindowsFeatureCommand
why not try this instead
$Cred = Get-Credential
$Name = "server01"
invoke-command -ComputerName $Name -Credential $Cred -ScriptBlock {
Get-WindowsFeature
Get-winEvent -MaxEvents 1
Get-WindowsFeature
}

"Access denied" error when trying to enumerate drives on remote computers

I am trying to run a PowerShell command to get the total disk space of all drives for all our remote servers. When I run the command I am getting the error below. I have a text file which has names of the servers and I have also confirmed that WinRM is configured and is running.
$Servers = Get-Content "C:\users\anorris\desktop\DR\servers1.txt"
foreach ($s in $Servers) {
Invoke-Command -ComputerName $s {Get-PSDrive}
}
Error:
[ahv-a2acortst02] Connecting to remote server failed with the following error
message : Access is denied.
For more information, see the about_Remote_Troubleshooting Help topic.
+ CategoryInfo : OpenError: (:) [], PSRemotingTransportException
+ FullyQualifiedErrorId : PSSessionStateBroken
Agreed that the message 'Access is denied' is a dead giveaway that you don't have access.
I would create a credential variable and make sure it is a credential that has rights to the remote system.
$Creds = Get-Credential
then change your code to the following (I added the -scriptblock and the bolded text
$Servers = Get-Content "C:\users\anorris\desktop\DR\servers1.txt"
foreach ($s in $Servers) {
Invoke-Command -ComputerName $s -ScriptBlock {Get-PSDrive} -Credential $creds
}

invoke command on remote machine is not working using powershell

I ran the below commands on my machine to download data from one server to another server using the invoke command
Enable-PSRemoting -force
Enter-PSSession Server1
invoke-command -computername Server1 -credential:'dom\jack' {c:\temp.ps1 -server serverX -id 4231e429-d238-4e32-a1bb-0ee812cd3124 -download $true}
ERROR is: Failed: Access is denied. (Exception from HRESULT: 0x80070005 (E_ACCESSDENIED))
but when i run the above command on my machine as
c:\temp.ps1 -server serverX -id 4231e429-d238-4e32-a1bb-0ee812cd3124 -download $true
it works as expected.
Is there something i am missing when i execute it remotely....please help me.
thanks
Try this good References:
http://www.ravichaganti.com/blog/?p=1108
http://technet.microsoft.com/en-us/magazine/ff700227.aspx
It might be something to do with the TrustedHosts or Authentication
setting of a client. You can set it like this:WinRM set
winrm/config/client #{TrustedHosts="*"}
Read more about this here:
http://blogs.dirteam.com/blogs/sanderberkouwer/archive/2008/02/23/remotely-managing-your-server-core-using-winrm-and-winrs.aspx
I use
powershell.exe -ExecutionPolicy Unrestricted -WindowStyle Hidden -NoLogo
I use this code:
try
{
Invoke-Command -credential $testCred -computer $ServerName -scriptblock {
param([String]$scriptDeploy, [String]$destino) &"$scriptDeploy" 'parametro1' $destino
$ScriptBlockOutput = $Error
} -ArgumentList $RutaRemotaParaScriptDeInstalacion, "$dirRemotoDestino"
"`r`n`r`nOK para script de despliegue"
exit 0;
}
catch
{
"`r`n`r`nError en script de despliegue"
"`r`nError in " + $_.InvocationInfo.ScriptName + " at line: " + $_.InvocationInfo.ScriptLineNumber + ", offset: " + $_.InvocationInfo.OffsetInLine + ".";
exit -1
}
You need to enable remoting on the remote machine. You also need to make sure the firewall/anti virus does not block the remoting ports. These are port 5985 for http, or port 5986 for https.
If both machines on the same domain it's fairly easy to get working. If the machines are on different domains however then it's more complex. There's a registry setting that needs to be changed on the remote server, and you need to pass credentials. Have a read here for more info. There is of course ssl which can also be enabled, but that's another story.
There is a bug in your script.
You should not be executing Enter-PSSession before the Invoke-Command, because the Invoke-Command itself sets up the PSSession.
Use only this:
Invoke-command -computername Server1 -credential:'dom\jack' {c:\temp.ps1 -server serverX -id 4231e429-d238-4e32-a1bb-0ee812cd3124 -download $true}
... Without the Enter-PSSession