Quantcast
Channel: Powershell – TheITBros
Viewing all 91 articles
Browse latest View live

How to Renew SSL Certificate on Exchange Server?

$
0
0
Renew SSL Certificate on Exchange Server

When you install Microsoft Exchange 2016/2013, an SSL certificate is automatically generated to protect connections between clients and the server. Usually, the first SSL certificate is issued exactly for one year. When this certificate expires, users see a message with the following warning when starting Outlook:

The security certificate has expired or is not yet valid

renew exchange certificate

You can renew the certificate or release a new one through the ECP/EAC GUI (Exchange Admin Center) or using the PowerShell cmdlets from the Exchange Management Shell.

Next, we will show the steps for renewing the Exchange certificate using the ECP interface and then share similar EMS commands.

Renew Exchange Certificate from Exchange Admin Center

Open the Exchange control panel by going to the following URL:

https://your_exch_srv_name/ecp/

First, you need to generate a certificate renewal request. Go to the Server > Certificate section. Select an expired certificate and click the Renew button. Save the certificate renewal file (.req) to a shared network folder.

exchange renew ssl certificate

The status of the certificate in the EAC will change to Pending Request.

Submit the req file for certificate renewal to your Certification Authority (external or internal CA). Based on your request, certificate manager should generate a certificate and return you a new .cer file.

Select your certificate in the EAC console and click Complete.

exchange renew self signed certificate

Specify the UNC path to your certificate file in the shared network folder and click OK.

Now you need to assign (reassign) a certificate to Exchange services (usually IMAP, POP, IIS).

renew exchange certificate step by step

It remains to restart IIS on the Exchange server with the command:

iisreset

The certificate status in the Exchange console should change to Valid.

You can export the new certificate to other Exchange servers. To do this, export the certificate into the .pfx format (it contains the private key, so use a cryptographic password to protect cert file). Import the certificate on the destination Exchange servers.

Renew Exchange Server Certificate Using PowerShell

Display the full list of Exchange certificates and copy the ThumbPrint of the certificate you want to renew.

Get-ExchangeCertificate | C:\ExchangeCertThumbPrint.txt

For example, your certificate ThumbPrint is 1234512345123451234512345123451234512345.

Use the following PowerShell command to create renewal request for your certificate and save it on a shared folder:

Get-ExchangeCertificate -Thumbprint 1234512345123451234512345123451234512345| New-ExchangeCertificate -GenerateRequest -RequestFile "\\your_exch_srv_name\share\renewcert.req" -PrivateKeyExportable:$true

After receiving a new certificate from CA, complete the certificate request:

Import-ExchangeCertificate -FileName “\\your_exch_srv_name\share\company_new_sslcert.cer" -PrivateKeyExportable:$true

Now enable this certificate for the required Exchange services:

Enable-ExchangeCertificate –Thumbprint 9519495194951949519495194951949519495194 –Services "IIS, SMTP, POP, IMAP"

It remains only to restart IIS on your Exchange server:

Restart-Service W3SVC

The post How to Renew SSL Certificate on Exchange Server? appeared first on TheITBros.


Hyper-V: Nested Virtualization on Windows Server 2016

$
0
0
Hyper-V Nested Virtualization

Nested virtualization allows you to run Hyper-V inside a virtual machine and create several more virtual machines in this nested Hyper-V server. Most often, nested virtualization is used in test environments.

Microsoft Hyper-V supports nested virtualization starting from Windows Server 2016. If you try to install the Hyper-V role inside the VM on the guest Hyper-V with Windows Server 2012 R2 (or older), you will get the install error:

Hyper-V can not be installed: The hypervisor is already running.

windows nested virtualization

This error is related to the fact that the Hyper- host V specifically masked the Intel VT-x and AMD-V Virtualization Extensions from the guest OS. In Windows Server 2016, the Hyper-V architecture has been redesigned. CPU requirements have also changed. Now, for nested virtualization to work, in addition to supporting Intel VT-x, the processor must support Intel EPT (provides virtual machines memory direct access, bypassing the hypervisor).

Other limitations when using nested virtualization:

  1. Host and guest Hyper-V must use Windows Server 2016/2019 or Windows 10;
  2. Hyper-V VM hardware version >=8.0;
  3. For nested virtual machines the following features are nor supported; dynamic memory, dynamic migration, VM checkpoints, and Save/Restore options.

How to Enable and Use Nested Virtualization in Windows Server 2016?

First of all, you need to update the version of the Hyper-V VM configuration (vm hardware) for which you want to enable nested virtualization to 8.0 or higher (the virtual machine must be turned off). To do this, run the Hyper-V Manager console, find the VM, right-click it and select Upgrade Configuration Version.

windows server 2016 nested virtualization

You can also upgrade the HW version of the virtual machine through PowerShell:

Update-VMVersion -Name ‘WinSrv2016Nested’

server 2016 nested virtualization

You can update all VMs on the host at once:

Get-VM | Update-VMVersion

Now you need to enable nested virtualization support for the selected virtual machine. By default, the hypervisor masks virtualization CPU instruction that are sent to the guest. To change this behavior, use the command:

Set-VMProcessor -VMName VMName -ExposeVirtualizationExtensions $true

Because dynamic memory is not supported for nested Hyper-V, you must disable this option in the VM settings (VM > Settings > Memory > uncheck Enable Dynamic Memory).

nested virtualization windows server 2016

Or you can disable dynamic memory through PowerShell:

Set-VMMemory "'WinSrv2016Nested' -DynamicMemoryEnabled $false

If you plan to provide access for nested virtual machines on an external network, the host Hyper-V can see several MAC addresses on a single network adapter of the virtual machine. Therefore, you need to enable MAC address spoofing for the VM network adapter.

Open the VM properties in the Hyper-V manager console, find the VM network adapter and in the Advanced features section enable the Enable MAC address spoofing option.

windows server 2016 enable nested virtualization

You can also enable this option via PowerShell:

Get-VMNetworkAdapter -VMName 'WinSrv2016Nested' | Set-VMNetworkAdapter -MacAddressSpoofing On

To quickly check VMs and enable nested virtualization memory, you can use a ready-made PowerShell script Enable-NestedVm.ps1. You can run it as follows:

Invoke-WebRequest https://raw.githubusercontent.com/Microsoft/Virtualization-Documentation/master/hyperv-tools/Nested/Enable-NestedVm.ps1 -OutFile ~/Enable-NestedVm.ps1 ~/Enable-NestedVm.ps1 -VmName 'WinSrv2016Nested'

Now you just have to install the Hyper-V role in the virtual machine (Install-WindowsFeature -Name Hyper-V -IncludeManagementTools -Restart) and you can create nested virtual machines.

The post Hyper-V: Nested Virtualization on Windows Server 2016 appeared first on TheITBros.

Import Users Into Active Directory From CSV

$
0
0
Import Users Into Active Directory From CSV

If you need to create many new user accounts in a domain at once, it is extremely inefficient to create them all manually from the graphical console Active Directory Users and Computers (ADUC). In this article, we will take a look at a simple PowerShell script that allows you to import user data from a CSV/XLS file and create accounts for them in the Active Directory domain.

First of all, create a NewUser.xlsx file in Excel with the following header structure:

FullName;sn;givenName;company;department;title;telephoneNumber;City;sAMAccountName;Password

Fill the Excel file with the data of all users that you want to create in Active Directory (usually this data is provided from the personnel accounting system).

import users into active directory from csv

Export the Excel file to CSV format with commas as separators (File > Save as > File type: CSV, File name: new_as_users.csv). If you want to use “;” as a separator, you need to add the following argument to the Import-CSV cmdlet -delimiter “;”.

import users into active directory

To create new users in the domain, we will use the New-ADUser cmdlet from the Active Directory for Windows PowerShell module, so before running the PowerShell script, make sure that this module is installed on the server/computer from which you are performing users import.

Create an import_ad_users.ps1 file with the following PowerShell code (change the name of your domain and the Active Directory Organizational Unit (OU) in which you want to create users):

Import-Module ActiveDirectory

$Domain="@theitbros.cpm"

$UserOu="OU=Users,OU=UK,DC=theitbros,DC=com"

$NewUsersList=Import-CSV "C:\PS\new_as_users.csv"

ForEach ($User in $NewUsersList) {

$FullName=$User.FullName

$Company=$User.company

$Department=$User.department

$Description=$User.description

$givenName=$User.givenName

$title=$User.title

$City=$User.City

$telephoneNumber=$User.telephoneNumber

$sAMAccountName=$User.sAMAccountName

$sn=$User.sn

$userPrincipalName=$User.sAMAccountName+$Domain

$userPassword=$User.Password

$expire=$null

New-ADUser -PassThru -Path $UserOu -Enabled $True -ChangePasswordAtLogon $True -AccountPassword (ConvertTo-SecureString $userPassword -AsPlainText -Force) -CannotChangePassword $False -City $City -Company $Company -Department $Department –title $title –OfficePhone $telephoneNumber -DisplayName $FullName -GivenName $givenName -Name $FullName -SamAccountName $sAMAccountName -Surname $sn -UserPrincipalName $userPrincipalName

}

Note. Options-ChangePasswordAtLogon $True requires changing the user password at the first login, -CannotChangePassword $False – allows the user to change passwords by himself. If you create service accounts, you can specify -ChangePasswordAtLogon $False, -CannotChangePassword $True.

Run the script from the PowerShell command prompt, then open the ADUC console and make sure that new users appeared in the specified OU.

import users into active directory from csv powershell

As you can see, this PowerShell script allows the mass import of users into Active Directory in a few minutes. You can remove or add any user attributes to the script and CSV/Excel file from AD. A complete list of available user attributes in your domain schema can be displayed using the following cmdlet:

Get-ADUser –identity administrator –filter * -properties *|fl

import contacts into active directory

The post Import Users Into Active Directory From CSV appeared first on TheITBros.

How to Install and Configure SNMP Service on Windows 10?

$
0
0
snmp service cover

Simple Network Management Protocol or SNMP is used for monitoring, event notification, and network device management on corporate networks. The protocol consists of a set of network management standards, including the Application Layer protocol, database schemas, and a set of data objects. SNMP can receive various information (uptime, performance counters, device parameters, etc.) from any network devices: switches, servers, routers or computers on which the SNMP agent is installed. In Windows 10, the SNMP service is available as a separate Windows component and it’s not installed by the default.

How to Install SNMP Service in Windows 10?

You can check if the SNMP service is installed on your Windows 10 using the PowerShell cmdlet Get-Service:

Get-Service -Name snmp*

Most likely, the service has not been installed yet.

