100% found this document useful (1 vote)
172 views23 pages

Sysadmin Magazine March 2020

The document discusses using PowerShell commands to manage Group Policy objects (GPOs). It provides examples for creating and linking GPOs, getting information about GPOs, configuring registry-based settings in GPOs, applying GPOs, and reviewing which GPOs are applied to users and computers. The commands shown allow automating common Group Policy management tasks from PowerShell.

Uploaded by

fletox786
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
100% found this document useful (1 vote)
172 views23 pages

Sysadmin Magazine March 2020

The document discusses using PowerShell commands to manage Group Policy objects (GPOs). It provides examples for creating and linking GPOs, getting information about GPOs, configuring registry-based settings in GPOs, applying GPOs, and reviewing which GPOs are applied to users and computers. The commands shown allow automating common Group Policy management tasks from PowerShell.

Uploaded by

fletox786
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 23

SysAdmin MAGAZINE

Power Move: Master


More PowerShell
Commands
Contents SysAdmin Magazine March 2020

SysAdmin Contents
Magazine

03 SysAdmin Magazine: Now on Facebook

№ 57 March ‘20
04 Top 10 PowerShell commands for Group Policy

08 Most useful PowerShell commands for SharePoint


SysAdmin Magazine is a free
source of knowledge for IT Pros 12 10 most useful PowerShell commands for Office 365
who are eager to keep a tight
grip on network security and do
the job faster. 16 PowerShell commands for effective password management

20 How to get local administrators

21 Tool of the month: Inactive User Tracker

The Sysadmin Magazine team


[email protected]

2
Contents SysAdmin Magazine March 2020

New Sysadmin Magazine Page


on Facebook

Now on
Facebook

SysAdmin Magazine

Get the best articles from the magazine, along with the freshest
IT news and top tips from the IT community.

Follow the page to streamline your workload and stay on top of


what’s going on in IT.

Follow Us

3
Contents SysAdmin Magazine March 2020

Top 10 Group Creating a new Group Policy Object


Let’s start by creating a new Group Policy object (GPO). The
You can optionally link the GPO to a domain, domain con-
troller’s organizational unit (OU) or site using piping. The

Policy PowerShell
command below creates a new GPO and links it to the Cli-
command below creates a new GPO called ‘Netwrix PCs’
ents OU in the ad.contoso.com domain:
and adds a comment to describe the its purpose:

Commands New-GPO -Name "Netwrix PCs" -Comment "Clie-


nt settings for Netwrix PCs"
New-GPO -Name "Netwrix PCs" | New-GPLink
-Target "ou=clients,dc=ad,dc=contoso,dc=com"

Russell Smith
Windows Security Expert, IT Consultant, Writer, and MCSE The command creates an empty GPO with no settings. If
To unlink a GPO, use the Remove-GPLink cmdlet:
you have starter GPOs configured in your Active Directory
domain, you can create a new GPO based on their settings.
The following command creates a new GPO called ‘Netwrix Remove-GPLink -Name "Netwrix PCs" -Target

In addition to the Group Policy Management Console PCs’ based on the ‘Windows 10 MS Security Settings’ GPO: "ou=clients,dc=ad,dc=contoso,dc=com"

(GPMC), Microsoft provides a set of Windows PowerShell


cmdlets you can use to manage Group Policy. To use the
New-GPO -Name "Netwrix PCs" -StarterGPOName
Group Policy PowerShell cmdlets, you must have GPMC in-
"Windows 10 MS Security Settings"
stalled on the device where you will run the cmdlets. To
check if the Group Policy PowerShell module is installed
on a device, run the command below, which will display all
the available Group Policy cmdlets available if the module
is installed.

Get-Command -Module GroupPolicy

4
Contents SysAdmin Magazine March 2020

Figure 1. How to link and unlink a GPO

Getting information about a GPO


Once a GPO is created, you can use Get-GPO to return informa-
tion like GPO status, creation time and last modification time:

Get-GPO -Name "Netwrix PCs"

