Powershell Access Denied Issue - windows

I'm trying to download registry hives from computers in my domain, and I'm testing some commands locally first. I have two machines (VMs) not on the same domain: SRV2K12 and US-TEST. I can run reg.exe save HKLM\SYSTEM \\SRV2K12\Hives\<hostname> (where is the local hostname manually typed) successfully on both machines. However, I ultimately need to run the commands remotely, so I'm using Invoke-Command. On my Win 2012 server, I can use Invoke-Command -computername SRV2K12 -ScriptBlock {reg.exe save HKLM\SYSTEM \\SRV2K12\Hives\<hostname> and it works as expected. On my Windows 7 and Windows 10 machines, it doesn't work. I get this error:
ERROR: Access is denied.
+ CategoryInfo : NotSpecified: (ERROR: Access id denied.: String) []. RemoteException
+ FullyQualifiedErrorId : NativeCommandError
+ PSComputerName : <hostname>
NotSpecified: (:) [], RemoteException
I can run Invoke-Command -ScriptBlock {reg.exe save HKLM\SYSTEM \\SRV2K12\Hives\US-TEST} on the US-TEST Windows 7 machine just fine, and it saves the hive to the remote computer. But when I add the -computername US-TEST attribute (on the Win 7 or 10 machine) it tells me access is denied.
Any ideas how I can get that to work? I have already ran enabled-psremoting -force on those machines and it completes successfully. I also ran Set-item wsman:localhost\client\trustedhosts -value * on both machines. No change.

2-Hop remoting is your problem, as BenH said CredSSP can resolve it but so can a small design change on your part, rather than trying to do the save from the remote host just return the data to your calling computer and do the save from there. Below is one way to do it, but you can get even more efficient and avoid the temp file if you use get-itemproperty instead of reg.exe Also please note that there is a good chance that this will not work when you use invoke-command with the -computername parameter targeting the computer you are running from, -computername needs to be called against a remote machine.
$SB = {
reg.exe save HKLM\SYSTEM "$($env:TMP)\reg"
$tempFile = gc "$($env:TMP)\reg"
return $tempFile
}
$result = Invoke-Command -ScriptBlock $SB -computername COMPUTERNAME
$result | Out-File \\SRV2K12\Hives\US-TEST

Related

Regarding permissions for Get-ScheduledTask via remote powershell

My problem is as follows:
I have two users on a windows server (Windows Server 2016). One is my regular user (with admin privileges) and the other a technical user.
I would like to probe for a given scheduled task on a remote machine (which is a Windows Server 2016 as well). To do so i use "Invoke-Command" and pass the session as follows:
Invoke-Command -Session $session -ScriptBlock { Get-ScheduledTask -TaskName <task_name>}
For my regular user this works (i am using localhost for testing, but also verified this against a different server)
For the technical user it does not. However, the command
Get-ScheduledTask -TaskName <task_name>
executed in the technical users' powershell WORKS.
Further (executed as the technical user), the following works as well
Invoke-Command -Session $session -ScriptBlock { Get-ChildItem C:\ }
So what i take from this is that for the technical user in general remoting works as well access to the scheduled tasks. However, somehow the combination does NOT.
The exception is get is
Access denied
+ CategoryInfo : PermissionDenied: (MSFT_ScheduledTask:Root/Microsoft/...T_ScheduledTask) [Get-ScheduledTask], CimException
+ FullyQualifiedErrorId : HRESULT 0x80041003,Get-ScheduledTask
+ PSComputerName : <hostname>
So obviously this is a permission issue. But i do not get what i need to change to fix it. I tried to compare the different permission between my regular user and the technical user, however I did not spot anything immediately obvious.
Does anyone know what needs to be changed?
"Enable Account" and "Remote Enable" permissions need to be be granted via WMI Control on Remote\Microsoft\TaskScheduler namespace.

Access Denied when using Power Shell Remoting with local account on Server Core 2019