You can install the SNMP service via the Control Panel. Go to the Control Panel > Programs and Features > Turn Windows features on or off. In the list of Windows features, select Simple Network Management Protocol (SNMP) and the WMI SNMP Provider (provides access to SNMP information via the Windows Management Instrumentation interfaces) and click OK.

snmp windows 10

You can also install SNMP service using PowerShell:

Enable-WindowsOptionalFeature -online -FeatureName SNMP

This command can help you to install SNMP service on Windows 10 in 1803 build or earlier. Starting from Windows 10 1809 Microsoft has changed the way to deploy snmp service on desktop OSs.

Installing SNMP Service in Windows 10 1803 and Newer

In Windows 10 1803 and later (1809, 1903), the SNMP service is considered deprecated and is not listed in the Windows features in the Control Panel list.

windows 10 snmp

Microsoft plans to completely remove the SNMP service in the next Windows builds because of the security risks associated with this protocol. Instead of SNMP, it is recommended to use the Common Information Model (CIM), which is supported by Windows Remote Management. On the current builds of Windows 10, the SNMP service is hidden.

The SNMP service is now missing from the Windows 10 image and can only be installed as Feature On Demand (FoD).

If your computer has a direct Internet connection, you can install the SNMP service components online from Microsoft servers. To do this, open the elevated PowerShell console and run the command:

Add-WindowsCapability -Online -Name "SNMP.Client~~~~0.0.1.0"

enable snmp windows 10

You can also use DISM to install the SNMP service:

DISM /online /add-capability /capabilityname:SNMP.Client~~~~0.0.1.0

After that, you can verify that the SNMP service is installed:

Get-WindowsCapability -Online -Name "SNMP*"

install snmp windows 10

Name : SNMP.Client~~~~0.0.1.0

State : Installed

DisplayName : Simple Network Management Protocol (SNMP)

Description : This feature includes Simple Network Management Protocol agents that monitor the activity in network devices and report to the network console workstation

DownloadSize : 595304

InstallSize : 1128133

To disable the SNMP service, use the PowerShell command:

Remove-WindowsCapability -Online -Name "SNMP.Client~~~~0.0.1.0"

You can also install the SNMP service through the Optional Features graphical interface.

Go to the Settings > Apps > Apps & Features > Manage optional feature > Add Feature. Select in the list the following features: Simple Network Management Protocol (SNMP) and WMI SNMP Provider (to get all SNMP service configuration tabs).

snmp service windows 10

After that, the SNMP service will appear in the services.msc console.

If when performing the Add-WindowsCapability command you received the “Add-WindowsCapability failed error. Error code = 0x800f0954”, most likely your computer receives Windows updates not from Microsoft Update servers but from the internal WSUS server. To make SNMP service receiving install files from Microsoft servers, you need to temporarily bypass the WSUS.

To do this, run the command:

reg add "HKEY_LOCAL_MACHINE\Software\Policies\Microsoft\Windows\WindowsUpdate\AU" /v UseWUServer /t REG_DWORD /d 0 /f

After that, restart the Windows Update service:

netshh winhttp reset proxy
net stop wuauserv
net start wuauserv

Now try to install the SNMP service with the Add-WindowsCapability command. If all goes well, return the initial wusuaserv service registry parameter pointing to the WSUS server. Run the command:

reg add "HKEY_LOCAL_MACHINE\Software\Policies\Microsoft\Windows\WindowsUpdate\AU" /v UseWUServer /t REG_DWORD /d 1 /f

And restart the Windows Update Service.

Configure SNMP on Windows 10 Computer

After the installation, SNMP services should start automatically. Open the Services management console (services.msc). Two new services should appear in the service list:

  • SNMP Service – This is the primary SNMP agent service, that tracks activity and sends information;
  • SNMP Trap – Receives trap messages from local or remote SNMP agents, and forwards messages to the SNMP management software that is being run on that computer.

Open the properties of the SNMP Service. If it is stopped, start it by pressing the Start button and change the startup type to Automatic.

windows 10 enable snmp

Click the Agent tab. Fill in the Contact and Location fields (you can specify the user’s contact name and computer location), and select the list of services from which you want to collect data and send it to the monitoring device. There are five service-based options:

  • Physical;
  • Applications;
  • Internet;
  • End-to-end;
  • Datalink and subnetwork.

windows 10 snmp service

Click the Security tab. Here you can configure various security settings for different SNMP servers.

The list of Accepted community names contains the names of the communities whose SNMP hosts are authenticated to send SNMP requests to this computer. The community name has the same functions like login and password.

Click the Add button and specify the Community Name and one of the five access levels (None, Notify, READ ONLY, READ WRITE, READ CREATE). READ WRITE is the maximum access level at which the SNMP management server can make changes on the system. For monitoring systems, it is usually enough to select READ ONLY, while the monitoring server can only poll the system, but not make changes. In our example, we added a community name public with READ ONLY permissions.

Add to the Accept SNMP packets from these hosts list of monitoring servers (hostnames or IP addresses) from which you want to accept SNMP packages.

how to enable snmp on windows 10

Tip. You can select the Accept SNMP packets from any host option, but this is not safe.

Save the changes and restart the SNMP service.

This completes the SNMP service configuration in Windows 10. If you need to enable SNMP on multiple computers or servers, you can remotely install and configure SNMP service using PowerShell or Group Policy.

The post How to Install and Configure SNMP Service on Windows 10? appeared first on TheITBros.

How to Find Active Directory User’s/Computer’s Last Logon Time?

$
0
0
Get User Last Logon Time

The Active Directory administrator must periodically disable and inactivate objects in AD. In this article, we will show how to get the last logon time for the AD domain user and find accounts that have been inactive for more than 90 days.

How to Get Last Logged on User Using ADUC?

You can find out the last logon time for the domain user with the ADUC graphical console (Active Directory Users and Computers).

  1. Run the console dsa.msc;
  2. In the top menu, enable the option View > Advanced Features;
    active directory user last logon time
  3. In the AD tree, select the user and open its properties;
  4. Click on the tab Attribute Editor;
  5. In the list of attributes, find lastLogon. This attribute contains the time the user was last logged in the domain.

last logon time active directory powershell

Find Last Logon Time Using CMD

You can find out the time the user last logged into the domain from the command line using the net or dsquery tools.

Open a command prompt (you don’t need domain administrator privileges to get AD user info) and run the command:

net user administrator /domain| findstr "Last"

You got the user last login time: 08.08.2019 11:14:13.

powershell command to find last logon time for all users

You can also get the last login time using dsquery. For example:

dsquery * domainroot -filter "(&(objectCategory=Person)(objectClass=User)(sAMAccountName=administrator))" -attr distinguishedName lastLogon lastLogonTimestamp -limit 0

The main problem is that the attributes lastLogon and lastLogonTimestamp in AD are stored in timestamp format and you need to additionally convert it to a normal time format.

last logon time powershell

You can also use this command to find all users who are inactive, for example, for 10 weeks:

dsquery user domainroot -inactive 10

Find Last Logon Time Using PowerShell

You can also use PowerShell to get the user last domain logon time. For this, you need to use

Active Directory module for Windows PowerShell. Install this module and import it into your PowerShell session:

Import-Module ActiveDirectory

To find the last logon time for the domain administrator account, run the command:

Get-ADUser -Identity administrator -Properties LastLogon

The cmdlet returned the time in Timestamp format. To convert it to normal time use the following command:

Get-ADUser -Filter {Name -eq "administrator"} -Properties * | Select-Object Name, @{N='LastLogon'; E={[DateTime]::FromFileTime($_.LastLogon)}}

powershell get last logged on user

Using PowerShell, you can display Lastlogon time for all enabled domain users:

Get-ADUser -filter {enabled -eq $true} -Properties * | Select-Object Name, @{N='LastLogon'; E={[DateTime]::FromFileTime($_.LastLogon)}}|Sort-Object LastLogon -Descending

last logon time active directory

Or you can find users who are inactive for more than 90 days:

$date1= (Get-Date).AddDays(-90)

Get-ADUser -Properties LastLogonDate -Filter {LastLogonDate -lt $date1} | ft

The post How to Find Active Directory User’s/Computer’s Last Logon Time? appeared first on TheITBros.

How to Check Windows Uptime?

$
0
0
Check Windows Uptime

Uptime is the measure of the uninterrupted time that an operating system experiences since the last boot. Unlike Linux/Unix, Windows doesn’t have a native uptime command. On Windows, you can get the computer uptime value in several different ways: from the GUI, command prompt, or PowerShell. Let’s consider all methods on how to check Windows uptime.

Check Windows Uptime Using Task Manager

You can check the current Windows uptime value from the GUI. To do this, use the Task Manager.

  1. Press Ctrl + Shift + Esc to run the Task Manager;
  2. Click the Performance tab;
  3. The current uptime value is indicated in the Up time label (in this example, the computer didn’t reboot for 5 days).
    check windows uptime

Show Your Computer Uptime Using CMD

To get the uptime of a computer from the command prompt, you can use one of the methods below.
Run the command prompt as an administrator and execute the command:

systeminfo|FIND “System Boot Time”

The command should return the following response:

System Boot Time: 9/27/2019, 1:15:55 PM

windows uptime command

Also, you can get the uptime value using the built-in statistics of any system service that has been working non-stop since the system booted. These are typically server or workstation services. For example:

net statistics workstation |find “Statistics since”

Statistics since ?9/?27/?2019 1:16:18 PM

windows show uptime

Another way to get the Windows uptime is through WMI. The standard wmic utility is used:

wmic path Win32_OperatingSystem get LastBootUpTime

or

wmic path Win32_OperatingSystem get LastBootUpTime

LastBootUpTime

20190927131555.500000+120

check windows server uptime

To get uptime from a remote server/computer, use this command:

wmic /node:"lon-man01" os get lastbootuptime

check uptime windows 10

How to Check Windows Uptime Using PowerShell?

Now let’s look at ways to check uptime from PowerShell. Computer boot time is also can be requested through WMI:

Get-CimInstance Win32_OperatingSystem | Select-Object LastBootUpTime

windows server uptime command

Or you can get the date of the last OS boot in a more convenient form:

$wmi = Get-WmiObject Win32_OperatingSystem

$wmi.ConvertToDateTime($wmi.LastBootUpTime)

windows uptime command line

Friday, September 27, 2019 1:15:55 PM

To find out how many days your computer has been running without rebooting up to the current date, run:

(get-date) - (gcim Win32_OperatingSystem).LastBootUpTime

windows 10 check uptime

You got the computer up to the millisecond:

Days : 5

Hours : 20

Minutes : 15

Seconds : 11

Milliseconds : 256

Ticks : 5049112566859

TotalDays : 5.84388028571643

TotalHours : 140.253126857194

