Invoke-Command to remote computer through teamcity - windows

I need to execute some code on remote machine, I use powershell's Invoke-Command to do that.
Invoke-Command -ComputerName TESTPC -ScriptBlock { Get-WMIObject Win32_ComputerSystem | Select-Object -ExpandProperty name };
It works on my local but fails in TeamCity server. It says: Connecting to remote server TESTPC failed with the following error message : Access is denied. For more information, see the about_Remote_Troubleshooting Help topic.. I tried to solve it this way https://stackoverflow.com/a/27872686/3561198 but the condition is always true and it looks like the script is run with admin rights. How to fix the issue? Otherwise suggest another way to execute some code on remote Windows machine.

Start an interactive session with the destination machine first and then use Invoke-Command to run the script block.
Enter-PSSession Server01
Invoke-Command -ComputerName Server01, Server02 -ScriptBlock { your code here }
Exit-PSSession

Related

Automating robocopy using powershell Invoke command - remote session

I want to automate robocopy through Azure powershell runbook and I am taking below steps but Its failing with access denied error for Source location. Service account used to create remote connection is admin user on both servers
Create remote session on destination server (using Azure Automation account runbook which is running on Hybrid worker )
run Invoke-command for ROBOCopy to pull data from source server to destination D drive.
Below code is not doing anything but runbooks status shows as complete
$serviceAccountPassword = (Get-AzureKeyVaultSecret -VaultName 'kvname' -Name 'secname').SecretValue
$credential = New-Object System.Management.Automation.PSCredential('serviceaccountname',
$serviceAccountPassword)
$session = New-PSSession -ComputerName 'destination_server' -Credential $credential
$scriptblock = {c:\Windows\System32\robocopy.exe \\source_server\Backups\ \\destination_server\d$\data\}
invoke-command -session $session -scriptblock $scriptblock
I have also enbled-Psremoting and also added service account as admin to both servers
Edit : If I don't run as JOB I get access denied error

Winrm not able to use dnscmd - Windows server 2012 R2 Standard server

I am trying to manage a Windows server 2012 R2 Standard server over winrm. On the server I would like to run dnscmd from the rsat package. You can see below if I just run the dnscmd in the power shell prompt it is successful. However when I invoke it remotely over winrm the command fails with ERROR_ACCESS_DENIED.
PS C:\Windows\system32> dnscmd adServer /RecordDelete mycompany.com newTestRecord A /f
Deleted A record(s) at mycompany.com
Command completed successfully.
PS C:\Windows\system32> Test-WsMan localhost
wsmid : http://schemas.dmtf.org/wbem/wsman/identity/1/wsmanidentity.xsd
ProtocolVersion : http://schemas.dmtf.org/wbem/wsman/1/wsman.xsd
ProductVendor : Microsoft Corporation
ProductVersion : OS: 0.0.0 SP: 0.0 Stack: 3.0
PS C:\Windows\system32> Invoke-Command -ComputerName localhost -ScriptBlock {
>> dnscmd adServer /RecordDelete mycompany.com newTestRecord A /f
>> }
Command failed: ERROR_ACCESS_DENIED 5 0x5
PS C:\Windows\system32> Invoke-Command -ComputerName localhost -ScriptBlock {
>> hostname
>> }
myServerHostname
The issue was double-hop/multi-hop. When you login over winRM it doesn't want to allow you to use the same credential token to reach to a different machine. I got around this issue by connecting over winrm then opening up a nested Powershell session. It's essentially refreshes the tokens allowing the user to connect to the active directory server.
Please see the following for more information
https://blogs.technet.microsoft.com/ashleymcglone/2016/08/30/powershell-remoting-kerberos-double-hop-solved-securely/
https://blogs.msdn.microsoft.com/sergey_babkins_blog/2015/03/18/another-solution-to-multi-hop-powershell-remoting/
Make sure to install Remote Server Administration Tools (RSAT) for dnscmd.
$password = '{pass}' | ConvertTo-SecureString -AsPlainText -Force
$username = '{user}'
$cred = New-Object System.Management.Automation.PSCredential -ArgumentList $username,$password
Invoke-Command -ComputerName localhost -Credential $cred -ConfigurationName svc_dns_middleMan -ScriptBlock {
'{dnscmd_commands}'
}