I want to remotely trigger some commands with power shell on a Windows Server Core 2019.
I am using the following to enter the remote Session:
$Username = "x.x.x.x\Administrator"
$PasswordSS = ConvertTo-SecureString 'The-Password' -AsPlainText -Force
$Cred = New-Object System.management.Automation.PSCredential $Username,$PasswordSS
Enter-PSSession -ComputerName 'x.x.x.x' -Credential $cred
The connection then fails with the following message:
Enter-PSSession : Connecting to remote server x.x.x.x failed with the
following error message : Access is denied. For more information, see
the about_Remote_Troubleshooting Help topic. At line:4 char:2
+ Enter-PSSession -ComputerName 'x.x.x.x' -Credential $cred
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidArgument: (x.x.x.x:String) [Enter-PSSession], PSRemotingTransportException
+ FullyQualifiedErrorId : CreateRemoteRunspaceFailed
The remote computer is on the local network and I can ping it.
The Administrator account is a local account on the remote computer.
The remote ip is on the trusted host list on the client.
PSRemoting was enabled on the remote computer.
What am I missing? Help would be appreciated.
This ought to be in a comment. Not enough reps
a. Reset PSSession configurations:
https://stackoverflow.com/a/22385798/10994804
b. Add -ComputerName 'x.x.x.x to trusted hosts.
Get-Item WSMan:\localhost\Client\TrustedHosts
Set-Item WSMan:\localhost\Client\TrustedHosts -Value x.x.x.x -Force
CONTEXT ANALYSIS:
You chose another Input Language than the Time And Currency Format language during the installation. However, your choice is ignored for the Welcome Screen.
At the end of the installation, at the first boot, when you are asked to enter a password for the Administrator account, you type a password with the Time And Currency Format language but you are not aware of this.
At every login, you will use the Time And Currency Format language, until you change this behavior, but you are still not aware of it.
That's why you cannot:
PSRemote
RDP
change the local Administrator's password with ALT + CTRL + SUPPR
SOLUTION:
To be able to RDP or PSRemote, you must set the password again but with PowerShell
Set-LocalUser -Name Administrator -Password (Read-Host -AsSecureString)
However, now you won't be able to login with the console anymore.
To fix this you must change the Welcome screen language.
Easy graphical solution for a few computers:
In the command prompt type intl.cpl to open the Region control panel.
Go to the Administrative tab.
Click on the Copy settings button.
Check the Welcome screen and system accounts check box.
Click OK
PowerShell solution for many computers:
1.Check your current substitutes
Get-ItemProperty -Path 'HKCU:\Keyboard Laytout\Substitutes'
The complete list of Keyboard Identifiers can be found on Microsoft Docs:
Keyboard Identifiers and Input Method Editors for Windows
2.Check current substitutes of the Default user account
Get-ItemProperty -Path 'Registry::HKEY_USERS\.DEFAULT\Keyboard Layout\Substitutes'
3. Add one or all missing substitutes to the Default user account
New-ItemProperty -Path 'Registry::HKEY_USERS\.DEFAULT\Keyboard Layout\Substitutes' -Name '00000809' -Value '00000040c' -PropertyType 'String'
4. Just for information have a look at the current values of the Preload key of the Default user account
Get-ItemProperty -Path 'Registry::HKEY_USERS\.DEFAULT\Keyboard Layout\Preload'
5. Configure value 1 of the Preload key with the substitute name which will be used first on the Welcome screen. (If you want, you can also remove other values from the Preload key or even reorder them...)
Set-ItemProperty -Path 'Registry::HKEY_USERS\.DEFAULT\Keyboard Layout\Preload' -Name 1 -Value '00000809'

Invoke-Command Cannot Find Path But File Does Exist

