Automating robocopy using powershell Invoke command - remote session - windows

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

Related

Installing certificate under a different user causes Access Denied while not logged in to VM

I'm building a VM image in Azure through automation pipelines using PowerShell. One of the requirements is to install a certificate on the CurrentUser store for a specific user. When I am currently logged into the VM, I can run the following command through Azure Run Commands:
$Credential = New-Object -TypeName System.Management.Automation.PSCredential -ArgumentList $User, $PWord
$session = New-PSSession $env:ComputerName -credential $Credential
$command = {
param($certPassword, $filePath)
Import-PfxCertificate -FilePath $filePath -CertStoreLocation Cert:\CurrentUser\My -Password $certPassword
}
Invoke-Command -ScriptBlock $command -ArgumentList $certPassword,$filePath -Session $session
When I am not currently logged into the VM under that user, I get an Access Denied error. The error goes away as soon as I login to the machine again. If I run the pipeline while I'm logged into the VM, it succeeds.
What is different about PowerShell permissions while I am logged into the VM?

Invoke-Command to remote computer through teamcity

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

How to run powershell scriptblock as domain user?

I have a script block that I'm trying to make it run as a different domain user.
$Username = 'domain\test'
$Password = '1234'
$pass = ConvertTo-SecureString -AsPlainText $Password -Force
$cred = New-Object System.Management.Automation.PSCredential -ArgumentList $UserName,$pass
Invoke-Command -ScriptBlock{
write-host "hello"
} -Credential $cred -ComputerName $env:COMPUTERNAME
When I run it I got the following error:
[test-pc] Connecting to remote server test-pc 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 se
rvice: "winrm quickconfig". For more information, see the about_Remote_Troubleshooting Help topic.
Why the script is trying to authenticate locally and not against the DC ?
Thanks
If you don't actually want to run the script remotely, you can use Start-Process to run Powershell as another user, which will then execute your command/script as that user.
(See powershell command line help for full syntax options and examples)
# Using Get-Credential to illustrate, substitute with your own credential code
$cred = Get-Credential
# Run Command:
Start-Process -FilePath Powershell -Credential $cred -ArgumentList '-Command', 'Write-Host "Hello"'
# Run Script:
Start-Process -FilePath Powershell -Credential $cred -ArgumentList '-File', 'C:\folder\script.ps1'

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 }

How to create a local windows user account using remote powershell?

tried creating users with powershel.This worked fine for local machine. But how to create a local user account in a remote machine using remote powershell?
The script localwindows.ps1 is
$comp = [adsi]'WinNT://machinename,computer';
$user = $comp.Create('User', 'account4');
$user.SetPassword('change,password.10');
$user.SetInfo();
I tried the same thing through C# :
PSCredential credential = new PSCredential(userName, securePassword);
WSManConnectionInfo connectionInfo = new WSManConnectionInfo(false, "machinename", 5985, "/wsman", shellUri, credential);
using (Runspace runspace = RunspaceFactory.CreateRunspace(connectionInfo))
{
runspace.Open();
String file = "C:\\localwindows.ps1";
Pipeline pipeline = runspace.CreatePipeline();
pipeline.Commands.AddScript(System.IO.File.ReadAllText(file));
pipeline.Commands.Add("Out-String");
// execute the script
Collection<PSObject> results = pipeline.Invoke();
}
This also works fine locally .But for remote computer its throwing exception "create :Access is denied ".
I was able to create a local user account in a remote computer using the following command :
Invoke-Command -ComputerName machineName -filepath c:\script.ps1 -credential $getcredential
The script is
$comp = [adsi]'WinNT://localhost,computer';
$user = $comp.Create('User', 'account11');
$user.SetPassword('change,password.10');
$user.SetInfo();
$user
Use the ADSI WinNT provider:
$username = "foo"
$password = "bar"
$computer = "hostname"
$prov = [adsi]"WinNT://$computer"
$user = $prov.Create("User", $username)
$user.SetPassword($password)
$user.SetInfo()
The powershell script invoke-Command executes any powershell script on a remote computer. You didn't say just how you use powershell to create the user, but as an example you write:
invoke-command -computername myserver {[ADSI]$server="WinNT://localhost";$HD=$server.Create("User","HD");$HD.SetPassword("H3lpD3>K");$HD.SetInfo()}
You can also execute your local powershell script remotely by using the -filepath parameter:
Invoke-Command -ComputerName MyRemoteServer -filepath c:\Scripts\DaScript.ps1
To enable remote commands you will have to enable winrm on the remote computer. you can do this by running
winrm quickconfig
On the remote computer.
If you have a PowerShell script to create a local user account locally on a server, then just simply use PSExec to run it on remote machines with administrative account
Invoke-Command works but you can also use Enter-PSSession -Computer to submit commands locally on a remote machine.
The following will prompt the user for the username and add them to the local Administrators group with no password:
$user = read-host 'What is the name of the local user you would like to add?'
net user /add $user
net localgroup Administrators /add $user
I don't know if the question is still relevant, but I have tried this out and found what needs to be fixed. When you create the directory entry object, use the following code
$objOu = New-Object System.DirectoryServices.DirectoryEntry("WinNT://$computer", $admin, $adminPass, "Secure")
The rest is the same.

Resources