Deleting registry keys in batch file (ERROR: Access is denied) - powershell

I'm trying to delete registry keys in a batch file, here's what I'm doing.
reg delete "HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\CCM" /f
I'm recieving the following error:
ERROR: Access is denied.
Yet I can simply open regedit.exe and right click and delete the registry key no problem! To state the obvious, I have elevated the batch file instance as administrator, am logged in as administrator, and tried running the batch from a cmd and powershell instance both as administrator. The Administrator account has full permissions for the registry keys, which is why I'm able to delete them simply through the regedit GUI. This is part of a large batch file script, the point is I want the whole process to be automated. Any ideas?

Lots of companies have a GPO setting called 'Prevent Access To Registry Editing Tools' set to 'Yes'.
Maybe that is the culprit here. When you run regedit yourself, the machine wil probably show you a UAC message first and next you click 'OK' on that?
You may get a useful errormessage if you try to delete the key using a different scripting language like VBScript:
Const HKEY_LOCAL_MACHINE = &H80000002
Dim objReg, strKeyPath, strComputer
strComputer = "."
Set objReg = GetObject("winmgmts:{impersonationLevel=impersonate}!\\" & _
strComputer & "\root\default:StdRegProv")
strKeyPath = "SOFTWARE\Microsoft\CCM"
objReg.DeleteKey HKEY_LOCAL_MACHINE, strKeyPath
Set objReg = Nothing
or using PowerShell:
Remove-Item -Path 'HKLM:\SOFTWARE\Microsoft\CCM' -Recurse

More of a follow up to #Theo response, it seems like somethings preventing you access as that command should work. I would suggest trying his idea then if it does not work, trying this one.
Since you have admin access you could attempt to give Everyone perms to the key as all you want to do is simply remove it. The REGINI command can do this but will add some bulk to the script.
::Grant perms to REG key
echo \Registry\machine\SOFTWARE\Microsoft\NEW [7] >> "%~dp0KeyPermx.txt"
REGINI %~dp0KeyPermx.txt
del %~dp0KeyPermx.txt
::Remove the key
reg delete "HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\NEW" /f

Related

Required Help in RDP Automation