TotalMinutes : 8415.18761143167

TotalSeconds : 504911.2566859

TotalMilliseconds : 504911256.6859

Checking Windows Uptime Using Event Viewer

OS boot time can also be obtained from the Event Viewer. When the computer boots up, EventID 6005 appears in events (and the EventID 6005 when the Windows shuts down).

Open the Event Viewer > Windows Logs > System > right click > Filter current log > Event ID 6005 – Ok.

windows 10 uptime command

Open the last event (The Event log service was started). Computer boot time is indicated on its date.

find windows uptime

You can also get the time of this event from PowerShell:

Get-WinEvent -ProviderName EventLog | Where-Object {$_.Id -eq 6005} | Select-Object -First 1 TimeCreated

powershell get system uptime

Get Uptime of Multiple Windows Computers in AD Domain with PowerShell

To find uptime across many computers (servers) in the AD domain you can use the following PowerShell script (we are using the Active Directory for Windows PowerShell module to get the computer list from a specific OU):

import-module activedirectory

$Servers = get-adcomputer -properties DNSHostName -Filter { enabled -eq "true" -and Operatingsystem -like "*Windows Server*" } -SearchBase ‘OU=Servers,OU=London,DC=corp,DC=theitbros,DC=com’

Foreach ($server in $Servers){

write-host $server.DNSHostName

Invoke-Command -ComputerName $server.DNSHostName -ScriptBlock { ("Uptime " + ((get-date) - (gcim Win32_OperatingSystem).LastBootUpTime).days) + " days" }

}

check windows 10 uptime

The post How to Check Windows Uptime? appeared first on TheITBros.

How to Delete AD User Using PowerShell?

$
0
0
Remove AD User Using PowerShell

You can remove user objects from an Active Directory domain by using the Remove-ADUser PowerShell cmdlet. This cmdlet is a part of the ActiveDirectory Module for Windows PowerShell, which must be pre-installed and imported into the PoSh session with the command:

Import-Module activedirectory

The syntax of the Remove-ADUser cmdlet looks as follows:

Remove-ADUser [-Identity] <ADUser> [-WhatIf] [-Confirm] [-AuthType <ADAuthType> {Negotiate | Basic}] [-Credential <pscredential>] [-Partition <string>] [-Server <string>] [<CommonParameters>]

In the -Identity parameter you must specify the AD user account to remove. You can specify a username in several ways, by using: distinguished name (DN), GUID, security identifier (SID) or SAM account name.

To remove the user with the user logon name b.jackson, run the command:

Remove-ADUser b.jackson

A prompt appears that asks you to confirm the removal of the user object from the domain. To delete a user, press Y > Enter.

powershell disable ad user

To remove AD user without confirmation prompt, add -Confirm:$False at the end:

Remove-ADUser b.jackson -Confirm:$False

You can remove several domain users at once using a simple PowerShell script. Create a text file Users.txt with a list of users to remove.

b.jackson

brett.jackson

t.mauer

a.kit

s.cooper

To remove AD users from the list from a text file, use the following PowerShell script:

Import-Module Activedirectory

$users = Get-Content "c:\PS\Users.txt"




ForEach ($user in $users)

{

Start-Sleep -s "1"

Remove-ADUser -Identity $remove -Confirm:$false

Write-host $user "Deleted"

}

 

powershell delete ad user

Before running the script, it is advisable to run it once in the –WhatIf mode.

If you want to log the results (which users were deleted) to a text file, add the following pipeline:

| Out-File c:\ps\removeusers_log.txt -Encoding ASCII -Append -PassThru

You can delete all blocked (disabled) user accounts in domain. To select disabled AD users, use the Search-ADAccount cmdlet (available in PowerShell 4.0 and newer):

Search-ADAccount -AccountDisabled | where {$_.ObjectClass -eq 'user'} | Remove-ADUser

Using PowerShell and the LastLogon attribute, you can find inactive user accounts that have not logged into the domain, for example, more than 6 months. To remove such user objects, run the script:

$lastdate= (Get-Date).AddDays(-180)

Get-ADUser -Properties LastLogonDate -Filter {LastLogonDate -lt $lastdate } | Remove-ADUser –WhatIF

You can run a simple PowerShell onliner to remove disabled and inactive users from a specific Organizational Unit in Active Directory:

get-aduser -filter "enabled -eq 'false'" -property WhenChanged -SearchBase "OU=Employees,OU=HQ,DC=theitbros,DC=com" | where {$_.WhenChanged -le (Get-Date).AddDays(-180)} | Remove-ADuser -whatif

The post How to Delete AD User Using PowerShell? appeared first on TheITBros.

How to Create a GUI for PowerShell Scripts?

$
0
0
powershell gui creator

One of the significant drawbacks of PowerShell scripts, when used by users (not sysadmins or programmers), is its command-line interface. The result of the scripts is displayed in the PowerShell CLI console and it is not always convenient for the end user. However, Powershell is a powerful and modern automation tool for Windows that allows you to transparently use a variety of .NET Framework objects. For example, using the .NET API, you can easily create a simple graphical interface (GUI) for your PowerShell scripts.

In this example, we’ll show you how to create a simple Windows GUI form using PowerShell and place on it various standard Windows Forms controls elements: textboxes, buttons, labels, checkboxes/listboxes, radiobuttons, datagrids, etc. For example, our task is to build a simple GUI for a PowerShell script that shows the last password change time for the Active Directory user. In this example, we use PowerShell 3.0+ and PowerShell ISE for easy code editing.

Create Windows Form with PowerShell

To use the .NET functionality to create forms, we use the class System.Windows.Forms. To load this class into a PowerShell session, you can use the following code:

Add-Type -assembly System.Windows.Forms

Now create the screen form (window) to contain elements:

$main_form = New-Object System.Windows.Forms.Form

Set the title and size of the window:

$main_form.Text ='GUI for my PoSh script'

$main_form.Width = 600

$main_form.Height = 400

To make the form automatically stretch, if the elements on the form are out of window bounds, use the AutoSize property.

$main_form.AutoSize = $true

Now you can display the form on the screen.

$main_form.ShowDialog()

powershell gui

Adding Dialog-Box Components to your PowerShell Form

As you can see, an empty form was displayed. To add various graphical dialog and control elements to it, add the code below before the last line ($main_form.ShowDialog()).

Create a label element on the form:

$Label = New-Object System.Windows.Forms.Label

$Label.Text = "AD users"

$Label.Location  = New-Object System.Drawing.Point(0,10)

$Label.AutoSize = $true

$main_form.Controls.Add($Label)

Create a drop-down list and fill it with a list of accounts from the Active Directory domain. You can get AD user list using the Get-ADuser cmdlet (from Active Directory for Windows PowerShell module):

$ComboBox = New-Object System.Windows.Forms.ComboBox

$ComboBox.Width = 300

$Users = get-aduser -filter * -Properties SamAccountName

Foreach ($User in $Users)

{

$ComboBox.Items.Add($User.SamAccountName);

}

$ComboBox.Location  = New-Object System.Drawing.Point(60,10)

$main_form.Controls.Add($ComboBox)

Add two more labels to the form. The second will show the time of last password change for the selected user account:

$Label2 = New-Object System.Windows.Forms.Label

$Label2.Text = "Last Password Set:"

$Label2.Location  = New-Object System.Drawing.Point(0,40)

$Label2.AutoSize = $true

$main_form.Controls.Add($Label2)

$Label3 = New-Object System.Windows.Forms.Label

$Label3.Text = ""

$Label3.Location  = New-Object System.Drawing.Point(110,40)

$Label3.AutoSize = $true

$main_form.Controls.Add($Label3)

Now put the button on the form:

$Button = New-Object System.Windows.Forms.Button

$Button.Location = New-Object System.Drawing.Size(400,10)

$Button.Size = New-Object System.Drawing.Size(120,23)

$Button.Text = "Check"

$main_form.Controls.Add($Button)

The following code will be executed when the user clicks on the button. To convert the date from the TimeStamp format to the more convenient form, we use the function [datetime]::FromFileTime:

$Button.Add_Click(

{

$Label3.Text =  [datetime]::FromFileTime((Get-ADUser -identity $ComboBox.selectedItem -Properties pwdLastSet).pwdLastSet).ToString('MM dd yy : hh ss')

}

)

Run the PowerShell script. As you can see, the drop-down list is automatically filled with the names of the user accounts from Active Directory. If you select the user account and click the Check button, the form displays the time when the user’s last password was changed in Active Directory.

powershell gui builder

So you built your first simple graphical user interface for a PowerShell script. What’s next? Now you can add a more complex UI element to your PowerShell form.

Commonly Used PowerShell UI Elements

Similarly, you can create the following graphic elements on the form:

  • CheckBox – used to list some options and select them prior running script
  • RadioButton – lists some text options and allow to select only one of them;
  • TextBox – user can write some text. It can be used to get the vapue of the PoSh script parameter;
  • Label – used for labeling some parts of scripts’ GUI.
  • ChekedListBox – shows a list of items;
  • DataGridView – allows to view some tabular data;
  • GroupBox – allows to view to group a set of controls together;
  • ListBox – can store several text items;
  • TabControl – allows to split your form into different areas (tabs)
  • ListView – displays a list of items with text and (optionally) an icon
  • TreeView – hierarchical objects view;
  • DateTimePicker – allows to select date and time;
  • TrackBar – scrollable control;
  • PictureBox – allows to show picture on the form;
  • ProgressBar – indicates the operation progress
  • HScrollBar – horizontal scroll bar;
  • VScrollBar – vertical scroll bar;
  • ContextMenu – right click menus;
  • Menu – top menu in your form.

Building PowerShell Scripts’ GUI Using Visual Studio

You can use Visual Studio with a WPF (Windows Presentation Foundation) as a simple PowerShell GUI builder. Download and install Visual Studio Community 2019 version.

WPF is a part of the .NET Framework that can be used to visualize user interfaces in Windows apps.

Run Microsoft Visual Studio and create a new Project (File > New > Project). Select Visual C# > Windows Forms App (.NET Framework)

powershell gui examples

Use Windows Forms element in the left Toolbox pane to place (with drag&drop) your control element on the form.

powershell ui

The Visual Studio will generate an XAML code for you. Save this code into the file C:\PS\Script\MainWindow.xaml. Open this file using Notepad and remove the following string:

x:Class="test.MainWindow”

And save the changes in the xaml file.

Now you can read this XAML code from you PowerShell script and display a Windows Form.

Use the following function to load XAML object:

$XamlPath = “C:\PS\Script\MainWindow.xaml”

[xml]$Global:xmlWPF = Get-Content -Path $XamlPath