If you want more information, pipe the object created by Get-


GPO to Get-GPOReport. The script below creates an HTML re-
port that gives information about the GPO similar to what you
might see in the Group Policy Management Console:

Figure 2. HTML report with detailed data about a specific GPO


Get-GPO -Name "Netwrix PCs" | Get-GPOReport
-ReportType HTML -Path c:\temp\report.html

5
Contents SysAdmin Magazine March 2020

Configuring Group Policy settings To get detailed information about a registry key configured in a GPO, use Get-GPRegistryValue:

If you know the location for a registry-based Group Poli-


Get-GPRegistryValue -Name "Netwrix PCs" -Key "HKCU\Software\Policies\Microsoft\Windows\Control Panel\Desktop"
cy setting, you can use the Set-GPRegistryValue cmdlet to
configure it. Registry-based Group Policy settings are those
that appear under Administrative Templates in GPMC.
Set-GPRegistryValue can also be used to set registry values
that are not covered by Group Policy settings. For exam-
ple, if you want to configure registry settings for third-party
applications that don’t have an ADMX file for Group Policy,
Set-GPRegistryValue is a quick way to configure the set-
tings you need. The following command sets a screensaver
timeout of 300 seconds for the logged-in user:

Set-GPRegistryValue -Name "Netwrix PCs" -Key


Figure 3. How to get detailed information about a registry key configured in a GPO
"HKCU\Software\Policies\Microsoft\Windows\Con-
trol Panel\Desktop" -ValueName ScreenSaveTime-
Out -Type DWord -Value 300 To remove a registry setting from a GPO, use Remove-GPRegistryValue:

Remove-GPRegistryValue -Name "Netwrix PCs" -Key "HKCU\Software\Policies\Microsoft\Windows\Control Panel\


You can specify either computer configuration or user con-
Desktop" -ValueName ScreenSaveTimeOut
figuration settings using Set- GPRegistryValue The regis-
try path in the -Key parameter below starts with “HKCU"
(which stands for “HKEY_CURRENT_USER”). If you want to The three cmdlets above have Group Policy Preference equivalents if you decide to use Preferences instead of Policies to set
configure a computer setting instead, replace “HKCU” with registry keys: Set-GPPrefRegistryValue, Get-GPPrefRegistryValue, and Remove-GPPrefRegistryValue.
“HKLM” (which expands to HKEY_LOCAL_MACHINE).

6
Contents SysAdmin Magazine March 2020

Applying Group Policy settings Get-GPResultantSetOfPolicy -Computer dc1 -ReportType HTML -Path c:\temp\dc1rsop.html
Provided that your GPO is linked to a domain, OU or site, it
will apply to user and computer objects below where it is
linked. But if you want to force a Group Policy update on a
remote server or other device, you can use Invoke-GPUp-
date. Running Invoke-GPUpdate without any parameters
will force an update of user and computer configuration
settings on the local computer. The command below forc-
es a Group Policy update on server1 for user configuration
settings only:

Invoke-GPUpdate -Computer "ad\server1" -Target


"User"

Reviewing which GPOs are applied to


a user or computer
To get information about which GPOs are applied to a user
or computer, you can generate a Resultant Set of Policy
(RSoP) report using the Get-GPResultantSetOfPolicy cm-
dlet. The command below generates a report for the com-
puter called “dc1” and writes the results to the c:\temp di-
rectory:

Figure 4. How to get information about which GPOs are applied to a user or computer

7
Contents SysAdmin Magazine March 2020

Most useful Share- A better option is to use the PowerShell ISE. Not only does
it include many cmdlets created especially for managing
Getting SharePoint site information
Get-SPSite cmdlet is the main cmdlet for getting infor-

Point PowerShell
SharePoint, it also offers color-highlighted code, a debug
mation about your SharePoint site collections. It lists the
engine and a cmdlet search engine.
URLs of your SharePoint sites and their compatibility levels