I'm very new to Windows scripting and am having an issue with trying to execute a Powershell script located on a remote node.
It's a super simple HelloWorld script.
I'm setting up my session and issuing the remote invocation command like this ::
$session = New-PSSession -ComputerName DH2VCAUSPTCTX01.XXX.XXX.com -Credential XXX\XXX
Invoke-Command -Session $session -FilePath C:\Users\Public\EOD_CWx_Scripts\hello_world_PS.ps1
I keep getting this error ::
Invoke-Command : Cannot find path 'C:\Users\Public\EOD_CWx_Scripts\hello_world_PS.ps1' because it does not exist.
At line:1 char:1
+ Invoke-Command -Session $session -FilePath C:\Users\Public\EOD_CWx_Sc ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : ObjectNotFound: (C:\Users\Public...lo_world_PS.ps1:String) [Invoke-Command], ItemNotFoundException
+ FullyQualifiedErrorId : PathNotFound,Microsoft.PowerShell.Commands.InvokeCommandCommand
This is a screen shot of the Remote node showing that the file does indeed exist ::
This is a screen shot of me attempting to invoke the Powershell script on the remote node ::
Like I said, I'm really new to Windows scripting.
Is there something that I'm missing when it comes to remotely invoking Powershell scripts?
For reference, I've been using this resource to try and figure out how to do this :: https://msdn.microsoft.com/en-us/powershell/reference/5.1/microsoft.powershell.core/invoke-command

Install .net remotely via powershell