try{

Add-Type -AssemblyName PresentationCore,PresentationFramework,WindowsBase,system.windows.forms

} catch {

Throw "Failed to load WPF."

}

$Global:xamGUI = [Windows.Markup.XamlReader]::Load((new-object System.Xml.XmlNodeReader $xmlWPF))

$xmlWPF.SelectNodes("//*[@*[contains(translate(name(.),'n','N'),'Name')]]") | %{

Set-Variable -Name ($_.Name) -Value $xamGUI.FindName($_.Name) -Scope Global

}

To display your form use:

$xamGUI.ShowDialog()

Use the Online Editor to Create a Form for your PoSh Script

For more convenient creation of graphical elements for PowerShell forms, you can use the online editor to create a GUI form for PowerShell scripts: https://poshgui.com/Editor. With it, you can create a beautiful form with the necessary dialog elements.

powershell menu gui

And get the ready PoSh code for your GUI scripts. Just copy this code into your PowerShell ISE, change element names (optionally) and run the code to display the generated form on your computer.

gui powershell

The post How to Create a GUI for PowerShell Scripts? appeared first on TheITBros.


Get-service: Checking the Status of Windows Services with PowerShell

$
0
0
get service command

You can use the Get-Service cmdlet to get a list of all the services installed on the Windows operating systems, their status and startup type. This one and other cmdlets to get the status and management of Windows services first time appeared in Powershell 1.0. In this article we will demonstrate typical examples of Get-Service cmdlet usage to get the status of a service on local or remote computers, the type of services startup, also we’ll cover how to determine the dependencies of services.

You can get a list of services on a local or remote computer by using the Get-Service cmdlet. Get-Service command without parameters returns a list of all services on the local system.

Use Get-Service to Check Windows Service Status

This command will list all local Windows services, their status (running or stopped) and display name.

get-service remote computer

To save the service list to a text file for future investigation, use the Out-File cmdlet:

Get-Service | Out-File "C:\PS\Current_Services.txt"

To get two or more service state, you need to specify its name divided by commas:

get-service bits, wuauserv

If you need to display only running services, use this command:

Get-Service | Where-Object {$_.Status -EQ "Running"}

The pipeline operator (|) passes the results to the Where-Object cmdlet, which selects only those services for which the Status parameter is set to “Running”. If you want to display only the stopped services, specify “Stopped”.

powershell get service status

You can get all the properties of the service object using the Get-Member.

get-service | get-member

As you can see, these objects have the Typename –  System.ServiceProcess.ServiceController. The screenshot shows all the available properties and methods of service objects in the system (most of them are not used when displaying by default).

powershell get-service remote computer

To display specific properties of the service, use the next command. For example, we need to display the Display Name, status and features of the Windows Update (wuauserv) service:

get-service wuauserv | select Displayname,Status,ServiceName,Can*

DisplayName : Windows Update

Status : Stopped

CanPauseAndContinue : False

CanShutdown : False

CanStop : False

powershell check service status

You can find all services that can be paused and resumed without Windows restart:

Get-Service | Where-Object {$_.canpauseandcontinue -eq "True"}

For example, to get the type of Windows services startup type, run the command (works in PowerShell 5.1):

Get-Service | select -property name,starttype

You can filter the services list by the service name using the asterisk as a wildcard:

get-service wi*

Also, note that the PowerShell is not a not case-sensitive language. It means that the following command will return the equal results:

get-service win*

get-service WIN*

To exclude some service from resulting list you can use the -Exclude option:

Get-Service -Name "win*" -Exclude "WinRM"

You can sort services in descending order by the value of the Status property (running services are displayed earlier than stopped):

get-service s* | sort-object status – Descending

How to Check if a Specific Service Exists via PowerShell?

If you want to check whether a specific Windows service in exist on current, you can use the following commands (usually used in various scripts):

$servicename = “SomeService”

if (Get-Service $servicename -ErrorAction SilentlyContinue)

{

Write-Host "$servicename exists"

# do something

}

Else {

Write-Host " $servicename not found"

# do something

}

get service status powershell

You can check if a specific Windows service exists on a list of remote computers/servers. To do this task you need to save the list of remote computers to the text file comp_list.txt in the simple format:

server1

server2

server3

PC21

PC34

powershell get-service

And run the following PowerShell script:

$servicename = "SomeService"

$list = get-content “c:\ps\comp_list.txt”

foreach ($server in $list) {

if (Get-Service $servicename -computername $server -ErrorAction 'SilentlyContinue'){

Write-Host "$servicename exists on $server "

# do something

}

else{write-host "No service $servicename found on $server."}

}

Use PowerShell to Check Service Status on a Remote Computer

You can use the Get-Service cmdlet to get the status of services not only on the local, but also on remote computers. To do this, use the –ComputerName parameter. You can use the NetBIOS, FQDN name or an IP address as a computer name. Connection to remote computers is established not through PowerShell Remoting (WinRM), but through Service Manager (similar to the sc.exe command).

get-service wuauserv -ComputerName remotePC1

In PowerShell v3 you can get the status of the service on multiple remote computers at once, their names must be separated by commas.

get-service spooler -ComputerName remotePC1,remotePC2, remotePC3| format-table Name,Status,Machinename –autosize

powershell service status

Use the format-table cmdlet in this example to get a more convenient table with the list of the services status.

Also, you can get the services health on a list of remote computers that is being stored in a plain text file:

$list = get-content “c:\ps\comp_list.txt”
Get-Service -Computername (Get-Content -path “c:\ps\comp_list.txt”) -Name spooler | Select-Object MachineName,Name,Displayname,Status | Sort-Object Status

To restart a service on a remote computer, use the following command:

Get-Service wuauserv -ComputerName server1| Start-Service

Use Get-Service to Display Service Dependencies

The Get-Service cmdlet has two other useful parameters that you can use when managing Windows services. The DependentServices parameter returns services that depend on this service. The RequiredServices parameter returns the services on which this service depends.

The following command receives the services needed to start the LanmanWorkstation service.

Get-Service -Name LanmanWorkstation –RequiredServices

get-service powershell

The next command returns dependent services that require the LanmanWorkstation service.

Get-Service -Name LanmanWorkstation -DependentServices

If you manually stop all dependence services, you won’t be able to run your service. In order to automatically run all dependency services, use the following PowerShell one-liner:

get-service servicename | Foreach { start-service $_.name -passthru; start-service $_.DependentServices -passthru}

The post Get-service: Checking the Status of Windows Services with PowerShell appeared first on TheITBros.

How to Backup Active Directory on Windows Server 2016?

$
0
0
Backup Active Directory

In this article, we will take a look on how to backup an Active Directory domain controller running on Windows Server 2016. This backup will allow you to restore both individual AD objects and the entire AD domain in case of problems.

Although Active Directory services are designed with high redundancy (if you deployed several DCs in your company), an AD administrator needs to develop and implement a clear Active Directory backup policy. At least, you need to back up a DCs with FSMO roles and one DC per site. The specific recommendations for the backup strategy are highly dependent on your domain architecture and network structure.

Windows Server 2016 has a built-in Windows Server Backup component that allows you to backup Active Directory.

Using Windows Server Backup to Backup Active Directory

Open the Server Manager on your DC running Windows Server 2016 and select Add Roles and Features. Then click Next several times and set the Windows Server Backup checkbox on the Select features step.

backup active directory

Also, you can install the WSB feature on Windows Server using the PowerShell command:

Install-WindowsFeature -Name Windows-Server-Backup -IncludeAllSubfeature –IncludeManagementTools

Wait for the installation of Windows Server Backup to complete and click Close.

ad backup

Now in the Server Manager select Tools > Windows Server Backup.

active directory backup and restore in windows server 2016

Right click Local Backup item in the left pane and select Backup Schedule.

backup active directory 2016

On the Select Backup Configuration step select Custom.

backup active directory powershell

On the Select Items for Backup stage press Add Item and select the System State. This is enough to restore an Active Directory domain controller in failure cases.

The System State includes:

  • Active Directory database;
  • The Sysvol folder (with GPO objects);
  • Integrated DNS zones and records;
  • Certificate Authority service database;
  • System boot files;
  • System registry;
  • Component Services database.

As a result, you can restore ADDS services on the same server (OS recovery from system state backup on another server is not supported). If you plan to restore the domain controller on another server, you need to select the Bare metal recovery option.

windows server backup active directory

Set a backup schedule. For example, I want to back up AD daily at 12:00 AM.

windows backup active directory

You can backup your DC to a dedicated backup volume, or a shared network folder. I am using a dedicated volume, select it as a backup Destination Target.

windows ad backup

Press Finish to create a backup task.

windows server 2016 backup active directory

You can find the created backup task in the Task Scheduler. Browse to the Task Sheduler Library > Microsoft > Windows > Backup and find a task named Microsoft-Windows-WindowsBackup. This task is run NT Authority\SYSTEM account. If you want to create a DC backup immediately, open the task properties, go to the tab Setting and check the box “Allow task to be run on demand”. Save the changes by pressing OK. Then right click on task and select Run (or wait for the scheduled task to start).

backup ad server

After the backup process is completed, a directory with the name WindowsImageBackup appears on drive E:. Pay attention to the structure of the WindowsImageBackup directory. It contains a directory with the name of the domain controller, which contains the folder named by the backup copy creation time (for example, E:\WindowsImageBackup\dc01\Backup 2020-01-17 180557).

You can find a vhdx file inside this directory. This is a virtual hard disk image file with the backup Windows image of your domain controller. You can manually connect it through Disk Manager and access backup files.

active directory backup and recovery

How to Backup AD using Wbadmin and PowerShell?

You can also backup DCs using the wbadmin console utility. For example, to backup the system state of the running Windows Server and save it to a separate disk, run the command:

wbadmin start systemstatebackup -backuptarget:e: -quiet

This example overwrites the contents of the WindowsImageBackup directory on the target drive.

The list of available backup copies on the disk can be displayed as follows:

wbadmin get versions

backing up ad

To delete all old backup copies except the last, run the command:

wbadmin delete backup -keepVersions:1

You can also use the WindowsServerBackup module to backup Active Directory on a domain controller with PowerShell. The following PowerShell script will backup server’s System State to the specified drive:

$WBpolicy = New-WBPolicy

Add-WBSystemState -Policy $WBpolicy

$WBtarget = New-WBBackupTarget -VolumePath "E:"
Add-WBBackupTarget -Policy $policy -Target $WBtarget

Start-WBBackup -Policy $WBpolicy

To restore AD in the event of a disaster, you will need SystemState Backup in the root of the local DC drive. When restoring AD, you need to boot the server with the ADDS role in the Directory Services Restore Mode (DSRM).