Below script is to Automate RDP and I am stuck with below two points:
How to map local drive as mapped drive in RDP session(tsclient) using
powershell script/command
Example like this in RDP : drivestoredirect:s:value
RDP Automation - PowerShell Script :
cmdkey /list | ForEach-Object{if($_ -like "*target=TERMSRV/*"){cmdkey /del:($_ -replace " ","" -replace "Target:","")}}
echo "Connecting to Server Name"
$Server="Server Name"
$User="Username"
$Password="Password"
cmdkey /generic:TERMSRV/$Server /user:$User /pass:$Password
mstsc /v:$Server
reg add "HKEY_CURRENT_USER\Software\Microsoft\Terminal Server Client" /v "AuthenticationLevelOverride" /t "REG_DWORD" /d 0 /f
You can't control all aspects of your connection when using mstsc.exe via command line. The information for mapping local resources in the TS session are stored in the RDP file.
If not specified, it will use the default.rdp file located in "My Documents" folder (hidden file).
If you configure the default RDP to map local resources, all subsequent connections will also have the local resources mapped... but if you change it again, it will apply to all next connections.
So a better approach will be to create one *.rdp file and use it as a template in your script:
Create Template RDP file:
Launch mstsc.exe
Configure all options as per your needs
Save the file somewhere and use it in your script (i.e C:\Temp\MyRDPtemplate.rdp)
Now, change your script in order to use this template file when connecting to a Server:
mstsc "C:\temp\MyRDPtemplate.rdp" /v:$Server
When you first connect to a Server while mapping local resources, you will receive a warning message:
If you want to avoid this message, add the following registry key before launching:
reg add "HKCU\Software\Microsoft\Terminal Server Client\LocalDevices" /v $Server /t "REG_DWORD" /d 0x4d /f
mstsc "C:\temp\MyRDPtemplate.rdp" /v:$Server
There may be a global parameter you can add to avoid this message for all Servers (like for "AuthenticationLevelOverride") but I don't know for sure.
On last word about the stored credentials... if you use cmdkey /generic:xxx, you don't need to specify the service type (TERMSRV), that's the purpose of the /generic switch. But it also works fine...
PS: Very last remark, if you want to bypass the certificate prompt (in case your server doesn't present a valid one, you should add the registry key AuthenticationLevelOverride before connecting to the Server. Also note that this key is valid for all connections.
Another choice is get a help form some 3rd-part tools for RDP.
https://github.com/VShawn/PRemoteM

Change Documents default location with powershell

I am trying to change the default location of the documents folder using powershell or cmd specifically.
What I have tried:
I have tried changing both the shell folders and user folders registry path and restarted the computer but nothing happens:
reg add "HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\Explorer\User Shell Folders" /f /v Personal /t REG_EXPAND_SZ /d "C:\users\JatonJustice\desktop\testfolder"
But I still see it in the users folder in documents(even after restarting. The picture below is after restarting the computer.):
I tried using the answer from here: Set location of Special Folders with PowerShell
However that didn't seem to do anything either:
If anyone has any ideas for this, that would be awesome. If I have to I guess I can use wswshell but that is the last resort.
I found out that reg add "HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\Explorer\User Shell Folders" /f /v Personal /t REG_EXPAND_SZ /d "C:\users\JatonJustice\desktop\testfolder" works but when you are using an azure domain account or an amazon workspace account, the registry location for the user shell folders will be in a different place
you can verify the user location of the shell folder key by navigating to HKEY_CURRENT_USER and double checking which account you are in. There are accounts like .DEFAULT, or S-1-5-18 (SYSTEM ACCOUNT), etc.

Working around the "You don't currently have permission to access this folder" issue for PowerShell

When navigating to C:\Users\%SomeUsername% as an administrator on a Windows 2008 R2 server I get the error You don't currently have permission to access this folder, Click Continue to permanently get access to this folder. Clicking Continue resolves this problem.
If I try the same by PowerShell (e.g. get-childitem 'C:\Users\' -Directory | get-childitem -Force; or some variant), any profiles to which I've not already granted myself access explicitly give the error Access to the path 'C:\Users\%SomeUsername%' is denied.; even with the Force switch included.
Is there a way to "click continue" via PowerShell; i.e. have the system give me access to anything which I don't strictly have access to, though as an administrator on the server can grant myself access to. Ideally this would be done as I access the files (e.g. by a switch on the Get-Item command) rather than having to code something to explicitly go through all files checking and amending permissions.
Make sure about start Powershell Run As Admin if you want always run it as administrator make shortcut from powershell.exe and follow this image :
My mistake; I hadn't been running the PowerShell session as administrator (i.e. UAC).
right click on powershell.exe
run as administrator

Deleting all locally stored user profiles on log off

I want to delete all locally stored user profiles on logoff using a Powershell script. I've the following script:
Set-ExecutionPolicyRemoteSigned[gc]::collect()
cmd /c start reg unload "HKCU"Remove-PSDrive HKCU import-module C:\Windows\System32\WindowsPowerShell\v1.0\Modules\ManageUserProfiles\ManageUserProfiles.PSM1
get-userprofile |where{ $_.SID -ne ("S-1-5-21-3071724114-2656578308-4228372245-500")} | remove-userprofile
I'm a complete newbie to powershell. So could someone tell me whether this script meets my needs and how does it run? And could you also explain what $_.SID -ne ("S-1-5-21-3071724114-2656578308-4228372245-500") means too. Thanks in advance.
I am not familiar with the module that you are running, and it looks like that should be 6 lines not 3 (insert break before [gc], before Remove-PSDrive, and before Import-Module).
Next, add a space between Set-ExecutionPolicy and RemoteSigned.
Now, the script appears to collect user profiles, pipes them through a Where statement that excludes the Administrator account from the list of profiles, and then removes all remaining profiles. Let's step through it...
Set-ExecutionPolicy RemoteSigned
This sets your execution policy. I'm going to assume this is to avoid issues with an unsigned module that you load in a couple steps.
[gc]::collect()
This forces the garbage collection to clean up memory and remove unused resources. This line can probably be skipped.
cmd /c start reg unload "HKCU"
This uses the reg.exe command line application to unload the HKEY_CURRENT_USER hive from within the current registry set. This would need to be done before deleting a profile since you can't delete files that are in use.
Remove-PSDrive HKCU
This does pretty much the same thing, but for PowerShell's registry provider. I'm guessing this is so that you don't get errors, or so that it doesn't try to reload the HKCU hive.
C:\Windows\System32\WindowsPowerShell\v1.0\Modules\ManageUserProfiles\ManageUserProfiles.PSM1
This loads the 'Manage User Profiles' module. I am not familiar with the module, but you would need to make sure that you have that module installed on the computer that this is running on, so if you are running this on all of your computers you need to install that module on all of your computers.
get-userprofile |where{ $_.SID -ne ("S-1-5-21-3071724114-2656578308-4228372245-500")} | remove-userprofile
This is a command from the module you just loaded. It will, I assume, get user profiles as some sort of custom object, and then it pipes to a Where statement that excludes the Administrator account by stating that it only allows profile objects that do not (-ne is the 'not equal' operator) have a SID property equal to "S-1-5-21-3071724114-2656578308-4228372245-500". So all user profiles except the admin account's profile are then piped to the Remove-UserProfile command, which we can probably assume deletes each profile that is piped to it.
Hopefully that explains what your script is doing.

Run as administrator, but still "requested registry access is not allowed"

I have a Windows PowerShell script. I logged into Windows as an administrator and run the script with PowerShell running as an administrator, and it worked; I could see all the changes happen after running this script.
But I still get the red error message:
requested registry access is not allowed
which is driving me nuts.
Why am I getting this error and how can I make it go away?
If you run regedit and navigate to the key that you are trying to access with your script, you can right click on it and view the permissions. You can see on that key what permissions Administrator has (Full Control, Read, Special Permissions)
This PowerShell trick worked for me:
$Path = "SOFTWARE\Microsoft\Windows\CurrentVersion\Explorer\FileExts\.jpeg\UserChoice"
$SubKey = [Microsoft.Win32.Registry]::CurrentUser.OpenSubKey($Path, [Microsoft.Win32.RegistryKeyPermissionCheck]::ReadWriteSubTree, [System.Security.AccessControl.RegistryRights]::ChangePermissions)
$Acl = $SubKey.GetAccessControl()
$RemoveAcl = $Acl.Access | Where-Object {$_.AccessControlType -eq "Deny"}
$Acl.RemoveAccessRule($RemoveAcl)
$SubKey.SetAccessControl($Acl)
$SubKey.Close()
**in $Path ==> change this to your path (path after Root folder)
**in $SubKey ==> [Microsoft.Win32.Registry]::CurrentUser : change this to your needed root Registry path
Try as Local System via psexec
This here worked for me:
get psexec.exe from here: https://learn.microsoft.com/en-us/sysinternals/downloads/psexec
use psexec.exe -i -s powershell.exe to start a new interactive (-i parameter) powershell.exe window as user Local System (-s parameter).
Inside that new powershell window try your command again.