Sie sind auf Seite 1von 31

SysAdminMagazine

Sysadmins’ Most
Wanted How-to’s
SysAdmin Magazine June 2019

SysAdmin Contents
Magazine

49
03 How to create new Active Directory users with PowerShell
June ‘19

08 How to manage file system ACLs with PowerShell scripts

17 How to protect credentials in Windows Server 2016


SysAdmin Magazine is a free
source of knowledge for IT Pros
20 How to perform Windows Registry repair and fix errors
who are eager to keep a tight
grip on network security and do
the job faster. 25 How to automate PowerShell scripts with Task Scheduler

30 Free tool of the month: Account Lockout Examiner

The Sysadmin Magazine team


sysadmin.magazine@netwrix.com

2
SysAdmin Magazine June 2019

How to Create Create New User Accounts Using the New-Aduser Cmdlet
So what is the PowerShell cmdlet used to create user objects? It’s the New-ADUser cmdlet, which is included in the Active Directory

New Active PowerShell module built into Microsoft Windows Server 2008R2/2012 and above. Therefore, the first thing we need to do is enable
the AD module:

Directory Users Import-Module ActiveDirectory

with PowerShell Now let’s take a closer look at cmdlet New-ADUser. We can get its full syntax by running the following command:

Get-Command New-ADUser –Syntax

Jeff Melnick
IT Security Expert, Blogger

The easiest way to create a new user in an Active Directory


domain is using the Active Directory Users and Computers
MMC snap-in. However, what if you need to create multiple
user accounts in bulk, or ADUC is not available for some
reason? In this article, we explain several ways to create
Active Directory user accounts with PowerShell using the
New-ADUser cmdlet.

When you know the syntax, it’s easy to add users to Active Directory:

New-ADUser B.Johnson

3
SysAdmin Magazine June 2019

Now let’s check whether the user was added successful- Create a New Active Directory User •• Password Input
ly by listing all Active Directory users using the following
script:
Account with Password •• Status – Enabled

Accounts are created with the following default properties:


Here’s the script we’ll use:
Get-ADUser -Filter * -Properties samAccount-
•• Account is created in the “Users” container.
Name | select samAccountName
New-ADUser -Name "Jack Robinson" -GivenName
•• Account is disabled.
"Jack" -Surname "Robinson" -SamAccountName
•• Account is a member of Domain Users group. "J.Robinson" -UserPrincipalName "J.Robinson@
enterprise.com" -Path "OU=Managers,DC=en-
•• No password is set. terprise,DC=com" -AccountPassword(Read-Host
-AsSecureString "Input Password") -Enabled
•• User must reset the password at the first logon.
$true

Therefore, to make a new account that’s actually usable,


we need to enable it using the Enable-ADAccount cmdlet The Read-Host parameter will ask you to input new pass-
and give it a password using the Set-ADAccountPassword word. Note that the password should meet the length,
cmdlet. complexity and history requirements of your domain se-
curity policy.
So let’s create a new account with the following attributes:
There it is, the last one in the list!
Now let’s take a look at the results by running the following
•• Name – Jack Robinson
cmdlet:
•• Given Name – Jack
Get-ADUser J.Robinson -Properties Canoni-
•• Surname – Robinson
calName, Enabled, GivenName, Surname, Name,

•• Account Name – J.Robinson UserPrincipalName, samAccountName, whenCre-


ated, PasswordLastSet | Select Canonical-
•• User Principal Name – J.Robinson@enterprise.com Name, Enabled, GivenName, Surname, Name,
UserPrincipalName, samAccountName, whenCre-
•• Path address – “OU=Managers,DC=enterprise,DC=com”
ated, PasswordLastSet

4
SysAdmin Magazine June 2019

Free Guide

SQL Server
Security Best
Practices
Now let’s make our script more flexible by adding the Read-
Host parameter, which will ask for the name and number of
Create AD Users in Bulk with a PowerShell Script users:

Now, let’s make our task a little bit harder and create ten similar Active Directory accounts in bulk, for example, for our company’s IT
class, and set a default password (P@ssw0rd) for each of them. To send the default password in a protected state, we must use the
path="OU=IT,DC=enterprise,DC=com"
ConvertTo-SecureString parameter. Here’s the script to use:
$username=Read-Host "Enter name"
$n=Read-Host "Enter Number"
$count=1..$n
$path="OU=IT,DC=enterprise,DC=com"
foreach ($i in $count)
$username="ITclassuser"
{ New-AdUser -Name $username$i -Path $path
$count=1..10
-Enabled $True -ChangePasswordAtLogon $true
foreach ($i in $count)
`
{ New-AdUser -Name $username$i -Path $path -Enabled $True -ChangePasswordAtLogon $true `
-AccountPassword (ConvertTo-SecureString "P@
ssw0rd" -AsPlainText -force) -passThru }
-AccountPassword (ConvertTo-SecureString "P@ssw0rd" -AsPlainText -force) -passThru }

5
SysAdmin Magazine June 2019

Import AD Users from a CSV File


Another option for creating users in AD is to import them
from a CSV file. This option is great when you have a list of
users with predefined personal details such as:

•• FirstName

•• LastName

•• Username

•• Department

•• Password

•• OU

6
SysAdmin Magazine June 2019

The CSV file must be in UTF8 encoding and contain contact data that looks like this:
if (Get-ADUser -F {SamAccountName -eq
$Username})
{
#If user does exist, output a
warning message
Write-Warning "A user account
$Username has already exist in Active Direc-
tory."
}
else
{
#If a user does not exist then
TThe following script will create enabled user objects for any users in the CSV that don’t already have accounts in AD. The “Reset pass- create a new user account

word at the next logon” option will be enabled for the new accounts, so you can use your default password: #Account will be created in the OU
listed in the $OU variable in the CSV file;
don’t forget to change the domain name in
#Enter a path to your import CSV file the"-UserPrincipalName" variable
$ADUsers = Import-csv C:\scripts\newusers.csv New-ADUser `
-SamAccountName $Username `
-UserPrincipalName "$Username@
foreach ($User in $ADUsers) yourdomain.com" `
{ -Name "$Firstname $Lastname" `
-GivenName $Firstname `
-Surname $Lastname `
$Username = $User.username -Enabled $True `
-ChangePasswordAtLogon $True `
$Password = $User.password
-DisplayName "$Lastname, $First-
$Firstname = $User.firstname name" `
$Lastname = $User.lastname -Department $Department `
-Path $OU `
$Department = $User.department -AccountPassword (convertto-se-
$OU = $User.ou curestring $Password -AsPlainText -Force)

}
#Check if the user account already exists in AD }

7
SysAdmin Magazine June 2019

After script execution, we have two new users, Edward Franklin and Bill Jackson, in our Active Directory domain: Let’s take a look at their details by running Get-ADUser cm-
dlet again:

Get-ADUser E.Franklin -Properties Canoni-


calName, Enabled, GivenName, Surname, Name,
UserPrincipalName, samAccountName, whenCre-
ated, PasswordLastSet | Select Canonical-
Name, Enabled, GivenName, Surname, Name,
UserPrincipalName, samAccountName, whenCre-
ated, PasswordLastSet

Windows PowerShell
Scripting Tutorial for
Beginners
Free Download

8
SysAdmin Magazine June 2019

How to Manage
There are both basic and advanced NTFS permissions. You can •• List Folder/Read Data: Users can view a list of files
set each of the permissions to “Allow” or “Deny”. Here are the and subfolders within the folder as well as the content
basic permissions: of the files.

File System ACLs •• Full Control: Users can modify, add, move and delete
•• Read Attributes: Users can view the attributes of a file or
folder, such as whether it is read-only or hidden.

with PowerShell
files and directories, as well as their associated proper-
ties. In addition, users can change permissions settings •• Write Attributes: Users can change the attributes of a
for all files and subdirectories. file or folder.

•• Modify: Users can view and modify files and file proper- •• Read Extended Attributes: Users can view the extended
ties, including deleting and adding files to a directory or attributes of a file or folder, such as permissions and cre-
Ryan Brooks
Cybersecurity Expert, Netwrix Product Evangelist file properties to a file. ation and modification times.

•• Read & Execute: Users can run executable files, including •• Write Extended Attributes: Users can change the ex-
script tended attributes of a file or folder.
Many organizations with a Microsoft Windows environ-
•• Read: Users can view files, file properties and directories. •• Create Files/Write Data: The “Create Files” permission
ment rely on NTFS as the main file system for their storage
allows users to create files within the folder. (This per-
devices that contain sensitive data. It is the easiest way for •• Write: Users can write to a file and add files to directories.
mission applies to folders only.) The “Write Data” per-
users to work with files. In order to implement a least-priv-
mission allows users to make changes to the file and
ilege model, which is a best practice for system security,
Here is the list of advanced permissions: overwrite existing content. (This permission applies to
IT security specialists and system administrators configure
files only.)
NTFS access control lists (ACLs) by adding access control •• Traverse Folder/Execute File: Users can navigate
entries (ACEs) on NTFS file servers. through folders to reach other files or folders, even if •• Create Folders/Append Data: The “Create Folders”
they have no permissions for these files or folders. Us- permission allows users to create folders within a folder.
ers can also run executable files. The Traverse Folder (This permission applies to folders only.) The “Append

NTFS Permissions Types for Files and permission takes effect only when the group or user
doesn’t have the “Bypass Traverse Checking” right in
Data” permission allows users to make changes to the
end of the file, but they can’t change, delete or overwrite
Folders the Group Policy snap-in. existing data. (This permission applies to files only.)

9
SysAdmin Magazine June 2019

•• Delete: Users can delete the file or folder. (If users don’t NTFS permissions can be either explicit or inherited. Explic-
have the “Delete” permission on a file or folder, they can it permissions are permissions that are configured individ-
still delete it if they have the “Delete Subfolders And Files” ually, while inherited permissions are inherited from the
permission on the parent folder.) parent folder. The hierarchy for permissions is as follows:

•• Read Permissions: Users can read the permissions of a •• Explicit Deny


file or folder, such as “Full Control”, “Read”, and “Write”.
•• Explicit Allow
•• Change Permissions: Users can change the permissions If you want to get a full NTFS permissions report via Power-
•• Inherited Deny
of a file or folder. Shell, you can follow this easy how-to about exporting NTFS
•• Inherited Allow permissions to CSV.
•• Take Ownership: Users can take ownership of the file
or folder. The owner of a file or folder can always change
Now that we know NTFS permissions are, let’s explore how
permissions on it, regardless of any existing permissions
to manage them.
that protect the file or folder.

•• Synchronize: Users can use the object for synchroniza- Copy File and Folder Permissions
tion. This enables a thread to wait until the object is in the
signaled state. This right is not presented in ACL Editor.
Get ACL for Files and Folders To copy permissions, a user must own both the source and
target folders. The following command will copy the per-
You can read more about it here. The first PowerShell cmdlet used to manage file and folder
missions from the “Accounting” folder to the “Sales” folder:
permissions is “get-acl”; it lists all object permissions. For
ou can find all these user permissions by running the fol- example, let’s get the list of all permissions for the folder
lowing PowerShell script: with the object path “\\fs1\shared\sales”: get-acl \\fs1\shared\accounting | Set-Acl
\\fs1\shared\sales

[system.enum]::getnames([System.Security. get-acl \\fs1\shared\sales | fl


AccessControl.FileSystemRights])

10
SysAdmin Magazine June 2019

Set File and Folder Permissions


The PowerShell “set-acl” cmdlet is used to change the se-
curity descriptor of a specified item, such as a file, folder
or a registry key; in other words, it is used to modify file
or folder permissions. The following script sets the “Full-
Control” permission to “Allow” for the user “ENTERPRISE\T.
Simpson” to the folder “Sales”:

$acl = Get-Acl \\fs1\shared\sales

$AccessRule = New-Object System.Security.


AccessControl.FileSystemAccessRule("ENTER-
PRISE\T.Simpson","FullControl","Allow")

$acl.SetAccessRule($AccessRule)

$acl | Set-Acl \\fs1\shared\sales$acl | Set-


Acl \\fs1\shared\sales

As we can see from the output of the “get-acl” commands before and after the permissions copy, the “Sales” shared folder per-
missions have been changed.

11
SysAdmin Magazine June 2019

Set-SPUser -Identity "i:0#.w|enterprise\t.


simpson" -Web http://sharepoint/sites/ent
-AddPermissionLevel "Contributor"

If you want to set other permissions to users or security groups, choose them from the table below:

Access Right Access Right’s Name in PowerShell

Full Control FullControl

Traverse Folder / Execute File ExecuteFile

List Folder / Read Data ReadData

Read Attributes ReadAttributes

Read Extended Attributes ReadExtendedAttributes

Create Files / Write Data CreateFiles

Create Folders / Append Data AppendData

Write Attributes WriteAttributes

Write Extended Attributes WriteExtendedAttributes

Delete Subfolders and Files DeleteSubdirectoriesAndFiles

Delete Delete

Read Permissions ReadPermissions

12
SysAdmin Magazine June 2019

There are also permissions sets of basic access rights that can be applied:

Access Right Access Right’s Name in PowerShell Name of the Set in PowerShell

Read List Folder / Read Data Read

Read Attributes

Read Extended Attributes

Read Permissions

Write Create Files / Write Data Write

Create Folders / Append Data

Write Attributes

Write Extended Attributes

Read and Execute Traverse folder / Execute File ReadAndExecute

List Folder / Read Data

Read Attributes

Read Extended Attributes

Read Permissions

Modify Traverse folder / Execute File Modify

List Folder / Read Data

Read Attributes

Read Extended Attributes

Create Files / Write Data

Create Folders / Append Data

Write Attributes

Write Extended Attributes

Delete

Read Permissions

13
SysAdmin Magazine June 2019

Remove User Permissions


To remove a permission, use the “RemoveAccessRule” pa-
rameter. Let’s delete the “Allow FullControl” permission for
T.Simpson to the “Sales” folder:

$acl = Get-Acl \\fs1\shared\sales

$AccessRule = New-Object System.Security.


AccessControl.FileSystemAccessRule("ENTER-
PRISE\T.Simpson","FullControl","Allow")

$acl.RemoveAccessRule($AccessRule)
Notice that T.Simpson still has the “Deny FullControl” permission. To remove it, let’s use the command “PurgeAccessRules”,

$acl | Set-Acl \\fs1\shared\sales which will completely wipe T.Simpson’s permissions to the “Sales” folder:

$acl = Get-Acl \\fs1\shared\sales

$usersid = New-Object System.Security.Principal.Ntaccount ("ENTERPRISE\T.Simpson")

$acl.PurgeAccessRules($usersid)

$acl | Set-Acl \\fs1\shared\sales

14
SysAdmin Magazine June 2019

Let’s disable inheritance for the “Sales” folder and delete


all inherited permissions as well:

$acl = Get-Acl \\fs1\shared\sales

$acl.SetAccessRuleProtection($true,$false)

$acl | Set-Acl \\fs1\shared\sales

Note that “PurgeAccessRules” doesn’t work with a string user name; it works only with SIDs. Therefore, we used the “Ntaccount”
class to convert the user account name from a string into a SID. Also note that “PurgeAccessRules” works only with explicit per-
missions; it does not purge inherited ones.

Now we have only one access permission left (because it


Disable or Enable Permissions Inheritance was added explicitly); all inherited permissions were re-
moved.
To manage inheritance, we use the “SetAccessRuleProtection” method. It has two parameters:

•• The first parameter is responsible for blocking inheritance from the parent folder. It has two states: “$true” and “$false”. Let’s revert this change and enable inheritance for the
folder “Sales” again:
•• The second parameter determines whether the current inherited permissions are retained or removed. It has the same two
states: “$true” and “$false”.

15
SysAdmin Magazine June 2019

$acl = Get-Acl \\fs1\shared\sales


$acl.SetAccessRuleProtection($false,$true)
$acl | Set-Acl \\fs1\shared\sales

Notice that we again used the “Ntaccount” class to convert


the user account name from a string into a SID.

Note that the “SetOwner” method does not enable you to NTFS
Permissions
change the owner to any account you want; the account
must have the “Take Ownership”, “Read” and “Change Per-

Change File and Folder Ownership


Management
missions” rights.

If you want to set an owner for a folder, you need to run the As you can see, it is very easy to manage NTFS permissions
“SetOwner” method. Let’s make “ENTERPRISE\J.Carter” the
owner of the “Sales” folder:
with PowerShell. But don’t forget to audit NTFS permis-
sions as well — it’s critical for security to track all changes
Best Practices
made to your file servers in order to reduce data leakage
$acl = Get-Acl \\fs1\shared\sales and combat the insider threat and other IT security risks.
$object = New-Object System.Security.Princi- Here is a basic guide on how to audit NTFS permissions Free Download
pal.Ntaccount("ENTERPRISE\J.Carter") with PowerShell.
$acl.SetOwner($object)
$acl | Set-Acl \\fs1\shared\sales

16
SysAdmin Magazine June 2019

How to Protect
are less secure. For example, Windows does not cache the For user accounts that need less stringent protection, you
credentials of members of this group locally, so they are nev- can use the following security options, which are available for
er left on workstations for attackers to harvest. In addition, any AD account:

Credentials in user accounts that are members of this group cannot:

•• Use default credentials delegation


•• Logon Hours — Enables you to specify when users can
use an account.

Windows Server •• Use Windows Digest •• Logon Workstations — Enables you to limit the com-
puters the account can sign in to.

2016
•• Use NTLM
•• Password Never Expires — Absolves the account from
•• Use Kerberos long-term keys
the “Maximum password age” policy setting; don’t con-
•• Sign on offline figure this option for privileged accounts.

Adam Stetson •• Use NT LAN Manager (NTLM) for authentication •• Smart card is required for interactive logon — Re-
Systems Engineer, Security Expert
quires a smart card to be presented for the account to
•• Use DES for Kerberos pre-authentication
sign in.
•• Use RC4 cipher suites for Kerberos pre-authentication
•• Account is sensitive and cannot be delegated — En-
Credentials are the keys to an account. By harvesting creden-
•• Be delegated privileges using constrained delegation sures that trusted applications cannot forward the ac-
tials, attackers can enter your network, move laterally and
count’s credentials to other services or computers on
escalate their privileges to steal your data. Windows Server •• Be delegated privileges using unconstrained delegation
the network.
2016 has several features for minimizing the chance that at-
•• Renew user ticket-granting tickets (TGTs) past the initial
tackers will be able to harvest credentials; •• This account supports Kerberos AES 128-bit encryption
240-minute lifetime
— Allows Kerberos AES 128-bit encryption.

•• This account supports Kerberos AES 256-bit encryption


Using the Protected Users Group — Allows Kerberos AES 256-bit encryption. Use this op-

Putting users, especially highly privileged users, in the “Pro- Using Account Preferences tion for privileged accounts.

tected Users” group helps you protect against compromise •• Account expires — Enables you to specify an end date
of their credentials by disabling authentication options that User Accounts for the account.

17
SysAdmin Magazine June 2019

Computer Accounts sources on the network. (It’s also possible to create user ac- Using Windows Defender Credential
In addition to controlling user accounts, you also need to un-
counts and configure them to run as service accounts, but
that is not convenient.)
Guard
derstand and manage the reach of computer and service ac-
Windows Defender Credential Guard is a new technology in
counts. When you join a computer to the domain for the first
There are three types of built-in service accounts: Windows 10 and Windows Server 2016 that helps to protect
time, Windows creates a computer account in Active Directo-
credentials from attackers who try to harvest them by using
ry in the “Computers” container and automatically assigns it a •• Local system — The NT AUTHORITY\SYSTEM account has
malware. Windows Defender Credential Guard uses virtual-
password. AD manages these passwords and updates them privileges equivalent to the local Administrators group on
ization-based security that allows you to isolate secrets, such
automatically every 30 days. the computer.
as cached credentials, so that only privileged software can
•• Local service — The NT AUTHORITY\LocalService account access them.
To manage the permissions of computer accounts and con-
has privileges equivalent to the local Users group on the
trol which Group Policies are applied to them, you can add
computer. In virtualization-based security, the specific processes that
them to groups and move them to different OUs. You can
use credentials or data, and the memory associated with
also disable and reset computer accounts: •• Network service — The NT AUTHORITY\NetworkService
those processes, run in a separate operating system paral-
account has privileges equivalent to the local Users group
•• Disabling a computer account means that the computer lel with, but independent of, the host operating system. This
on the computer.
cannot connect to the domain anymore. If you delete a virtual operating system protects processes from attempts
computer account and the computer is still operational, by any external software to read the data that those process-
To protect these accounts, ensure a sysadmin updates their
you’ll need to rejoin the computer to the domain if you es store and use. Windows Defender Credential Guard takes
passwords on a regular basis. This is a manual process if you
want it to regain domain membership. advantage of hardware security, including secure boot and
use native tools.
virtualization.
•• Resetting a computer account removes the connection
between the computer and the domain.
You can manage Windows Defender Credential Guard using
Group Managed Service Accounts and Virtual Accounts
Group Policy, Windows Management Instrumentation (WMI),
A Group Managed Service Account is a special type of service or Windows PowerShell.
Service Accounts
account; AD automatically updates the passwords of these
Service accounts are a special type of account that Windows accounts. A virtual account is the computer-specific local Windows Defender Credential Guard does not allow the use
services use to interact with the operating system and re- equivalent of a Group Managed Service Account. of:

18
SysAdmin Magazine June 2019

•• Unconstrained Kerberos delegation •• Transmits passwords to the client in a secure, encrypted


manner
•• NT LAN Manager version 1 (NTLMv1)

•• Microsoft Challenge Handshake Authentication Protocol


(MS-CHAPv2)
Using the Active Directory
•• Digest
Administrative Center
•• Credential Security Support Provider (CredSSP)
The Active Directory Administrative Center enables you to Windows
Server
•• Kerberos DES encryption search your Active Directory for accounts that are ripe for
takeover by attackers. In particular, you should regularly look

Hardening
for the following types of accounts:

Using the Local Administrator •• User accounts whose passwords never expire — You

Password Solution
should avoid configuring accounts with fixed passwords
because they are less secure than accounts with pass-
words that users have to update periodically.
Checklist
Microsoft’s Local Administrator Password Solution (LAPS)
provides a secure central repository for the passwords all •• Inactive user accounts — Inactive user accounts usual- Free Download
built-in local Administrator accounts and automates proper ly belong to a person who has left the organization. The
management of those passwords. In particular, LAPS: Active Directory Administrative Center console enables
you to find accounts that haven’t signed in for a specified
•• Ensures that local administrator passwords are unique on
number of days.
each computer

•• Automatically changes all local administrator passwords Deleting or disabling these user accounts prevents them from
every 30 days being misused by outside attackers or malicious insiders.

•• Provides configurable permissions to control access to


passwords

19
SysAdmin Magazine June 2019

How to Perform Common Registry Errors ed each time you restart the PC. Changes to the registry
by malware require immediate attention.

Windows Registry
There are several common causes of registry errors. Some are
worth worrying about, and others are not.

Repair and Fix Errors


•• Orphaned entries. Orphaned entries occur when you
uninstall software and small fragments of registry en-
Why Clean the Registry?
tries are left behind. Registry cleaner software will often
claim these are an immediate issue, but in reality, they Once you’ve been running the Windows OS for some time, in-
will just use up a few kilobytes of free space on your disk. stalling and uninstalling programs, and swapping in different
Jeff Melnick
keyboard and mice, you end up with hundreds or thousands
IT Security Expert, Blogger •• Duplicate keys. Duplicate keys are made when you re-
of registry entries that are completely useless. Each one uses
install, upgrade or update software on your machine, in-
very little hard drive space, but the operating system still has to
cluding the operating system. Registry cleaner software
filter through all of them, which slows it down a bit. By clean-
will state that your programs will be confused by the
The Windows registry is a database containing important, ing the registry, you can get rid of those unwanted entries and
duplicate entries, slowing your machines performance,
machine-specific settings and information regarding al- make your system run a little bit faster.
but that is not true.
most everything in your computer — preferences, applica-
tions, users, attached devices and so on. The registry con- •• Fragmented registry. The registry can also fragment Sometimes, however, it is really necessary to fix registry issues.
tains two basic elements: keys and values. The Windows when software is uninstalled, upgraded or updated. For example, if you have ever encountered a piece of malware,
operating system constantly refers to the registry; for ex- you know that it can completely mess up your registry. So, how
•• System shutdown errors. Each time your computer
ample, to open a program, install new software or change to fix broken registry items? When the time comes to fix regis-
shuts down, a copy of the registry is saved to system
your hardware, Windows must check the values of certain try errors, it is important to know what you are doing. The first
memory. If your computer is turned off, crashes or dies
keys. You can change registry key values manually using step is to make a registry backup.
without going through the normal shutdown routine, it
the built-in Windows Registry Editor (regedit) in order to
could cause an issue in the future, but this is unlikely.
improve performance or make Windows work the way you
want, but you need to know what you’re doing or you can •• Malware. Many types of malware attack and modify
seriously damage your OS. the registry. In particular, malware is regularly designed
to change the values of startup keys so it will be activat-

20
SysAdmin Magazine June 2019

Backing up the Windows Registry a stable system so you can troubleshoot and fix Windows is- Alternatively, a slightly quicker method is to browse to the
sues. Using Safe Mode to restore the registry is worthwhile location with the backup, right-click the file and select Merge.
Back up the Windows registry before you attempt to
because it helps protect vital files and drivers from corrup- The file will be automatically imported to your registry.
change, create or remove registry settings, so you can re-
tion. Once you’ve booted into Safe Mode, do the following:
vert to the old version if something goes wrong. Take the
following steps: 1. Press the Windows button and the R button simultane-
ously to open the Run window.
1. Press the Windows button and the R button simultane-
ously to open the Run window. 2. Type “regedit” and press Enter.

2. Type “regedit” and press Enter. 3. Click File > Export.

3. Click File > Export. 4. In the Import Registry dialogue box, browse to the loca-
tion where you saved your backup file and click Open. Restoring the registry from the command prompt
4. In the dialogue box, enter a name for the backup file
(for example “rgbkp2018”), select the location where you In some situations, the Windows system will not boot into
want to save it and click Save. Safe Mode, so you need to restore your registry manually
from the command prompt. To do this you’ll need your orig-
inal Windows OS disk or an ISO image on the bootable flash
drive with your Windows operating system.

Restoring the Windows Registry Tap the F8 button before Windows starts and choose Repair
You also need to know how to restore the registry so you are My Computer. If F8 doesn’t work, boot from your CD and en-
ready if anything goes wrong. There are several methods. ter the repair Windows mode from there. After booting the
Windows OS setup, go to System Recovery and select the
Restoring the Windows registry from Safe Mode command prompt.

This is the most basic method, provided your computer is


We’ll be assuming your Windows directory is located on the C
healthy. First, boot Windows in Safe Mode by pressing the
drive. Enter these commands to change your working direc-
F8 button while turning your device on. When you enter Safe
tory to the directory with your backup:
Mode, Windows loads a minimal environment that ensures

21
SysAdmin Magazine June 2019

Cd /d C:\windows\System32\config Editing the Registry a. Expand the HKEY_CURRENT_USER section and then
expand the Software
To edit the value of a registry key, take these steps:
xcopy *.* C:\RegBack\ b. Look for keys based on the name of the uninstalled
1. First, find the key you want to edit. Press the Ctrl and F applications or the vendor and delete them.
cd RegBack
keys simultaneously open the Find dialog.
4. Next, find and remove any duplicate keys that the unin-
dir 2. Type the name of the key and click Find Next.
stalled applications might have left behind:
3. Double-click the key you want in the list.
a. Press Ctrl+F to open the Find dialog box.
Then replace the current registry settings with the ones from 4. Edit the key’s value data.
b. Enter the name of the uninstalled application and click
the backup using these commands:
5. Click OK to save your settings. Some edits require a Win- OK to search. Each matching key or value will be high-
dows restart to take effect. lighted.

copy /y software ..
6. You can also edit the registry with PowerShell. c. Remove the highlighted key.

copy /y system .. d. Press F3 to find the next match and delete it. Repeat
this step until you have reviewed all highlighted items.
copy /y sam ..

Cleaning the Windows Registry with 5. Remove unwanted start-up items from the registry:

the Registry Editor a. Navigate to the following location: My Computer\


Note that the two periods are part of the command.
HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Win-
You can clean your registry manually using the Windows
dows\Current Version
After this process completes, restart your computer. Registry Editor. Follow these simple steps:
b. Click Run to list shortcuts to all the executable files
1. Click the Start button and then select ...
that run at startup.
2. Type “regedit” in the text box and press Enter.
c. Delete any applications that you don’t want to run at
3. Locate any applications that have already been unin- Windows startup. Do an online search to investigate any
stalled and delete them: that are unfamiliar.

22
SysAdmin Magazine June 2019

•HKLM\SOFTWARE\Wow6432Node\Microsoft\Win- ones. Each restore point will have a timestamp as well 5. On the Advanced Options screen, click Automated Repair.
dows\ CurrentVersion\Run as a brief description of why the restore point was cre-
6. Choose an account and login when prompted to do so.
ated.
•HKLM\SOFTWARE\Microsoft\Active Setup\Installed
7. Automatic repair will start and your computer may re-
Components 4. Click Scan for affected programs to see all of the pro-
boot during this process.
grams and drivers that will be deleted from the com-
•HKLM\SOFTWARE\Wow6432Node\Microsoft\Active
puter and all programs that will likely not work correct-
Setup\Installed Components
ly if you proceed with the restore. A system restore will
not affect any of your personal files.
Fixing Broken Registry Items with
Fixing Windows Registry Errors with
5. Click Next and then Finish to start the restore process.
This may take a few minutes. Your computer will re-
System File Checker
System Restore boot after the restore is complete. Another way to fix a corrupted registry is to run the System
File Checker:
If a recent change to your system caused errors in your reg-
1. Run cmd.exe with administrator rights.
istry, you can revert your computer’s registry settings using
a Windows restore point. If your computer has System Re- Repairing the Registry with 2. In the command window, type “sfc /scannow” and press
store enabled, restore points will be created automatical-
ly when major changes are made to the system, such as
Automatic Repair Enter.

3. Wait until the scan is complete and then reboot if needed.


the installation of new drivers. You can also create restore Newer versions of Microsoft Windows include an automatic
points manually. repair feature. When you run Automatic Repair, it will at-
tempt to fix corrupt registry keys and repair invalid keys.
1. To open the System Restore window, click the Start menu
and enter “restore” in the search box.
Take these steps:
Refreshing the Windows System
1. Open the Settings.
2. Select System Restore from the list of results. Windows 10 allows you to reset your computer and leave all
2. Go to the General. your files untouched. This option completely refreshes your
3. Select a restore point. Windows will select the most re-
system files and may help you fix registry issues. Here are
cent restore point. If the error has been around for a 3. On the Advanced Startup panel, click Restart now.
the steps to follow:
while, click Show more restore points to see previous
4. On the Choose an option screen, click Troubleshoot.

23
SysAdmin Magazine June 2019

1. Go to Settings and click Update and Security. Editing your registry is not likely to improve system speed or
PC performance. However, you should make regular back-
2. Select Recovery.
ups so you can restore if the installation of a program or
3. In the Reset This PC section, click Get Started and then device causes issues. It is also important to track changes to
click Keep My Files. your registry. In particular, malware often changes registry
startup keys so it will start automatically after each reboot.
4. Click Next twice and then click Finish.
You can learn more in this guide about detecting modifica-
tions to startup items in the Windows registry.

Repairing the Registry with the DISM Windows


Command
1. Run cmd.exe with administrator rights.
Registry Tutorial
2. Run the following command:
Free Download

DISM /Online /Cleanup-Image /ScanHealth

3. Wait until the scan process completes.

If these methods didn’t fix your registry problems, then you


probably will have to reinstall Windows from scratch.

24
SysAdmin Magazine June 2019

How to Automate Creating Tasks with Task Scheduler


Open Task Scheduler by pressing “Windows+R” and then typing “taskschd.msc” in the window that opens. Then take the following steps:

PowerShell Scripts 1. Click “Create a task” and enter a name and description for the new task. To run the program with administrator privileges, check
the “Run with the highest privileges” box. In our example, we’ll assign a service account to run the task, and run it regardless of
whether the user is logged on.

Adam Stetson
Systems Engineer, Security Expert

Microsoft Windows Task Scheduler can help you automati-


cally launch a program or PowerShell script at a certain time
or when certain conditions are met. You can also schedule
sending emails and even displaying certain messages. In
this blog, we will show you how to run a PowerShell script
from Task Scheduler that will alert on any software instal-
lation on a local computer. We will also create scheduled
tasks using PowerShell scripts. You will learn how to:

•• Create Tasks with Task Scheduler

•• Modify or Delete Scheduled Tasks

•• Create Scheduled Tasks with PowerShell Scripts.

25
SysAdmin Magazine June 2019

2. Switch to the Triggers tab and click the “New…” button. Here you can specify the conditions that trigger the task to be executed. For 3. Navigate to the “Actions” tab, and click “New…”. Here you can
example, you can have it executed on schedule, at logon, on idle, at startup or whenever a particular event occurs. We want our task specify the actions that will be executed whenever the trigger
to be triggered by any new software installation, so we choose “On an event” from the drop-down menu and select “Application” from conditions are met. For instance, you can send an email or dis-
the Log settings. Leave the “Source” parameter blank and set the EventID to “11707”. Click “OK” to save the changes. play a message. In our case, we want to start a program, so we
need to create the PowerShell script we want to run and save it
with the “ps1” extension. You can find the script here; it will send
an alert with the event details about the installed software.

To schedule the PowerShell script, specify the following


parameters:

•• Action: Start a program

•• Program\script: powershell

•• Add arguments (optional): -File [Specify the file path to


the script here]

Click “OK” to save your changes.

26
SysAdmin Magazine June 2019

4. The “Conditions” tab enables you to specify the conditions that, along with the trigger, determine whether the task should be 5. You can also set up additional parameters for your sched-
run. In our case, we should leave the default settings on this tab. uled task on the “Settings” tab. For our example, though,
we’ll leave them unchanged.

6. When the task is completely set up, the system will ask
you for the service account password. Note that this ac-
count must have the “Log on as Batch Job” right. Enter the
password and click “OK” to save the task.

7. For Task Scheduler to function properly, the Job Schedul-


er service must be set to start Run “Services.msc”. In the list
of services, find Task Scheduler and double-click it. On the
General tab, set the startup type to “Automatic” and click
OK to save your change.

27
SysAdmin Magazine June 2019

Now whenever new software is installed on your Microsoft In Windows Powershell 2.0 (Windows 7, Windows Serv- Windows PowerShell 4.0 (Windows Server 2012 R2 and above)
Windows Server, you will be notified via an email that de- er 2008 R2), to create a scheduled job, you must use the doesn’t include the Task Scheduler module, so this script will
tails the time of the installation, the name of the software TaskScheduler module. Install the module by running the not work. Instead, PowerShell 3.0 and 4.0 introduced new
and the user ID (SID) of the person who installed it. “Import-Module TaskScheduler” command and use the cmdlets for creating scheduled tasks, New-ScheduledTask-
following script to create a task that will execute the Pow- Trigger and Register-ScheduledTask, which make creating
erShell script named GroupMembershipChanges.ps1 daily a scheduled task much easier and more convenient. So let’s
at 10 AM: create a task that will execute our script daily at 10 AM using
Modifying or Deleting Scheduled the system account (SYSTEM). This task will be performed

Tasks Import-Module TaskScheduler $task = New-Task


by an account with elevated privileges.

$task.Settings.Hidden = $true
To modify an existing task, right-click it in the list, select Import-Module TaskScheduler $task = New-Task
Add-TaskAction -Task $task -Path C:\Windows\
Properties, edit the required settings and click OK. To de- $task.Settings.Hidden = $true
system32\WindowsPowerShell\v1.0\powershell.
lete a scheduled task, right-click it, select Delete and con- exe –Arguments “-File C:\Scripts\GroupMem- Add-TaskAction -Task $task -Path C:\Windows\
firm the action. bershipChanges.ps1” system32\WindowsPowerShell\v1.0\powershell.exe

Add-TaskTrigger -Task $task -Daily -At –Arguments “-File C:\Scripts\GroupMembership-

“10:00” Changes.ps1”

Register-ScheduledJob –Name ”Monitor Group Add-TaskTrigger -Task $task -Daily -At “10:00”

Creating Scheduled Tasks with Management” -Task $task Register-ScheduledJob –Name ”Monitor Group Ma-
nagement” -Task $task
PowerShell Scripts
Now that you know how to create a task using Task Sched-
uler, let’s find out how to create a scheduled task using
PowerShell. Suppose we want our task to be launched dai-
ly at 10 AM, and it must execute the PowerShell script you
can find here, which will monitor changes to group mem-
bership in the Active Directory site.

28
SysAdmin Magazine June 2019

Other trigger options that could be useful in creating new


tasks include:

•• -AtStartup — Triggers your task at Windows startup.

•• -AtLogon — Triggers your task when the user signs in.

•• -Once — Triggers your task once. You can set a repetition


interval using the –RepetitionInterval parameter.

•• -Weekly — Triggers your task once a week.

Note that, using these cmdlets, it is not possible to trigger


execution “on an event” as we did with the Task Schedul-
er tool. PowerShell scripts with “on an event” triggers are
much more complicated, so this is a real disadvantage of
using PowerShell rather than Task Scheduler.

As you can see, it is easy to create scheduled tasks using


Task Scheduler or PowerShell. But remember that improp-
er changes to your scheduled tasks can cause service inter-
ruptions and degrade server performance. Therefore, it’s
essential to track all changes to your scheduled tasks.

29
SysAdmin Magazine June 2019

Want to spend less time handling account lockout issues in Active Directory? Try this freeware account lockout tool that
alerts you to account lockouts in real time and helps you quickly troubleshoot and resolve them.

Free Tool of the Month

Account Lockout
Examiner
Download Free Tool

30
[On-Demand Webinar]

Active Directory Whether you are an Active Directory novice or an experienced IT pro, this session is for you! Learn how to effectively
install and administer Active Directory, and explore potential pitfalls of AD configuration and ways to ensure your con-

101: Install and figuration enhances the security of your IT environment.

Configure AD Watch this on-demand webinar to learn:

Domain Services
• How to install and configure domain controllers
• Best practices for creating AD users and computers
• How to effectively approach AD group and organizational unit management

Sander Berkouwer
Enterprise Mobility MVP
Watch Now

Corporate Headquarters: Phone: 1-949-407-5125 Copyright © Netwrix Corporation. All rights reserved. Netwrix is trademark of Netwrix Corporation and/or
300 Spectrum Center Drive, Toll-free: 888-638-9749 one or more of its subsidiaries and may be registered in the U.S. Patent and Trademark Office and in other
Suite 200 Irvine, CA 92618 EMEA: +44 (0) 203-318-02 countries. All other trademarks and registered trademarks are the property of their respective owners.

Das könnte Ihnen auch gefallen