Commands
(SharePoint versions).
To load the SharePoint snap-in, we need to run the follow-
ing command:

Jeff Melnick Add-PSSnapin Microsoft.SharePoint.PowerS-


IT Security Expert, Blogger
hell

After that, it is prudent to update PowerShell help in order Using the Select-Object parameter with this cmdlet, we can
get the latest information about the Microsoft SharePoint get specific properties about a site, such as the site owner,
SharePoint Server is a web-based collaborative platform
PowerShell cmdlets: storage usage, maximum quota level and last content mod-
that integrates with Microsoft Office. To configure Share-
ified date:MAC address filtering.
Point site settings, system administrators often use the
SharePoint Management Shell that is installed with the Update-Help
SharePoint product. Running the SharePoint Management
Shell calls the Windows PowerShell runtime environment Get-SPSite "http://sharepoint/sites/ent"
So, what cmdlets are available in the SharePoint snap-in?
and executes a script file named sharepoint.ps1, which | Select-Object url, owner, @{Expressi-
Here is the command that will list all of them for you:
loads the Windows PowerShell snap-in for SharePoint and on={$_.Usage.Storage}}, @{Expression={$_.
Audit.AuditFlags}}, readonly, LastCon-
runs a few commands. These commands are not very im-
tentModifiedDate, @{Express={$_.QuotaSto-
portant; they include choosing C:\Users\Username as the
Get-Command -Module "Microsoft.Share- rageMaximumLevel}}
home location for command execution and running the
Point.PowerShell"
latest version of PowerShell console.

8
Contents SysAdmin Magazine March 2020

$SPRoles = $WebPath.RoleAssign-
ments;
foreach ($SPRole in $SPRoles)
{
foreach ($SPRoleDefinition in
In addition, we can export information about all sites in our $SPRole.RoleDefinitionBindings)

SharePoint farm to a csv file: {


If you need a complete permissions report for a SharePoint
$WebPath.Title + "," + $We-
site, run the following code, specifying the SharePoint site bPath.Url + "," + "N/A" + "," + $SPRole.
URL ($SPSiteURL) and the path to export the data to a csv Member.Name + "," + $SPRoleDefinition.Name +
Get-SPWebApplication http://sharepoint/ |
file ($ExportFile) : "," + $WebPath.HasUniqueRoleAssignments |
Get-SPSite -Limit All | Get-SPWeb -Limit
out-file $ExportFile -append
All | Select Title, URL, ID, ParentWebID
}
| Export-CSV C:\root\sharepointinventory.
csv -NoTypeInformation [void][System.Reflection.Assembly]::Load- }

WithPartialName("Microsoft.SharePoint") }

$SPSiteUrl = "http://sharepoint/sites/
ent" foreach ($List in $WebPath.Lists)
We can also use the Get-SPSite cmdlet to create a SharePoint
$SPSite = New-Object Microsoft.Share- {
PowerShell script that lists all the groups and their members
Point.SPSite($SPSiteUrl); if ($List.HasUniqueRoleAssign-
for a particular SharePoint site: ments)
$ExportFile = "C:\root\Permissions.csv"
{

"Web Title,Web URL,List Title,User or $SPRoles = $List.RoleAssign-


$site = Get-SPSite http://sharepoint/si- Group,Role,Inherited" | out-file $Export- ments;
tes/ent/ File foreach ($SPRole in $SPRoles)
$groups = $site.RootWeb.sitegroups {
foreach ($grp in $groups) {"Group: " + foreach ($WebPath in $SPSite.AllWebs) foreach ($SPRoleDefinition in
$grp.name; foreach ($user in $grp.users) { $SPRole.RoleDefinitionBindings)
{" User: " + $user.name} } if ($WebPath.HasUniqueRoleAssignments) {
$site.Dispose() { $WebPath.Title + "," +

9
Contents SysAdmin Magazine March 2020

Now let’s make a report that will output all files created
$WebPath.Url + "," + $List.Title + "," + by a certain user. This script can be helpful, for example, Select Name,
$SPRole.Member.Name + "," + $SPRoleDefiniti- when an employee leaves the company and you need to @{Name="URL";
on.Name | out-file $ExportFile -append
transfer their data to other people. Expression={$_.ParentList.Par-
} entWeb.Url + "/" + $_.Url}}
}
}
Get-SPWeb http://sharepoint/sites/ent |
}
Select -ExpandProperty Lists |
}
Where { $_.GetType().Name -eq "SPDocu-
$SPSite.Dispose();
mentLibrary" -and
Using PowerShell to manage
-not $_.Hidden } |
Select -ExpandProperty Items | SharePoint sites and objects
To find a certain file on a SharePoint site, we need to use
Where { $_["Created By"] -like
the Get-SPWeb cmdlet. Here is a script that searches for a New SharePoint sites are typically created using a template.
"*system*" } |
file whose name contains the word “readme” in the “http:// Select Name, url, {$_["Created By"]} To get a list of all site templates, run the Get-SPWebTem-
sharepoint/sites/ent” site: plate cmdlet with no parameters.

We use the Get-SPWebTemplate cmdlet with the New-


Our last script using the Get-SPWeb cmdlet reports on all
Get-SPWeb http://sharepoint/sites/ent | SPSite cmdlet to create a new SharePoint site based on a
files with a specified extension:
Select -ExpandProperty Lists | template. Here is an example of a script for creating a site
Where { $_.GetType().Name -eq "SPDocu- using the “Team Site” template (STS#0):
mentLibrary" -and
-not $_.Hidden } | Get-SPWeb http://sharepoint/sites/ent |
Select -ExpandProperty Items | Select -ExpandProperty Lists |
$template = Get-SPWebTemplate "STS#0"
Where { $_.Name -like "*readme*" } | Where { $_.GetType().Name -eq "SPDocu-
New-SPSite -Url "http://sharepoint/sites/
Select Name, {$_.File.Length}, url mentLibrary" -and
netwrixteamsite" -OwnerAlias "enterprise\t.
-not $_.Hidden } |
simpson" -Template $template
Select -ExpandProperty Items |
Where { $_.Name -Like "*.rtf" } |

10
Contents SysAdmin Magazine March 2020

To delete a site, we use the Remove-SPSite cmdlet:


Set-SPUser -Identity "i:0#.w|enterprise\t.
simpson" -Web http://sharepoint/sites/ent
Remove-SPSite -Identity "http://sharepoint/ -AddPermissionLevel "Contributor"
sites/netwrixteamsite" -GradualDelete
FREE TOOL

To add permissions to a certain AD security group, use the


Sometimes, you might need to change the site collection same script but type the name of the group instead of the
administrator. Execute the following script to add admin
rights to the specified user:
name of the user account.
STAY ON TOP
To add a user to a group, use this command:

of changes and data


access events in your
Set-SPSite -Identity "http://sharepoint/si-
tes/netwrixteamsite" -SecondaryOwnerAlias " Set-SPUser -Identity "i:0#.w|enterprise\j.

SharePoint environment
i:0#.w|enterprise\i.scur" carter" -Web http://sharepoint/sites/ent
-Group "Enterprise Owners"

Now, let’s see how to manage permissions to our site col-


Free Download
lections. First, let’s add certain access rights to a particular
Active Directory user account. In this case, the user “enter-
prise\t.simpson” will be given “Contributor” rights to the As you can see, managing and reporting on SharePoint
site “http://sharepoint/sites/ent”. Note that before a regular sites using SharePoint PowerShell scripts is not as hard as
user account name like “enterprise\t.simpson”, you need to it may seem at first. In fact, in some cases, it is much faster
use the prefix “i:0#.w|”. Otherwise, the execution will fail to run a script rather than generate a report from the ad-
and the script will generate an error. min audit log.

11
Contents SysAdmin Magazine March 2020

Most Useful Office 1. Connecting to an Office 365


instance with PowerShell
$O365 = New-PSSession -ConfigurationName

365 PowerShell
Microsoft.Exchange -ConnectionUri https://
outlook.office365.com/powershell-liveid/
First, we need to install the Office 365 module for Windows -Credential $Cred -Authentication Basic

Commands
PowerShell and connect to the Office 365 instance. Take -AllowRedirection
the following steps:

Download and install the Microsoft Online Services Connect to all Office 365 services:
Sign-In Assistant for IT Professionals RTW.
Adam Stetson
Systems Engineer, Security Expert
Import the Online Services PowerShell module for Mic- Connect-MsolService –Credential $O365

rosoft Azure Active Directory and Office 365:

Once we have imported the modules for Windows PowerShell,


Using Windows PowerShell to manage Office 365 may
we are ready to manage our Office 365 instance.
seem odd at first. After all, cloud solutions promise simplic- Install-Module -Name AzureAD
Install-Module -Name MSOnline
ity and ease of use — adjectives rarely used in connection
with Windows PowerShell. But bear with me. In this arti-
cle, I’ll show you the ten most useful Office 365 PowerShell
Enter your Office 365 admin credentials:
2. Connecting to Exchange Online
cmdlets for system administrators. Perhaps after reading
these instructions, you’ll agree that PowerShell can be a
and SharePoint Online with
valuable tool, even for cloud-based systems. $Cred = Get-Credential
PowerShell
We can also connect to Microsoft Exchange Online and
Microsoft SharePoint Online separately. Connecting to
Create a remote PowerShell session: Exchange Online with PowerShell is basically the same as
connecting to Office 365:

12
Contents SysAdmin Magazine March 2020

$Cred = Get-Credential Get-Command -module MSOnline Get-MsolUser | Select DisplayName, City,


$Session = New-PSSession -ConfigurationName Department, ObjectID
Microsoft.Exchange -ConnectionUri https://
outlook.office365.com/powershell-liveid/
-Credential $Cred -Authentication Basic – To see the number of account licenses, you need to run
AllowRedirection the following cmdlet:

Connecting to SharePoint Online is a little bit different In or-


Get-MsolAccountSku
der to manage your SharePoint Online tenant, you first need
to download and install the SharePoint Online Management
Shell feature. Then run the following PowerShell script: To list the available services, run the following script:
We can also get the list of cmdlets for Azure Active Directory:

$admin=”[email protected]” Get-MsolAccountSku | select -ExpandProperty


$orgname=”enterprise” ServiceStatus
Get-Command -module AzureAD
$userCred = Get-Credential -UserName $admin
-Message “Type the password.”
Connect-SPOService -Url https://$orgname-
admin.sharepoint.com -Credential $userCred

4. Getting a list of all Office 365


users with PowerShell
3. Getting a list of available Office If you need to provide a list of Office 365 users and licenses,

365 PowerShell cmdlets use the Get-MsolUser cmdlet. It’ll retrieve all users with a
valid license in the Office 365 tenant, along with the Display-
To get a list of all available Office 365 PowerShell com- Name, City, Department and ObjectID parameters.
mands, we need to run the Get-Command cmdlet:

13
Contents SysAdmin Magazine March 2020

5. Creating a new user in Office 365 7. Changing a password in Office 365 Add-MsolGroupMember -GroupObjectId

with PowerShell with PowerShell 5b61d9e1-a13f-4a2d-b5ba-773cebc08eec


-GroupMemberObjectId a56cae92-a8b9-4fd0-
To create a new user, we use the New-MsolUser command: If you need to change the password for an account, use the acfc-6773a5c1c767 -GroupMembertype user
Set-MsolUserPassword cmdlet. You can either specify a new
password as in the example below, or omit the -NewPass-
New-MsolUser -UserPrincipalName JSmith@ word parameter to have the system automatically generate GroupObjectId is the hexadecimal ID of the group, which
enterprise.onmicrosoft.com -DisplayName “John
a random password. you can get from the Get-MsolGroup command. Group-
Smith” -FirstName “John” -LastName “Smith”
MemberObejctId is the user object ID, which you can find
by running this command:

The system will output the user’s password and license sta- Set-MsolUserPassword -UserPrincipalName
[email protected]
tus data.
-NewPassword P@SSw0rd! Get-MsolUser | Select ObjectID.

6. Removing a user from


all sites with PowerShell 8. Managing group membership in 9. Creating a SharePoint site
Office 365 with PowerShell collection with PowerShell
To remove a user from all sites at once, we use the follow-
ing command: We can also manage Office 365 groups using PowerShell We can also create a SharePoint site collection using Power-
cmdlets. To retrieve a list of all groups in Office 365, sim- Shell:
ply use the command Get-MsolGroup. To add users to a
Get-SPOSite | ForEach {Remove-SPOUser -Site group, use the Add-MsolGroupMember command:
$_.Url -LoginName “ JSmith@enterprise. New-SPOSite -Url “https://enterprise.
onmicrosoft.com”} sharepoint.com/sites/NewSite” -Owner
[email protected]
-StorageQuota “100” -Title “New Site”

14
Contents SysAdmin Magazine March 2020

10. Creating reports in Office 365


with PowerShell
PowerShell is a great tool for making different reports.
Here are some useful Office 365 reports done via Power-
Shell:
EBOOK
Details about all mailboxes:

Get-mailbox | get-MailboxStatistics Office 365 Securing Your


Administrator’s Network Devices
Guide
A list of all mailboxes that haven’t been logged into
during the last 30 days:
in the Era of Cyber
Get-Mailbox –RecipientType ‘UserMailbox’
Threats
| Get-MailboxStatistics | Sort-Object Free Download
LastLogonTime | Where {$_.LastLogonTime –lt
([System.DateTime]::Now).AddDays(-30) } |
Format-Table DisplayName, LastLogonTime

A report on the highest volume senders and recipients:

Get-MailTrafficTopReport

15
Contents SysAdmin Magazine March 2020

PowerShell Windows 10 Version 1809

If you are using Windows 10 version 1809, RSAT is included


Enable-WindowsOptionalFeature -Online -Fea-
tureName RSATClient-Roles-AD-Powershell

Commands for as a Feature On Demand, so you don’t need to download


the RSAT package. To enable RSAT in Windows 10 version

Effective Password
1809, run the following command in an elevated Power-
Shell console: Create credential with password
using PowerShell
Management Add-WindowsCapability -Online -Name Rsat.
ActiveDirectory.DS-LDS.Tools~~~~0.0.1.0 To create a new user account, use the New-ADUser cm-
dlet. In the example below, I have hardcoded the ad.con-
toso.com domain in the $UPN variable. You should change
Russell Smith Earlier Versions of Windows 10 this to match the UPN suffix you want to assign to users.
Windows Security Expert, IT Consultant, Writer, and MCSE
If you are using an earlier version of Windows 10, download
Provide the user’s first name and last name. The UPN and
the appropriate RSAT package from Microsoft’s website:
SamAccountName will then be created by adding a period
Automation is the key to streamlining Active Directory man- between the first and last name. Use the following Power-
If you are managing Windows Server version 1803 or
agement tasks. In this article, I’ll show you how to create, Shell script:
1709, download and install the WS_1803 package.
change and test user passwords with PowerShell scripts.
$GivenName = (Read-Host -Prompt "First
If you are managing Windows Server 2016 or earlier
Name")
versions of Windows Server, download and install the
Installing the AD PowerShell module
$Surname = (Read-Host -Prompt "Last Name")
$User = $GivenName+"."+$Surname
Once RSAT is installed, start the PowerShell console as a $UPN = $User+"@ad.contoso.com"
Before you can use PowerShell to manage Active Direc-
local administrator and enable the AD PowerShell module $Password = (Read-Host -Prompt "Password"
tory, you need to install the Active Directory PowerShell
using this PowerShell command: -AsSecureString)
module. If you are using Windows 10 to manage AD, first New-ADUser -Name $User -SamAccountName
install the Remote Server Administration Tools (RSAT). $User -UserPrincipalName $UPN -AccountPass-

16
Contents SysAdmin Magazine March 2020

word $Password -GivenName $GivenName -Surname


Change password using PowerShell Force a user to change their password at next logon

The Set-LocalUser cmdlet doesn’t support setting a local


$Surname -Enabled $True
Change a local user’s password user account to force a password change at next logon.
However, you can achieve the same goal by forcing the
To change a local user’s password, you need to use the
password to expire:
Get-LocalUser and Set-LocalUser cmdlets:

Create new AD user password using $User = (Read-Host -Prompt "Username")


PowerShell $Password = (Read-Host -Prompt "New Pass-
word" -AsSecureString)
$Usrstring = "WinNT://localhost/"+$User
$usr=[ADSI] $Usrstring
The following code will prompt you to specify a username $User = (Read-Host -Prompt "Username")
$usr.passwordExpired = 1
$UserAccount = Get-LocalUser -Name $User
and password. You must enter a username that already $usr.setinfo()
$UserAccount | Set-LocalUser -Password
exists in AD and a password that meets the domain’s pass-
$Password
word complexity requirements.
But you can force users to change their AD account pass-
words using Set-ADAccountPassword:
$User = (Read-Host -Prompt "Username") Change an AD user’s password
$NewPassword = (Read-Host -Prompt "New
To create a new AD user password using PowerShell, use
Password" -AsSecureString) $User = (Read-Host -Prompt "Username")
Set-ADAccountPassword -Identity $User -New- the following script. You will be prompted to specify the
Set-Aduser -Identity $User -ChangePassword-
Password $NewPassword -Reset username of an existing AD account and then a new pass-
AtLogon $true
word, which must meet the domain’s password complexi-
ty requirements.

Change an administrator password


$User = (Read-Host -Prompt "Username")
To change the AD administrator password, type adminis-
$NewPassword = (Read-Host -Prompt "New Pass-
word" -AsSecureString)
trator when you are prompted for a username using the

Set-ADAccountPassword -Identity $User -New- code below:


Password $NewPassword -Reset

17
Contents SysAdmin Magazine March 2020

To set the “password never expires” attribute on an Active


$User = (Read-Host -Prompt "Username") Directory user account, use Set-ADUser: $Username = (Read-Host -Prompt "Username")
$NewPassword = (Read-Host -Prompt "New $User = Get-ADUser $Username -Properties
Password" -AsSecureString) $User = (Read-Host -Prompt "Username") pwdlastset
Set-ADAccountPassword -Identity $User -New- Set-ADUser -Identity $User -PasswordNever- $User.pwdlastset = 0
Password $NewPassword -Reset Expires $true Set-ADUser -Instance $User
$User.pwdlastset = -1
Set-ADUser -Instance $User
To change a local administrator password, type adminis- Change the service account password
trator when prompted for a username:
To change the logon properties of a service, use the Get-Cre-
Bulk password reset
dential and Set-Service cmdlets. The following code chang-
es the AppReadiness service from using the Local System The best way to get users to change their AD passwords
$Password = (Read-Host -Prompt "New Pass-
account to using the username and password that are en- is to force a password reset. You can do this in bulk by
word" -AsSecureString)
$User = (Read-Host -Prompt "Username") tered when prompted. Note that the Set-Service -Creden- combining the Get-ADUser and Set-ADUser cmdlets. The
$UserAccount = Get-LocalUser -Name $User tial parameter is supported only in PowerShell 6 and later. command below uses a filter to get users in the “Accounts”
$UserAccount | Set-LocalUser -Password organizational unit (OU) and pipes the results to the
$Password Set-ADUser cmdlet to force all users in the OU to change
$credential = Get-Credential
their password at next logon.
Set-Service -Name "AppReadiness" -Credenti-
al $credential
Change the “password never expires” attribute
Get-ADUser -Filter * -SearchScope Subtree
To set the “password never expires” attribute on a local -SearchBase "OU=Accounts,DC=ad,DC=conto-
Change a password’s expiration date in Active Directory
user account, use Set-LocalUser: so,DC=com" |

If you need to extend the time a user can keep their cur- Set-ADUser -ChangePasswordAtLogon $true

rent password, set the pwsLastSet attribute to the current


$User = (Read-Host -Prompt "Username")
date, giving them extra time until Active Directory forces
Set-LocalUser -Name $User -PasswordNeverEx-
them to change their password. Clearing the attribute and
pires $true
then setting it to -1 will set it to the current date and time.

18
Contents SysAdmin Magazine March 2020

Testing a user’s credentials


If you want to test if a user’s credentials are working, all
you need to do is start a process using their username and
password. The code below starts cmd.exe using the cre-
GUIDE
dentials entered when prompted.

FREE TOOL
Start-Process -FilePath cmd.exe /c -Credential (Get-Cre-

Ease the burden


dential)

of password
management
Free Download

19
Contents SysAdmin Magazine March 2020

How-to for IT Pro 2. Open the file produced by the script in MS Excel.
Sample report:

HOW TO GET LOCAL ADMINISTRATORS

1. Open the Powershell ISE → Create new script with the


following code and run it, specifying the computer list
and the path for export:

invoke-command {
$members = net localgroup
administrators |
where {$_ -AND $_ -notmatch
"command completed successfully"} |
select -skip 4
New-Object PSObject -Property @{
Computername = $env:COMPUTERNAME
Group = "Administrators"
Members=$members
}
} -computer fs1,sp01,ncnad
-HideComputerName |
Select * -ExcludeProperty RunspaceID
| Export-CSV c:\data\local_admins.csv
-NoTypeInformation

20
Contents SysAdmin Magazine March 2020

Freeware tool that tracks down inactive user accounts, so you can harden your Active Directory security and mitigate the risk of
breaches.

FREE TOOL OF THE MONTH

Inactive User
Tracker
Download Free Tool

21
Contents SysAdmin Magazine March 2020

[On-Demand Webinar]

Managing SharePoint Managing SharePoint Online and Exchange Online can be a painful task — you have to con-
stantly switch between multiple administration centers and it’s hard to know where to go for a

Online and Exchange


specific setting. Luckily, you can accomplish many tasks with PowerShell.

In this webinar, Liam Cleary and Jeff Melnick will walk you through how to use PowerShell to:

Online with PowerShell • Connect to Office 365


• Perform basic management tasks like user and mailbox administration
• Modify permissions and retrieve log data when auditing permissions
Leam Cleary Jeff Melnick
Security expert, Microsoft MVP IT Security Expert, Blogger

Watch Now

22
About Netwrix
What did you think Netwrix is a software company that enables information security and governance professionals to reclaim control over
of this issue? sensitive, regulated and business-critical data, regardless of where it resides.
What did you think of this content?
Over 10,000 organizations worldwide rely on Netwrix solutions to secure sensitive data, realize the full business value of
enterprise content, pass compliance audits with less effort and expense, and increase the productivity of IT teams and
knowledge workers.

For more information visit www.netwrix.com

CORPORATE HEADQUARTER: PHONES: OTHER LOCATIONS:

300 Spectrum Center Drive 1-949-407-5125 Spain: +34 911 982608 Switzerland: +41 43 508 3472 Hong Kong: +852 5808 1306
Suite 200 Irvine, CA 92618 Toll-free (USA): 888-638-9749 Italy: +39 02 947 53539
Netherlands: +31 858 887 804 France: +33 9 75 18 11 19

Sweden: +46 8 525 03487 Germany: +49 711 899 89 187


565 Metro Place S, Suite 400 1-201-490-8840
Dublin, OH 43017

5 New Street Square +44 (0) 203 588 3023 SOCIAL: netwrix.com/social
London EC4A 3TW

You might also like