DCDIAG returns different output in PowerShell

When I run the command dcdiag /test:RIDManager in PowerShell in my Domain Controller, I get the test as passed.
But when I run it from another server in a different domain using Remote Session in PowerShell I get the test as failed.
$testSession= New-PSSession -ComputerName <hostname> -Credential Get-Credential
Invoke-Command -Session $testSession -ScriptBlock {dcdiag /test:RIDManager}
This command gives passed when I use the hostname of the Primary Domain Controller but failed for the Secondary Domain Controller. This comes as failed only when I run the command from as Computer in another domain.
I get the below error when failed:
DsBindWithSpnEx() failed with error 5,
Access is denied..
This issue is because of the double hop problem. So if you create a remote PS Session using Creedssp then the result is as it is in the target server.

Windows services not visible remotely

I'm struggling to figure out what is going on, but it has a pretty widespread effect on a system I'm working with.
I have several machines running a service, but when I try to query the service (both in .net and in powershell) the service is not found. When I connect to the machine via RDP, the service shows up. I've already confirmed that I had permissions on the service, including granting explicit permissions to the service for my user using subinacl.
I do get a result back from get-service -computername $server but it doesn't list the service I'm looking for. Is there a group policy or windows configuration that I'm missing here? Why would some services show up remotely but not all of them?
Any tips/advice on what to look for would be greatly appreciated.
EDIT: Using this command:
get-Service -computername $servername | Export-Csv C:\temp\Local.csv -notypeinformation
On the machine yields the following file:
https://drive.google.com/open?id=1aXvIgWT4NU2EN4j14JlxrY-jHGp-hG2Q
Running the same command remotely against the machine yields the following file:
https://drive.google.com/open?id=16NvRgrQsSGc9CKlqmIqntLy1bkLMl5tJ
EDIT2:
Command:
Get-Service -Computername $servername -Name 'AdobeARMservice'
Running Remotely Result:
Get-Service : Cannot find any service with service name
'AdobeARMservice'. At line:1 char:1
+ Get-Service -Computername $servername -Name 'AdobeARMservice'
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : ObjectNotFound: (AdobeARMservice:String) [Get-Service], ServiceCommandExcep
+ FullyQualifiedErrorId : NoServiceFoundForGivenName,Microsoft.PowerShell.Commands.GetServiceCommand
Running Locally Result:
Status Name DisplayName
------ ---- -----------
Running AdobeARMservice Adobe Acrobat Update Service
Edit3:
This issue can also be seen in the microsoft service list.
While locally on the machine:
While remote:
The powershell documentation for get-service says:
This cmdlet can display services only when the current user has
permission to see them. If this cmdlet does not display services, you
might not have permission to see them.
I would therefore assume that your remote user is a different user than the local user.
if you truly have access rights, you could just do this instead
invoke-command -computername $servername -scriptblock {get-service} | export-csv C:\temp\Local.csv -notypeinformation

Add user access to a shared folder in remote computer

My objective is to add users to a shared folder in the remote server. I know that netshare command can be used to add users to local folder.
net share PathName=D:/Projects /GRANT:XXXX,FULL
When i run the above command in the local machine, it works fine.
Since the shared folder is present in remote server, i tried wmic and the psExec options. But both did not work. Not sure what i am missing here
wmic /node:ComputerName process call create "cmd.exe net share PathName=D:/Projects /GRANT:XXXX,FULL"
and
psExec \\ComputerName cmd.exe "net share PathName=D:/Projects /GRANT:XXXX,FULL"
Assuming you're running Windows 8 (Server 2012) or newer, use the Grant-SmbShareAccess cmdlet and a remote CIM session:
$RemoteSession = New-CimSession -ComputerName RemoteComputerName
Grant-SmbShareAccess -Name ShareName -AccountName XXXX -AccessRights Full -CimSession $RemoteSession
On Windows 7, you can use Invoke-Command to run the net share command on the remote machine:
$RemoteSession = New-PSSession -ComputerName RemoteComputerName
Invoke-Command -Session $RemoteSession -ScriptBlock { net share PathName=D:/Projects /GRANT:XXXX,FULL }

Resources