invoke command on remote machine is not working using powershell - 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

Related

How to Install Windows Updates on Remote Computer with PowerShell

I'm trying to install Windows Updates on a Remote Computer with this command:
$InstallSplat = #{
AcceptAll = $true
SendReport = $true
IgnoreReboot = if ($Reboot) { $false } else { $true }
PSWUSettings = #{
SmtpServer = "my mail server"
From = "myfrom <myfrom#myfrom.com>"
To = "myto <myto#myto.com>"
Port = 25
}
}
Invoke-Command -ComputerName $_ -Credential $cred -AsJob -ArgumentList $InstallSplat -ScriptBlock {
param([hashtable]$InstallSplat)
Import-Module PSWindowsUpdate
Install-WindowsUpdate #InstallSplat
$Error | out-file C:\install\installwinupdate.log -Append
}
I pass a credential Object with domain admin privileges in $cred but I still always get this error
Install-WindowsUpdate : Access denied (Ausnahme von HRESULT: 0x80070005 (E_ACCESSDENIED)) In Zeile:4 Zeichen:25
+ Install-WindowsUpdate #InstallSplat
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : NotSpecified: (:) [Get-WindowsUpdate], UnauthorizedAccessException
+ FullyQualifiedErrorId : System.UnauthorizedAccessException,PSWindowsUpdate.GetWindowsUpdate
The Command Install-WindowsUpdate itself does not have a credential parameter I could use. The Command needs to run in an elevated PowerShell, but I use an elevated PowerShell when starting this command on my Computer.
I Also tried creating a New-PSSession with my $cred and run Invoke-Command -Session $session instead of Invoke-Command -ComputerName $_ with the same result.
Does anybody know what's happening here? Why do I get Access denied?
It can't have anything to do with passing the $InstallSplat because the same thing happens if I don't pass any parameter at all and write the parameters and their Values directly at the command instead of splatting.
The Problem was, that you can't Download or Install Updates on a machine from another remote machine. Here's a list what you can or can't do remotely when it comes to Windows Updates
The solution is, to create a scheduled task on each server you want to install updates from a remote script, and start that task.
luckily, when you use the PSWindowsUpdate module, you don't have to do that yourself, you can just use Invoke-WUJob (formerly Invoke-WUInstall) which does the trick for you.
I used it like so ($ServerData.Value contains a list of my Servers) and it works like a charm. It creates a scheduled task on each server, and runs them immediately, if you add the -RunNow Parameter.
invoke-WUJob -ComputerName $ServerData.Value -Script { Import-Module PSWindowsUpdate ; Install-WindowsUpdate -AcceptAll -SendReport -IgnoreReboot -PSWUSettings #{From='xy';Port=25;SmtpServer='xy';To='xy'} | Out-File C:\install\PSWindowsUpdateLog.txt -Append} -Confirm:$false -verbose -RunNow
Note that what you specify as a script block in -Script will be pasted to -Command " <here> " in your scheduled task, so you should work with ' inside -Script.

New-PSSession - WinRM cannot process the request

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.

Powershell invoke-command access is denied error - not a double hop

I am building a new network with Server 2016 and a handful of Windows 10 clients. I have run Enable-PSRemoting successfully on all the clients. From the server I run:
Invoke-Command -ComputerName $computer -Scriptblock {'test'}
which results in
[computer] Connecting to remote server failed with the following error message : Access is denied.
+ CategoryInfo: OpenError: (computer:string) [], PSRemotingTransportException
+ FullyQualifiedErrorId: AccessDenied,PSSessionStateBroken
Because I am only having the remote computer process a string I believe this is not related to the common double hop issue I see in the forums.
I can also run WinRM successfully on the client machines:
Test-WSMan $computer
If anyone has insight into other causes of the access denied error I would greatly appreciate some ideas on where to look.
Thanks.
You need to be in Remote management users group on target machine (if it's local account). This will be enough for Invoke-Command access
I guess it is a permission problem. Try to create PsSession object via
$s = New-PSSession -ComputerName "you_computer_name" -Credential(Get-Credential)
Call Invoke-Command with the beforehand created session object:
Invoke-Command -Session $s -ScriptBlock { Get-Service }
This should return a list of all services of remote machine.
Hope that helps.

Run .ps1 on remote machine

I need to execute powershell script on remote computer with admin privilegies.
I have 2 scripts: client and server.
When i start client.ps1 i invoke command on server machine but get access error. I get no error if I use simple code in server.ps1 like write-host "hello".
server.ps1:
Get-service -ComputerName 'client'
client.ps1:
$ScriptBlockContent = {
d:\server.ps1
}
$remote=New-PSSession -ComputerName 'server'
Invoke-Command $remote -ScriptBlock $ScriptBlockContent
Your problem is authentication. You have to enable the server to use your credentials for that. You can do this by using CredSSP.
Enable this on your client:
Enable-WSManCredSSP -Role Client -DelegateComputer ServerNameHere
Enable it on your server:
Enable-WSManCredSSP -Role Server
Now add this to your Invoke-Command:
-Credential Domain\YourUsername -Authentication CredSSP
A remark on that: With CredSSP, its easy to steal your credentials, if you connect to a compromised system (same as RDP). Be sure that you do this on secure computers only.
Your client is trying to open D:\server.ps1 and getting access denied. Your script block doesn't even contain the neccesary code to cause powershell to process the contents of the server.ps1 anyway. You have it way to complicated.
You need to properly define a script block:
$scriptblock = { Get-service -ComputerName 'client' }
$remote=New-PSSession -ComputerName 'server'
Invoke-Command $remote -ScriptBlock $scriptblock
Running this command will connect to the machine called 'Server' and tell it to run Get-Service on 'Client' You don't need a client.ps1 and server.ps1 It can all be done from 1 script.
You also need to ensure winrm is running and configured on the server.

Access is Denied when Reset-ComputerMachinePassword is run through Invoke-command

I'm using the following command to reset a remote machine'
s password.
$user="Domain\domainadmin";
$pass="dapassword" | ConvertTo-SecureString -AsPlainText -Force;
$creds=New-Object System.Management.Automation.PSCredential -ArgumentList $UserName, $pass;
Invoke-Command -Credential $creds -ComputerName "DomainControllerMachine" -ScriptBlock{
$ComputerName = #"
SomeRemoteHost
"#
Import-Module ActiveDirectory;
Reset-ComputerMachinePassword -Server ${ComputerName};
}
I keep getting 'Access is denied' error.
This command cannot be executed on target computer('DomainControllerMachine') due to following error: Access is
denied.
+ CategoryInfo : InvalidOperation: (DomainControllerMachine:String) [Reset-ComputerMachinePasswor
d], InvalidOperationException
+ FullyQualifiedErrorId : InvalidOperationException,Microsoft.PowerShell.Commands.ResetCompute
rMachinePasswordCommand
The account I use has all levels of access to the ActiveDirectory. So there won't be a issue with the credentials used for authentication.
If I run the same command on the 'DomainControllerMachine' (logged in as same user) it works fine.
Import-Module ActiveDirectory;
Reset-ComputerMachinePassword -Server "SomeRemoteHost";
Even the whole invoke-command block above just works without complaining on the DomainControllerMachine.
But when I do it remotely through Invoke-Command, or Enter-PSSession I get that dreaded access denied error..
I've also tried using CredSSP after setting up the WSManCredSSP (Client, delegation and Server) on the machines with no luck.
I may have missed something, or is there a better way to handle such a case?
It looks to me like you are running the Reset-computermachinepassword command on the domaincontroller. As far as I know it should be run on the computer that needs to be reset with the DC name in the -server field.
To do this you would need to run the command on the computer that needs it's credentials reset:
Reset-Computermachinepassword -server "DomainControllerMachine" -credential $PScredential
You can try to do it remotely with a PSsession if the computer has powershell remoting enabled. You will need to specify a different authentication method to reach a computer that has lost it's trust with the domain.
You can use Credssp but this will only work if your GPO allows delegating your credentials to the target computer.
Or you can use Basic authentication. But for that to work the Target must accept unencrypted traffic.
The command to do it remotely would probably look something like this:
$session = new-PSSession "targetcomputer" -Authentication Basic -Credential "Domain\domainadmin"
Invoke-Command -Session $session -scriptblock {Reset-Computermachinepassword -server "Domain\domainadmin"}