The post How to Backup Active Directory on Windows Server 2016? appeared first on TheITBros.

How to Disable Active Directory Account Using PowerShell?

$
0
0
Disable Active Directory Account

An Active Directory administrator must periodically disable user and computer domain accounts that are not used for a long time. Disabled accounts cannot be used to log on the domain, even if the user knows the password for the account and it is not expired.

You can disable a user or computer account in Active Directory through the Active Directory Users & Computers graphical snap-in (ADUC). To do this, find the user account in the console, right-click on it and select Disable Account.

active directory disable account

Or you can open the user’s properties and enable the “Account is disabled” option in the “Account options” section on the “Account” tab.

powershell disable ad user

You can also disable Active Directory account using the PowerShell cmdlet Disable-ADAccount.

Install the Active Directory for Windows PowerShell and import it into the PS session with the command:

Import-Module ActiveDirectory

In order to disable the jbrion user account, run the command:

Disable-ADAccount -Identity jbrion

disable ad account powershell

In order to prompt the account disabling confirmation, you can add the –Confirm parameter.

Check that the account is disabled now (Enabled = False):

Get-ADUser jbrion |select name,enabled

powershell disable computer account

You can use the Disable-ADAccount cmdlet to disable both the computer and user or service account in domain. The following parameters of the AD object can be specified as an -Identity argument:

Hint. To enable an account, use the command: Get-ADUser jbrion | Enable-ADAccount

To disable all computer accounts in a specific OU:

Get-ADUser -Filter 'Name -like "*"' -SearchBase "OU=Laptops,OU=NY,OU=USA,DC=theitbros,DC=com" | Disable-ADAccount

To find all disabled computer accounts in the domain, use the command:

Search-ADAccount -AccountDisabled -ComputersOnly|select Name,LastLogonDate,Enabled

To display list user accounts:

active directory disable user

Hint. You can read more about special service AD account krbtgt.

With PowerShell, you can disable multiple AD accounts. To do this, create a text file with a list of user accounts that you want to disable. Then you can disable all user accounts from the txt file using the following PowerShell script:

$users=Get-Content c:\ps\users.txt

ForEach ($user in $users)

{

Disable-ADAccount -Identity $($user.name)

}

Similarly, you can disable computer accounts:

$computers= Get-Content c:\ps\computers.txt

ForEach ($computer in $computers)

{

Disable-ADAccount -Identity "$($computer.name)$"

}

Using the Search-ADAccount cmdlet, you can find all inactive accounts in domain and disable them at once. For example, you want to disable all users who have not logged into the domain for more than 3 months.

$timespan = New-Timespan -Days 90

Search-ADAccount -UsersOnly -AccountInactive -TimeSpan $timespan | Disable-ADAccount

The post How to Disable Active Directory Account Using PowerShell? appeared first on TheITBros.

How to Get Windows 10 User Login History Using PowerShell?

$
0
0
User Login History Using PowerShell

On Windows, you can track user login and logoff events using the Security log. In this article, we’ll show you how to get user login/logoff history from Event Logs on the local computer using simple PowerShell script.

In order the user logon/logoff events to be displayed in the Security log, you need to enable the audit of logon events using Group Policies.

You can enable login auditing on all domain-joined computers using a domain GPO.

  1. Run the Group Policy Management Console under domain admin account (gpmc.msc);
  2. Right-click on Default Domain Policy and select Edit; windows 10 user login history
  3. Go to the following GPO section: Computer Configuration > Policies > Windows Settings > Advanced Audit Policy Configuration > Audit Policies > Logon/Logoff;
  4. Enable the following GPO options: Audit Logoff, Audit Logon, Audit Other Logon/Logoff Events. To do this, in each policy, select the options Configure the following audit events > Success; powershell get user login history
  5. Save the GPO and wait until the new policy settings are applied to the domain computers (you can apply the policy on a client immediately using the gpupdate command).

Now, when a user logons locally or remotely to a computer, an event with EventID 4624 appears in the Windows Logs > Security event log.

You can manually filter all logon events with the specified code in the Event Viewer. Run the Compute Management console. Go to System Tools > Event Viewer > Windows > Logs > Security. Right-click on this section and select Filter Current Log. In the window that opens, specify Event ID 4624 and click OK.

windows user login history

As a result, only user logon events will be displayed in the event log. Open any Audit Success event. The event description says “An account was successfully logged on”. The name of the user who logged in is specified in the following message field:

New Logon:

Security ID: CORPjsmith

Account Name: jsmith

If the user has logged on from a remote computer, the name (or IP) of the computer will be specified in the: Source Network Address: 192.168.1.70

powershell user login history

Let’s try to use PowerShell to select all user logon and logout events. To select events with EventID 4634 and 4624, we use the Get-WinEvent cmdlet. The following PowerShell script must be run with elevated privileges.

$Results = @()

$logs =Get-WinEvent -LogName Security| Where-Object {$_.ID -eq 4634 -or $_.ID -eq 4624}

ForEach ($log in $logs) {

if ($log.Id -eq 4634)

{

$type=”SessionStop”

$username=$log.Properties[1].Value

}

 

Else {

$type=”SessionStart”

$username=$log.Properties[5].Value

}

if ($username -ne “”) {

$Results += New-Object PSObject -Property @{“Time” = $log.TimeCreated; “Event” = $type; “User” = $username};

}

}

$Results

powershell get specific user login history

After executing this script, you will get a list of all user logon/logoff events on this computer. If you want to select all events for a specific user account, add the following variable to the top of the script:

$userlog =”jsmith”

And replace the line:

if ($username -ne “”) {

to:

if ($username -eq $userlog) {

Specify the user name (not case-sensitive) for which you want to receive user activity report on a specific computer.

For convenience, you can display the results in a graphical table using Out-GridView. Just replace the last line with:
$Results|Out-GridView.

get user login history powershell

The post How to Get Windows 10 User Login History Using PowerShell? appeared first on TheITBros.

How to Create Office 365 Group?

$
0
0
Create Office 365 Group

Office 365 groups are objects that contain user lists. Office 365 groups used to share resources within and across different Azure apps (Teams, Outlook, OneDrive, OneNote, Skype for Business, Power BI, Dynamics CRM, etc.) and the organizations. Office 365 groups are stored in Azure Active Directory and can be Private or Public.

Creating Office 365 Group via Admin Portal

You can create an Office 365 group using the Exchange/Office 365 Admin Center.

  1. Connect to your Office 365 administrator mailbox and go to the Exchange Admin Center;
  2. Select Recipients and click Groups in the right pane; create office 365 group
  3. On the Basics tab, specify a unique group name, email address and description (optional);
  4. In the Privacy field, you can select the type of the group: Private or Public;
  5. Click the Save button to create a new group;
  6. After that, a window will appear in which you can add members to the group. Select the accounts you want to add and click Add.

You can also create an Office 365 group from other products that using Azure Active Directory, for example: Outlook (both online and desktop client), SharePoint, OneDrive, Teams, Power BI, Yammer, etc.

Creating Office 365 Group Using PowerShell

In order to create Office 365 groups with PowerShell, you need to import Exchange Online PowerShell module:

$LiveCred = Get-Credential

$Session = New-PSSession -ConfigurationName Microsoft.Exchange -ConnectionUri https://outlook.office365.com/powershell-liveid/ -Credential $LiveCred -Authentication Basic –AllowRedirection

Import-PSSession $Session

To create a new Office 365 group, use the New-UnifiedGroup cmdlet.

Create a group:

New-UnifiedGroup –DisplayName "ITBros Admins" -Alias "ITBrosAdmins" -AccessType Public

Hint. To display all groups in your Azure tenant, use the Get-UnifiedGroup cmdlet.

Now with the Add-UnifiedGroupLinks command, you can add members to your Office 365 group.

Add the user Brett.Jackson to the group:

Add-UnifiedGroupLinks –Identity "ITBrosAdmins " –LinkType Members –Links Brett.Jackson

You can make this user the owner of this group:

Add-UnifiedGroupLinks –Identity "ITBrosAdmins" –LinkType Owners –Links Brett.Jackson

Hint. You can set multiple owner for Office 365 group.

To add users to a group from a list in a CSV file, you can use the following PowerShell script:

Import-CSV "C:psnew_admins.csv" | ForEach-Object {

Add-UnifiedGroupLinks –Identity "ITBrosAdmins" –LinkType Members–Links $_.member

}

You can add a subscriber to the group (receives updates by email):

Add-UnifiedGroupLinks –Identity "ITBrosAdmins" –LinkType Subscribers –Links Mary.Jordan

To list all members of the Office 365 group, run the command:

Get-UnifiedGroupLinks –Identity "ITBrosAdmins" –LinkType Members

To hide a group from the global address list (GAL) and other lists in your organization, use the command:

Set-UnifiedGroup -Identity "ITBrosAdmins" -HiddenFromAddressListsEnabled $true

You can also set a mailtip for your group (MailTip appears in the Outlook address bar of a user who is trying to send email to the specified group):

Set-UnifiedGroup -Identity "ITBrosAdmins" -DisplayName "This is group of ITBros sysops"

To close the opened PowerShell session with Office 365, run the command:

Remove-PSSession $Session

The post How to Create Office 365 Group? appeared first on TheITBros.

PowerShell: Move Computer to OU

$
0
0
powershell move computer to ou

By default, when you join a new computer or server to the Active Directory domain (through the properties of the computer), it creates the computer object in the Computers root container. If you use a complex Active Directory Organizational Unit (OU) structure in your domain with various Group Policies, delegated container and policies permissions to other users, you need to transfer computers from the default Computers container to other OU.

You can move the computer object from the Computers container to another OU using the Active Directory Users & Computers graphical snap-in (dsa.msc).

  1. Expand the domain root and select the Computers container;
  2. Find the computer name you want to move, right-click on it and select Move; powershell move computer to ou
  3. Select the OU to which you want to move this computer. For example, we want to move it to USA > Florida > Computers and click Ok. move computer to ou powershell

Hint. You can move the computer between the OU with a simple drag & drop operations in ADUC, take the computer object with the mouse and drag it to the desired OU.

move ad computer powershell

You can also move computers between OUs using the PowerShell cmdlet Move-ADObject (it is a part of AD PowerShell module). Using this cmdlet, you can move an object or several objects (user, computer, security group) to another OU.

The –Identity parameter specifies the name of the object to be moved. You can specify the SID of the object, or the full LDAP path, but not the SamAccountName.

For example, to move the computer NY-PC-B32-23from Florida OU to the container California > Computers, run the command:

Move-ADObject –Identity “CN=ny-pc-b32-23,OU=Computers,OU=Florida,OU=USA,DC=theitbros,DC=com” -TargetPath "OU=Computers,OU=California,OU=USA,DC=theitbros,DC=com"

powershell move computer to another ou

If you specify instead of distinguishedName computer name (ldap) its name (SamAccountName), an error will appear: Move-ADObject : Cannot find an object with identity

move computer ou powershell

In order not to specify the full LDAP path to source object when moving the computer, you can use the Get-ADComputer cmdlet. This cmdlet allows you to find a computer object in the AD domain by its hostname.

Get-ADComputer “ny-pc-b32-23” |Move-ADObject -TargetPath "OU=Computers,OU= Florida,OU=USA,DC=theitbros,DC=com" -Verbose

powershell move computer ou

As you can see, the command syntax has become much simpler.

If you need to move several computers from the Computers container to other OUs, you can use the following PowerShell script to move bulk computer objects. In the grid table that opens, select the computers that you want to move, select destination OU and click OK. The selected computers will be moved to a new location.

$ADComps= Get-ADComputer -Filter * -SearchBase "Cn=computers,DC=test,dc=com"| Select-Object -Property Name |sort -Property name | Out-GridView -PassThru –title “Select Computers to Move”| Select -ExpandProperty Name

$ADOUs= Get-ADOrganizationalUnit -Filter * | Select-Object -Property DistinguishedName | Out-GridView -PassThru –title “Select Target OU”| Select-Object -ExpandProperty DistinguishedName

Foreach($ou in $ADOUs){

Foreach($comp in $ADComps){

get-adcomputer $comp |Move-ADObject -TargetPath "$ou" -Verbose }

}

 

move computer to different ou powershell

powershell to move computer to ou

The post PowerShell: Move Computer to OU appeared first on TheITBros.

“User Must Change Password at Next Logon” Option Not Working/Grayed Out

$
0
0
User Must Change Password at Next Logon

The option “User must change password at next logon” is usually enabled when creating a new Active Directory user, when the administrator resets the user’s password (when the user forgot his password or the password was compromised).

You can enable the option “User must change password at next logon” using the ADUC console (Active Directory Users and Computers)

  1. Launch the dsa.msc snap-in;
  2. Find the domain user and open its properties;
  3. Go to the Account tab and enable the option “User must change password at next logon” in the Account options section;
  4. Save the changes by clicking OK.

user must change password at next logon

This option is also enabled by default when you create a new AD user using the ADUC graphical wizard (New > User).

user must change password at next logon powershell

When resetting the user’s password, the domain’s account operator can also enable or disable the password reset option.

user must change password at next logon greyed out

You can also enable the option “User must change password at next logon” using PowerShell. To do this, use the Get-ADUser and Set-ADUser cmdlets from the AD PowerShell module. For the username, specify the value of the samAccountName attribute:

Import-Module ActiveDirectory

Get-ADUser –identity jsanti | Set-ADUser –ChangePasswordAtLogon $true

You can enable the ChangePasswordAtLogon attribute for all users in the specific OU:

Get-ADUser -Filter * -SearchBase "OU=Users,OU=California.OU=USA,DC=theitbros,DC=com"| Set-ADUser -ChangePasswordAtLogon:$True

When creating new users in AD using the PowerShell New-ADUser cmdlet, you can also enable this attribute (see the example in the article https://theitbros.com/import-users-into-active-directory-from-csv/)

If this option is enabled for the user account, then when the next time user logon to any domain computer or server after entering the password, a notification appears:

The user’s password must be changed before signing in

powershell set user must change password at next logon

The user must click OK, and in the next form specify a new password and confirmation.

change password at next logon

If the user refuses to change the password, he won’t be able to logon to domain computer with the old password until he changes it.

If you want to reset the AD user password, but in the Reset Password window the option “User must change password at next logon” grayed out, check the following:

change password at next logon powershell

  1. Make sure that the option “Password never expires” is not enabled in the user properties on the Account tab. If enabled, uncheck the option and click OK; active directory user must change password at next logon
  2. Make sure that your account has sufficient permissions to reset the password for this user. To do this, in the user properties in the ADUC console, go to the Security > Advanced > Effective Access tab. Click the Select a user button and specify the name of your account (to which the password reset permissions are delegated) and click the View effective access button.
  3. powershell ad user must change password at next logon
  4. Make sure that you have ResetPassword and Write userAccountControl (or Write Account Restrictions) permissions. powershell set change password at next logon

If your account does not have the above permissions to reset the password, you need to delegate these permission under an account with Domain Admin rights. Right-click on the OU where the user is located and select Delegate Control.

user must change password

In the Delegation of Control Wizard, specify the user or group to whom you want to delegate permissions and on the next step (Tasks to Delegate) select Reset user passwords and force password change at next logon. Click Next > Finish.

powershell set ad user must change password at next logon

If the permissions didn’t appear even after that, check that inheritance is enabled in the properties of the user to whom you want to enable the password change option. Open the user properties > Security > Advanced button > if the Enable inheritance button is available, click it and OK.

must change password at next logon

The post “User Must Change Password at Next Logon” Option Not Working/Grayed Out appeared first on TheITBros.


Configuring Domain Password Expiration Policy

$
0
0
password expiration

In the Active Directory domain, a password expiration policy can be configured that forces the user to change the password when his password expires.

What happens when a user password is expires in Active Directory? The user account is not blocked, user must change password at next logon: Your password has expired and must be changed.

password expiration

Until the user changes his password, he won’t be able to access domain resources and computers.

You can configure password expiration settings for domain users using Group Policy.

  1. Open the Group Policy Management Console (gpmc.msc);
  2. Right click on the Default Domain Policy and select Edit; password age
  3. Go to the GPO section: Computer Configuration > Windows Settings > Security Settings > Account Policies > Password Policy;
  4. The maximum password age in days is set in the “Maximum password age” parameter. If the user password older than this value, his password is considered expired;
  5. You can change max password age or set it to 0 (in this case, user passwords in the domain are never expired). maximum password age

You can get the user password expiration date with the command Get-ADUser from RSAT AD PowerShell module:

Get-ADUser –Identity username –Properties msDS-UserPasswordExpiryTimeComputed|Select-Object -Property Name, @{Name="ExpiryDate";Expression={[datetime]::FromFileTime($_.msDS-UserPasswordExpiryTimeComputed)}}

powershell password expiration

Prior to Windows Server 2008, you can configure only one domain password policy for all users. However, in modern versions of Windows Server, you can specify that passwords are not expired for a specific users or group using the Fine-Grained Password Policy. For example, you want to set the password never expires policy for the Domain Admins group.

  1. Run the Active Directory Administration Center console;
  2. Go to the System section, click on Password Settings Container and select New > Password Settings; windows 10 password expiration
  3. In the policy settings, specify its name and uncheck the option Enforce maximum password age;
  4. Then, in the Direct Applies To section, you need to add the group on which the policy should apply (in this example, Domain Admin group). windows 10 disable password expiration
  5. Save the policy.

You can disable the password expiration for a specific user if you set the “Password never expires” option in user properties in AD. You can enable this option through the ADUC console (find user > properties > Account tab > check the “Password never expires” option under the Account options section)

windows password expiration

Domain password expiration policy applies only to users, but not domain computers.

There is a separate policy for domain computers that allows you to configure how often a domain member needs to change the password. The policy is called Domain member: Maximum machine account password age and is located in the GPO section: Computer Configuration > Windows Settings > Security Settings > Local Policies > Security Options. The process of changing the computer password is fully automatically and performed by the NETLOGON service of computer by default once every 30 days. You can use this policyto increase or decrease this interval (from 1 to 999 days). If the password of the computer that is stored locally doesn’t match the password in the Active Directory database, you won’t be able to login to the computer as a domain user with an error The trust relationship between this workstation and the primary domain failed.

If you want to completely disable password changes for computer accounts, you need to enable the Domain member: Disable machine account password changes policy.

The post Configuring Domain Password Expiration Policy appeared first on TheITBros.

How to Reset Firewall Settings to Default in Windows 10?

$
0
0
windows 10 firewall default

One of the major changes in Windows XP Service Pack 2 was the introduction of a new security feature called Windows Firewall that manages the Internet connections on your computer and either allows or blocks access to different servers. If properly configured, Windows Firewall becomes an extremely powerful security guard that prevents hackers from accessing your computer and infecting it with malware or viruses.

When to Reset Windows Firewall?

By default, an average user does not need to manage Windows Firewall thus there is no need to reset Windows Firewall Settings to default. Still, many users like to take control of their privacy and security. They create new Windows Firewall rules and try to fine-tune their network connection to ensure the best security possible. That is totally fine and normal if you know what you are doing. If you went too far with managing Windows Firewall rules, things get really-really messy and cause the programs on your computer to lose access to the Internet and other weird connectivity issues. This leads to the need to reset Windows Firewall in Windows 10 and apply the default Firewall settings.

Luckily for all of us, it is quite easy to reset Windows Firewall or delete all Windows Firewall rules in Windows 10. You can quickly reset Windows Firewall using a command prompt, PowerShell, or Control Panel. In this article, we prepared a complete guide on how to reset Windows Firewall in Windows 10. Although in this article we talk about Windows 10 only (since it is the most popular and the most recent Windows), you can use our guide to delete Windows Firewall rules in Windows 8.1 or Windows 7.

Resetting Windows Firewall in Windows 10 – Backup the Rules Before You Go

Important: if you want to reset Windows Firewall settings, make sure you have the Administrator access level. If you do not, Windows would ask you to enter the Administrator password. Remember, you can’t delete Windows Firewall rules without an Administrator account.

Before you reset Windows Firewall in Windows 10, backup all the current rules just in case you ever need to restore them. Backing up Windows Firewall rules implies saving them to a separate file and keep in for later use.

You can quickly backup Firewall settings in Windows 10 using the special command. Launch Command Prompt in elevated mode (Run as Administrator) using the search or any preferred method and paste the following command:

netsh advfirewall export "C:Archivefirewall-config.wfw"

reset firewall windows 10

After you execute the command, Windows will put the backup file in the C:Archive folder. Copy the file from there and store it whenever it is convenient for you.

If you do not like using Command Prompt to manage Windows Firewall Settings, you can use the Windows Control Panel.

  1. Launch the Windows Security app using the search or the icon in the notification area. reset firewall windows 10 cmd
  2. Go to Firewall & network protection. Locate the Advanced settings link and click it. This launches the Windows Defender Firewall with Advanced Security window. netsh advfirewall reset windows 10
  3. What you need to backup Windows Firewall settings is in the right sidebar of the window. Click Export Policy and specify where to store your backup file. reset windows firewall to default command line

That is it. Your Windows Firewall settings are now securely stored in a separate file. Now you can proceed and reset Windows Firewall settings to default.

Reset Windows 10 Firewall – Control Panel

The easiest way to reset Windows 10 firewall rules to default is from Control Panel and Windows Firewall section. This guide also applies to Windows 7 and Windows 8.

  1. To open the snap, press Win + R and run the command firewall.cpl. reset firewall rules windows 10
  2. In the left sidebar, locate the Restore Defaults link and click it. windows 10 reset firewall rules
  3. In the new window click on the Restore Defaults button to confirm. reset windows 10 firewall
  4. Confirm deletion of settings by clicking Yes. windows 10 reset firewall

This action will reset all Windows Firewall settings, which were made after installing Windows, including rules and exceptions for all ports and programs. After that, in the list of firewall rules, you will find only the standard system network access rules remain. Now you can add new Windows Firewall rules and configure it up to your desire or just leave it blank.

How to Reset Windows Firewall in Windows 10 – Windows Security

There is another way to reset Firewall in Windows 10. It can save you a few clicks and help avoid navigating the old Control Panel. All you need to do is to launch the Windows Security app and go to the Firewall and network protection section.

windows 10 firewall reset

Hit Restore firewall to default and confirm your decision in the new window.

Resetting Windows Firewall Settings to Default Using Command Prompt or PowerShell

Just like with almost any Windows setting, you can reset Windows Firewall using a simple command in Command Prompt or Windows PowerShell.

In case you use Windows Command Prompt (do not forget to launch it with Administrator access), use the following command:

netsh advfirewall reset

windows 10 default firewall rules

If you prefer Windows PowerShell or Windows Terminal, use this command:

(New-Object -ComObject HNetCfg.FwPolicy2).RestoreLocalFirewallDefaults()

reset windows firewall powershell

How Do I Reset Windows Firewall in Windows 7?

This part of the guide is specific for Windows 7 or Windows 8 users but also applies to Windows 10.

Our guide is not complete if we do not mention all the ways to reset Windows Firewall settings. It is not the quickest nor easiest, but also does the job.

  1. Hit Win + R on your keyboard and enter the wf.msc command. windows 10 reset firewall to default
  2. In the right-side pane, click Restore Default Policy and confirm the restoration. reset windows 10 firewall rules to default

Done, now your Firewall settings are reset to default.

Keep in mind that after you reset your Windows Firewall settings some applications may stop working or ask you to grant the access again. You need either create a new rule for each program or allow Internet access next time you launch an app. Some programs may require complete reinstallation to properly configure firewall access.

The post How to Reset Firewall Settings to Default in Windows 10? appeared first on TheITBros.

How to Create a New Office 365 Account?

$
0
0
Create a New Office 365 User Account

To use Office 365 resources, you must create a user. You can create a new user via the Microsoft 365 admin center or using PowerShell.

Creating a New Office 365 Account via Admin Center

  1. Browse and login to the Azure admin center at https://admin.microsoft.com;
  2. Go to UsersActive users, and click Add a user;
    create new office 365 email account
  3. Fill in the fields: Name, Domain, Password settings. You can create a password manually or automatically generate it. It is advisable to enable the option Require this user to change their password when they first sign I;
    create a new office 365 account
  4. Next, you need to select the user’s location and assign a license to the user (this step can be skipped);
    create new user office 365
  5. Next, you need to assign roles to the user. If this is a non-admin user, only the User: no administrator access option should be left.
    create new office 365 user account

Using PowerShell to Create a New User in Office 365

You can also create an Office 365 user using PowerShell.

First you need to connect to your Office 365 tenant from the PowerShell console. You can use the AzureAD module or MSOnline.

In order to connect your Azure tenant you can use the Azure Active Directory PowerShell for Graph module.

Install AzureAD module on your computer:

Install-Module -Name AzureAD

Hint. For more info check our post.

Authenticate on your Azure tenant with your Office 365 admin account

Now you can create a password profile variable:

$PasswordProfile=New-Object -TypeName Microsoft.Open.AzureAD.Model.PasswordProfile

$PasswordProfile.Password="$tr0ngP@ss0rd"

To create new Office 365 user, the New-AzureADUser cmdlet is used:

New-AzureADUser -DisplayName "Brian Jackson" -GivenName "Brian" -SurName "Jackson" -UserPrincipalName b.jackson@theitbros.onmicrosoft.com -UsageLocation UK -MailNickName b.jackson -PasswordProfile $PasswordProfile -AccountEnabled $true

Also, you can use the Azure Active Directory Module for Windows PowerShell.

Install the MSOnline module:

Install-Module MSOnline

Save your Office 365 admin credentials:

$MSOCred = Get-Credential

office 365 add new user

Connect to your subscription with saved credentials

Connect-MsolService -Credential $MSOCred

Now you can use the New-MsolUser cmdlet to create a new user:

New-MsolUser -DisplayName "Brian Jackson" -FirstName Brian -LastName Jackson -UserPrincipalName b.jackson@theitbros.onmicrosoft.com -UsageLocation UK -LicenseAssignment theitbros:ENTERPRISEPACK

Hint. If you don’t want to assign an Office 365 license to user, you can skip the–LicenseAssignment option.

Also you can create user accounts in bulk. Create a plain CSV file that contains a list of user you want create to:

UserPrincipalName,FirstName,LastName,DisplayName,UsageLocation,AccountSkuId
b.jackson1@theitbros.onmicrosoft.com,Brian1,Jackson1,Brian Jackson1,UK,contoso:ENTERPRISEPACK

b.jackson2@theitbros.onmicrosoft.com,Brian2,Jackson2,Brian Jackson2,UK,contoso:ENTERPRISEPACK

Now you can import these CSV file and create all user account specified:

Import-Csv -Path "C:\PS\NewOffice365Accounts.csv" | foreach {New-MsolUser -DisplayName $_.DisplayName -FirstName $_.FirstName -LastName $_.LastName -UserPrincipalName $_.UserPrincipalName -UsageLocation $_.UsageLocation -LicenseAssignment $_.AccountSkuId}

You can use the Get-MsolUser cmdlet to view Office 365 user details.

Once you have created an Office 365 user, you can assign a license, create mailboxes, etc. In previous article, we showed how to manage Office 365 users with PowerShell.

The post How to Create a New Office 365 Account? appeared first on TheITBros.

The Basics of PowerShell DSC (Desired State Configuration)

$
0
0
PowerShell Desired State Configuration

Desired State Configuration (DSC) allows you to configure Windows and applications using a configuration file and PowerShell. As in other configuration management systems (for example, Puppet or Ansible), when using Desired State Configuration, the administrator can describe the required configuration (target state) in the configuration file, and then use PowerShell to apply it to one or several computers/servers. With PowerShell Desired State Configuration, you can greatly simplify the deployment and configuration of servers and workstations with configure your OSs as code.

DSC first appeared in PowerShell 4.0 (a version of the Windows Management Framework introduced in Windows Server 2012 R2).

As we said above, the administrator must first create a configuration file that describes the Windows state. You can use the built-in resources (file, environment, registry, script, service, user), or third-party DSC resources. In Windows 10 (Windows Server 2016), there are 23 types of built-in DSC resources. You can display them using the Get-DSCResource command:

  • File
  • SignatureValidation
  • Archive
  • Environment
  • Group
  • GroupSet
  • Log
  • Package
  • ProcessSet
  • Registry
  • Script
  • Service
  • ServiceSet
  • User
  • WaitForAll
  • WaitForAny
  • WaitForSome
  • WindowsFeature
  • WindowsFeatureSet
  • WindowsOptionalFeature
  • WindowsOptionalFeatureSet
  • WindowsPackageCab
  • WindowsProcess

powershell dsc

To demonstrate how DSC works, we will create a simple configuration file. Suppose our task is to configure the server as follows: disable the BranchCache service, start the notepad.exe process, allow RDP access in the registry (the parameter fDenyTSConnections is set to 0), and create the C:\PS directory on the local drive.

The Configuration keyword is used to create the DSC configuration file. Create the dsc_test.ps1 file with the following code:

Configuration TestConfiguration

{

Node dc01

{

#Disable BranchCache Service

Service PeerDistSvc {

Name = “PeerDistSvc”

StartupType = “Disabled”

State = “Stopped”

}

#Enable RDP

Registry fDenyTSConnections {

Ensure = “Present”

Key = “HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Terminal Server”

ValueName = “fDenyTSConnections”

ValueData = “0”

ValueType = “Dword”

}

#Create C:\PS folder

File InstallDir {

Ensure = “Present”

Type = “Directory”

DestinationPath = “C:\PS”

}

#Run Notepad.exe

WindowsProcess Notepad

{

Ensure = “Present”

Path = “C:\WINDOWS\system32\notepad.exe”

Arguments = “”

}

}

}

TestConfiguration

Hint. In one configuration file, you can describe the state of one or more hosts.

Run this PS1 script file. As a result, the dc01.mof file will appear in the current directory.

desired state configuration

Based on the configuration file for each node, a separate file is generated in the MOF file format (Management Object Format). You can manually view the contents of the MOF file:

powershell dsc examples

To apply the settings from the DSC configuration file to the server, you need to apply the settings from the MOF file.

There are two ways to apply MOF files.

  • Push – configuration files are transferred from the administrator’s workstation to remote computers via WinRM (Windows Remote Management). To do this, use the Start-DscConfiguration cmdlet;
  • Pull – managed computers connect to a file server (configuration file repository), download and apply settings on their own. Pull DSC configuration is based on a special IIS-based AppPool.

Consider applying the DSC configuration via push mode.

Tip. Before using the Push method, you need to configure the execution policy “Set-ExecutionPolicy RemoteSigned” and enable remote PowerShell using the “Enable-PSRemoting” command.

To do this, use the Start-DscConfiguration command with the -Path argument, which specifies the path to the directory containing the MOF files. Apply the previously created configuration file to the current computer:

Start-DscConfiguration -Path C:\Users\Administrator\TestConfiguration

Hint. For more detailed information on applying the configuration, use -Wait and –Verbose parameters.

powershell dsc tutorial

After executing this command, if the computer configuration met the requirements, nothing will change, and if not, the settings will be changed. Settings applied on a computer by the Local Configuration Manager Service. In our example, the directory C:\PS was created on the disk, the BranchCahe service stopped, and the notepad.exe process started on behalf of NT AUTHORITY\SYSTEM.

Settings made using the DSC may change over time. You can check for discrepancies between the current settings and the configuration file using the Test-DscConfiguration command. For example, we killed the notepad.exe processes and deleted the C:\PS directory. Run the command:

Test-DscConfiguration

The cmdlet returned False, which means the server state does not match the configuration.

dsc configuration

Using the Get-DscConfiguration command, you can get the value of the current DSC configuration settings.

windows powershell desired state configuration

To remove the current DSC configuration from the computer, run the command:

Remove-DscConfigurationDocument -Stage Current -Verbose

The post The Basics of PowerShell DSC (Desired State Configuration) appeared first on TheITBros.

How to Get List of Installed Programs in Windows 10?

$
0
0
list installed apps windows 10

In this simple guide, we will show you a few different ways of how to get a list of installed programs in Windows 10, 8, or Windows 7 using built-in command-line tools. When it may be necessary? For example, the list of all installed programs can be useful when you re-install Windows and want to make sure you do not miss all the necessary apps. Also, a list of all installed apps in Windows will come in handy when you perform an audit, or when you want to find the unwanted programs. You will also find useful a list of all installed programs if you accidentally deleted a shortcut or cannot find some specific app.

How to Get Windows 10 Installed Programs List – Apps Folder

The easiest way to get a complete list of applications with icons is to press the Win + R keys on your keyboard and then enter the following command:

shell:AppsFolder

list of installed programs windows 10

It is particularly important to enter this command without any spaces, otherwise, it won’t work.

how to find installed programs in windows 10

Do note that you can in the bottom-left corner you can find the total number of installed apps in Windows. For your information: this number includes all the default Windows utilities, such as Control Panel, Disk Cleanup, Cortana, etc. In case you want to know the number of installed apps in Windows 10, use the next method.

Although simple, this method has one critical downside: you cannot generate a list of installed apps in Windows 10 from here. This folder only shows all the shortcuts you can copy or use to launch any installed app.

Get a List of All Installed Apps in Windows using Windows Settings

If you are running Windows 10, there is a very convenient section inside Windows Settings. It collects all the installed apps and lets you quickly get a list of all your apps. To get there, hit Win + I on your keyboard and go to Apps Apps and features.

windows 10 list of installed programs

Here you can find the list of all installed apps, plus pre-installed from Microsoft Store. This list does not include default Windows Utilities. At the top of the list, you can find the apps counter.

What is also important is that this section allows you to filter the list and generate a list of all apps installed on a specific disk. For example, you want to find all the apps installed on a system drive. Just hit Filter by and select your system’s drive.

windows list installed programs command line

Again, this section cannot generate a file with a list of all installed apps on a computer.

Generate a List of All Installed Apps in Windows 10

Ok, now let us talk about how you can generate a list of all installed apps in Windows 10 (works in older Windows versions down to Windows XP) and export it to use later. We will cover the built-in utilities down this article, but in this section let us show you a wonderful tool called UninstallView. This utility is completely free and does not require installation. All you need to do is to download UninstallView from the official website and launch it.

For your information: by default, UninstallView shows only win32 apps which is more than enough for most users. You can toggle it to show apps from Microsoft Store, but it is not very friendly with this type of apps. For example, each DLC in Forza Horizon 4 shows as a separate app which is totally not ok to me. You can load Microsoft Store apps using Options Load Windows Apps menu.

wmic list installed software remote computer

Ok, launch the app and wait a few seconds for the app to generate the list. Now you can export and save it for later use.

  1. If you want to generate a list of all installed apps with all the details (version, path, registry key, and many others), skip the next step. If you want only the editable text file with a list of installed programs, do the following step.
  2. Press View Choose Columns. wmic installed software
  3. In a new window, select Deselect all and place a checkmark next to the Display name. This will leave only a list of apps names.
  4. Now, press Ctrl + A and then hit Save selected items. get-appxpackage select name packagefullname
  5. Name the text file and place it wherever you want, then open it. Now you have a complete list of all installed on a PC apps. You can edit it as any text file. windows 10 installed programs

How to Get a List of Installed Programs with Command Prompt and WMIC?

The list of installed programs on a PC can be obtained by using WMIC command line utility, that can access the WMI namespace. Run the elevated Command Prompt (use search and then run the app as Administrator) and execute the following command:

wmic product get name,version

windows 10 get list of installed programs

After a short wait, you will see a table with a list of names and versions of programs installed on your system.

windows 10 installed programs list

To export this list into a text file, run following command:

wmic product get name,version /format:csv > C:\InstalledApps_%Computername%.csv

This command generates a CSV file with your computer name in the title. After command execution, open the drive C. In there, you will find a csv file with your apps. In addition to the app’s names and versions, this list has the current computer name (it may be useful for further analysis or when you need to generate lists from a few computers). Open this file using any text editor or Excel.

How to Get a List of Installed Programs in Windows 10 using PowerShell?

Now, let us show you how to get a list of installed apps using PowerShell. PowerShell gets this list by scanning a special registry key HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall. The Control Panel uses the same registry to generate the list of installed apps, although you cannot export this list. Do note that this registry key contains only programs installed “for all users”.

For your information: For 32-bit application on a 64-bit operating system, you need to get the content of branch HKEY_LOCAL_MACHINE\SOFTWARE\Wow6432Node\Microsoft\Windows\CurrentVersion\Uninstall

If an application was installed for the current user, then you can locate it using the following registry key:

HKCU\Software\Microsoft\Windows\CurrentVersion\Uninstall

Obviously, running all three separate commands is not convenient, so let us show you how to run them all simultaneously, so you get the list of all apps installed on a PC.

  1. Press Win + X on your keyboard and launch the PowerShell (Admin).
  2. Copy and paste to the PowerShell’s window the following command:
    Get-ItemProperty HKLM:\Software\Wow6432Node\Microsoft\Windows\CurrentVersion\Uninstall* | Select-Object DisplayName, DisplayVersion, Publisher, Size, InstallDate | Format-Table -AutoSize

As you can see, the resulting list contains the program name, version, publisher, and installation date.

powershell list installed software

Now all is left is to export the list of programs you have just generated to the text file. We will use the command to generate a file on a C: drive but you can specify any other preferable path. Here is the command:

Get-ItemProperty HKLM:\Software\Wow6432Node\Microsoft\Windows\CurrentVersion\Uninstall* | Select-Object DisplayName, DisplayVersion, Publisher, InstallDate | Format-Table -AutoSize > C:\List-installed-programs.txt

For your information: The method above generates only a list of win32 apps, also known as classic desktop Windows programs. If you need to go generate a list of all apps installed from Microsoft Store, use the following command:

Get-AppxPackage | Select Name, PackageFullName |Format-Table -AutoSize > c:\docs\list-store-apps.txt

This method is not very convenient since it extracts the app’s folder name which is not always the same as the app’s name. We do not recommend using it at all.

get list of installed programs powershell

To get a similar list of programs from a remote computer, run this command:

Invoke-command -computer remote_pc_name {Get-ItemProperty HKLM:\Software\Wow6432Node\Microsoft\Windows\CurrentVersion\Uninstall* | Select-Object DisplayName, DisplayVersion, Publisher, InstallDate | Format-Table -AutoSize }

With PowerShell, you can compare the list of installed programs on two different computers and determine which apps are missing. Just take two software text files and add their names to this command:

Compare-Object -ReferenceObject (Get-Content PATH) -DifferenceObject (Get-Content PATH)

Instead of PATH use a complete file path. For example, C:\Docs\file.txt.

As a result, you will see the difference in the two application lists. In the example depicted on the screenshot, you can see that different versions of Firefox are installed on the computers. The symbol => means that this program is only available on the right computer. The <= symbol indicates that this program is installed only on the left computer.

powershell get list of installed programs

Another way to get a list of installed programs in Windows 10 is to use the Get-WmiObject command. Simply copy and paste the following command:

Get-WmiObject -Class Win32_Product | Select-Object -Property Name

powershell get installed programs

Get the List of Installed Software on Remote Computers Using PowerShell

System administrators often need to check whether a certain program and/or version is installed on network computers. For example, you can check if an important Windows update is installed or if all workstations have the correct version of MS Office.

Usually, for the remote inventory of remote computers we use the following PowerShell script (if this account doesn’t have permissions to connect remotely to a computer, the script will ask you to enter the credentials):

Function Get-InstalledApps

{

[CmdletBinding()]

param (

[Switch]$Credential,

[parameter(ValueFromPipeline=$true)]

[String[]]$ComputerName = $env:COMPUTERNAME

)

begin {$key = "SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall"}

process

{

$ComputerName | Foreach {

$Comp = $_

if (!$Credential)

{

$reg=[microsoft.win32.registrykey]::OpenRemoteBaseKey('Localmachine',$Comp)

$regkey=$reg.OpenSubKey([regex]::Escape($key))

$SubKeys=$regkey.GetSubKeyNames()

Foreach ($i in $SubKeys)

{

$NewSubKey=[regex]::Escape($key)+"\\\"+$i

$ReadUninstall=$reg.OpenSubKey($NewSubKey)

$DisplayName=$ReadUninstall.GetValue("DisplayName")

$Date=$ReadUninstall.GetValue("InstallDate")

$Publ=$ReadUninstall.GetValue("Publisher")

New-Object PsObject -Property @{"Name"=$DisplayName;"Date"=$Date;"Publisher"=$Publ;"Computer"=$Comp} | Where {$_.Name}

}

}

else

{

$Cred = Get-Credential

$connect = New-Object System.Management.ConnectionOptions

$connect.UserName = $Cred.GetNetworkCredential().UserName

$connect.Password = $Cred.GetNetworkCredential().Password

$scope = New-Object System.Management.ManagementScope("\\\$Comp\root\default", $connect)

$path = New-Object System.Management.ManagementPath("StdRegProv")

$reg = New-Object System.Management.ManagementClass($scope,$path,$null)

$inputParams = $reg.GetMethodParameters("EnumKey")

$inputParams.sSubKeyName = $key

$outputParams = $reg.InvokeMethod("EnumKey", $inputParams, $null)

foreach ($i in $outputParams.sNames)

{

$inputParams = $reg.GetMethodParameters("GetStringValue")

$inputParams.sSubKeyName = $key + $i

$temp = "DisplayName","InstallDate","Publisher" | Foreach {

$inputParams.sValueName = $_

$outputParams = $reg.InvokeMethod("GetStringValue", $inputParams, $null)

$outputParams.sValue

}

New-Object PsObject -Property @{"Name"=$temp[0];"Date"=$temp[1];"Publisher"=$temp[2];"Computer"=$Comp} | Where {$_.Name}

}

}

}

}

}

To generate a list of installed programs on the current computer, run the command: Get-InstalledApps. To get lists of installed software from several remote computers, run this command: Get-InstalledApps PCName1,PCName2,PCName3,PCName4.

That is all! Hope this article will be helpful!

The post How to Get List of Installed Programs in Windows 10? appeared first on TheITBros.

Viewing all 91 articles
Browse latest View live