I’m attempting to install the .net framework on a windows server 2008 r2 machine remotely via PowerShell. Reading about it seems that this cannot be achieved through an existing PowerShell session but credentials need to be explicitly passed in (any idea why this is?). However, I'm still getting permission errors.
For example, If I run:
$cred = Get-Credential -Credential 10.20.0.13\administrator
$Session=New-PsSession -ComputerName 10.20.0.13 -Credential $cred
Invoke-command -ScriptBlock {Start-Process -FilePath c:\installers\dotNetFx40_Full_x86_x64.exe -ArgumentList "/q /norestart /log c:\" -Wait} -Credential $cred -ComputerName 10.20.0.13
I can see on the remote machine that the installer runs (in task manager), the temporary folder is created on the root of c:\, the files extracted and then I get a 700kb log file. At the foot of that log file I get:
OS Version = 6.1.7601, Platform 2, Service Pack 1 OS Description =
Win2K8R2 - x64 Standard Edition Service Pack 1 CommandLine =
C:\b65da67b927bfb71c84adcecefc019\Setup.exe /q /norestart /log c:\
/x86 /x64 TimeZone = GMT Standard Time Initial LCID = 2057 Using
Simultaneous Download and Install mechanism Operation: Installing
Package Name = Microsoft .NET Framework 4 Setup Package Version =
4.0.30319 User Experience Data Collection Policy: Disabled Number of applicable items: 11 Exe
(C:\b65da67b927bfb71c84adcecefc019\SetupUtility.exe) succeeded. Exe
Log File: dd_SetupUtility.txt ServiceControl operation succeeded!
ServiceControl operation succeeded! Exe
(C:\b65da67b927bfb71c84adcecefc019\Windows6.1-KB958488-v6001-x64.msu)
failed with 0x5 - Access is denied. . Final Result: Installation
failed with error code: (0x00000005), "Access is denied. " (Elapsed
time: 0 00:01:12).
So access is denied. However, using the exact same credentials I can perform other tasks (add server roles in Powershell, add windows features via powershell etc) and I can RDP onto the box using the same username/password and run the installer there (which completes fine).
I’m missing something somewhere, but can’t seem to find out what it is. I can see its worked for someone else (http://social.technet.microsoft.com/Forums/windowsserver/ar-SA/3045eb24-7739-4695-ae94-5aa7052119fd/install-dotnet-framework-4-using-powershell?forum=winserverpowershell) so no idea why I’m getting this.
Any help much appreciated.
Thanks
You're creating a session but never using it?
I haven't tried this on a remote computer beforey, but try to run the process "as admin" by using -Verb RunAs, like this:
$cred = Get-Credential -Credential 10.20.0.13\administrator
$Session=New-PsSession -ComputerName 10.20.0.13 -Credential $cred
Invoke-command -ScriptBlock {Start-Process -FilePath c:\installers\dotNetFx40_Full_x86_x64.exe -ArgumentList "/q /norestart /log c:\" -Wait -Verb RunAs } -Session $Session
While installation of .NET framework 4.0, It installs some updates as well (.msu) files.
But when we are installaing .NET 4.0 remotely, It fails because of these updates. The reason behind that is, it's not allowable to install these updates remotely. Please find the KB article here. This article also mentioned the workaround for this.
you have servername in textfile or machine names in OU based. create .bat which has .exe to run C:\temp\xxx.exe /S /qn
$ou='OU=subou3,OU=subou2,OU=subou1,DC=domain,DC=com'
$filter = #("machinename1", "machinename2")
$compute= Get-ADComputer -Filter * -SearchBase $ou | where-object{$filter -contains $_.name}
$comp=$compute.name
foreach ($Computer in $Comp) {
Write-Host "Processing $Computer"
{
Write-Host " Installing application on $Comp"
psexec $Compter path\XXX.bat /S /qn
}
}

How to keep remote powershell command alive after session end?

I use the following command to run setup_server.exe on remote Windows box:
powershell -command "$encpass=convertto-securestring -asplaintext RPASSWORD -force;$cred = New-Object System.Management.Automation.PSCredential -ArgumentList RUSER,$encpass; invoke-command -computername RCOMPUTERNAME -scriptblock {setup_server.exe} -credential $cred;"
setup_server.exe's task is to create some configuration files and start my_server.exe (some daemon process), then it finishes. And I want my_server.exe to keep running after setup_server.exe is finished.
So when I do it via CMD on local box (i.e. just run setup_server.exe from CMD) it works, but when I do it via powershell on remote host it doesn't work. Namely the my_server.exe gets started, but right after setup_server.exe is closed the server also gets closed(killed).
So the question is following:
Which powershell flags/cmdlets should I use to make the described scenario to work as in local mode?
NOTE: I want synchronously get output of setup_server.exe, so running remote command with -AsJob flag, probably wouldn't work for me, though I even don't know if it will keep the server alive after setup_server.exe's end.
The way to keep the remote PowerShell session running after the command has finished is to use a PSSession e.g.:
$s = new-PSSession computername
Invoke-Command -session $s { ..script.. }
... do other stuff, remote powershell.exe continues to run
Remove-PSSession $s # when you're done with the remote session
Generally though exes should run independently from the app that launched them.
Why are you using Invoke-Command. If you want a persistent Session, use Enter-PSSession.
$s = New-PSSession -Computername "Computername";
Enter-PSSession -Session $s;
setup_server.exe
# Once you are finnished
Exit-PSSession
With 'Enter-PSSession' you are not just Invoking some Command on the Server, you are directly logged-in like you probably know from SSH.
If you want your powershell session to keep running because you are running an exe, try using the -InDisconnectedSession switch. From what I understand, it will run the executable on the remote machine in a session that isn't actually connected to your computer. In essence, your computer will not destroy the session, when it disconnects, allowing the exe to continue to run.
invoke-command -computername RCOMPUTERNAME -scriptblock {start-process setup_server.exe} -InDisconnectedSession
If you need to do this on multiple computers. Setup an array of all the computer names.
Note: I don't believe this works with sessions that are already created.
In order to keep a powershell code running on the session exit it should be a process. And the windows way to keep the process is running a .exe or a windows service.
To keep a Powershell shell open after executing a command, I use the -NoExit switch, e.g. this script starts a remote interactive PS session on servername with user administrator
C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe -NoExit
-Command "Enter-PSSession -ComputerName servername -Credential administrator"
http://powershell-guru.com/powershell-tip-13-prevent-powershell-from-exiting-once-script-finished/

Resources