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

How to transfer FSMO Roles From a Failed Domain Controller

$
0
0
FSMO Roles

In case domain controller, which owns FSMO (Flexible Single Master Operation) roles, is fail (virus attack, fatal software problems or catastrophic hardware failure etc.), then you need to transfer FSMO roles from a failed to an another (additional) domain controller (for proper Active Directory domain functioning). Consider this tutorial on how to do it.

Transferring FSMO Roles From a Failed Domain Controller

Suppose, in our Active Directory domain there are 2 domain controllers, that is running Windows Server 2012 R2:

  • PDC – dc1.root.contoso.com
  • Secondary DC – dc2.root.contoso.com

After the failure of the DC1, we need to seize the FSMO roles from DC1 to a secondary domain controller. Then, on DC2, we need to delete all references to the old controller dc1.root.contoso.com.

Important! Before you begin, make sure your account is a member of a following AD groups: Domain Admins and Schema Admins.

Connect to a DC2 and run elevated command prompt (it is recommended to perform all actions on the domain controller, to which you want to transfer FSMO roles). Make sure that this domain has two domain controllers:

dsquery server -forest

dsquery server forest

Then check which domain controller is the owner of FSMO roles:

netdom query fsmo

You can see that the owner of all FSMO roles is dc1.root.contoso.com

netdom query fsmo

Transferring roles is performed by using the console utility NTDSUTIL (ADDS service and management tool).

Before you transfer the FSMO roles on the additional domain controller, you must register the Active Directory schema management library. In case you dont, then you wont be able to transfer role Schema master. In the Command prompt, run:

regsvr32 schmmgmt.dll

DllRegisterServer

You are now ready to seize the roles from a failed DC1. Run the command prompt as an Administrator and run the following command:

ntdsutil

Enter the role management and connect to the server (DC2), which will seize the roles:

roles

connections

connect to server DC2

q

ntdsutil

After connecting to the server DC2, seize all 5 FSMO roles:

seize naming master

seize infrastructure master

seize rid master

seize schema master

seize pdc

q

In the process of the transfer of each role, you will be prompted for confirmation.

CN_NTDS

Role Seizure Confirmation Dialog

Are you want server dc2 to seize the domain naming role with the value below?

Enter the clearing of meta-data mode and connect to the server (DC2):

metadata cleanup

connections

connect to server DC2

q

List the existing Active Directory sites:

select operation target

list sites

metadata cleanup

In this domain, only one site with the name Boulder. Choose a site, which is located on the failed domain controller DC1, and display a list of domain controllers in the site:

select site 0

list servers in site

list sites

Select the failed controller (DC1) and display the list of domains:

select server 0

list domains

Select the domain and return to the metadata cleanup menu:

select domain 0 q

Perform delete of the selected server (DC1):

remove selected server

In the dialog box «Are you sure you want to remove the server object … » confirm the removal of a domain controller.

remove CN NTDS

Now we need to clean up the AD from the remaining entries on deleted DC1.

Open the snap-in Administrative Tools -> Active Directory Sites and Services. Expand the site, where the deleted DC1 located, select it and choose Delete. Confirm the removal of a DC1 twice.

DNS settings active directory

Then, open the DNS snap-in and remove the PTR and A records remaining from DC1 server.

Now, open the Active Directory Users and Computers snap-in and expand Domain Controllers OU. If there is only displayed DC2, then everything is fine. And if DC1 present in this catalog, then it must be removed from the directory (it is unlikely, but check it).

domain controllers active directory

So, we took the force FSMO roles from DC1 and faulty completely removed the traces of its existence from the DNS and Active Directory. DC2 became the primary domain controller (the owner of all FSMO roles).

Once you have completed the seize of the FSMO roles, you need to close the Command prompt, and wait for the changes to replicate throughout the forest. Now transfer FSMO Roles From a Failed Domain Controller is completed.

The post How to transfer FSMO Roles From a Failed Domain Controller appeared first on TheITBros.


How to Backup Drivers and Restore them in Windows 10

$
0
0
backup drivers

A backup copy of the drivers will not only help to restore the operability of the hardware and the peripheral devices (printers, scanners, MFPs, etc.) of the computer quickly, but also prevent any possible problems (for example, with sound or graphics due to an incorrectly installed driver after clean reinstall or reset Windows 10 to its original state).

Note. There are many free applications for creating backup copies of drivers. But in this article we will describe a method that allows you to backup drivers without third-party tools, just using built-in Windows 10 tools.

Windows 10 allows you to extract all third-party (not Microsoft) drivers installed in the system from the Driver Store and save them to the specified location.

Backup drivers using DISM.exe

To create a backup of the installed drivers in Wndows 10, you can use the console utility DISM.exe (Deployment Image Servicing and Management).

  1. Run cmd.exe with Administrator privileges.
  2. Create a directory where you want to place the drivers:
    md C:\BackupDrivers
  3. Enter the command dism /online /export-driver /destination:C:\BackupDrivers and press Enter.
    backup drivers cmd
    Note. In our case, only 3 drivers were saved, since we exported the drivers on the virtual machine with Windows 10. In the case of a real system, there will be much more drivers.
  1. Each driver is exported in a separate folder in which not only *.inf files are placed, but also all related files (*.sys, *.dll, *.exe etc).
    backup drivers folder

It remains to copy this directory to DVD, external USB drive, network share or cloud storage. Now you have all the necessary drivers to re-install the system.

Export Drivers using PowerShell

You can also back up the drivers installed on Windows 10 by using the PowerShell cmdlet Export-WindowsDriver.

Note. The Export-WindowsDriver cmdlet is included in the PowerShell from Windows 8.1 Update 1. Export-WindowsDriver can get drivers from both the running system and the offline Windows image.

To do this, run the PowerShell console and execute the command:

Export-WindowsDriver -Online -Destination C:\BackupDriversPS

export windows drivers

As you can see, the result is the same a set of folders with drivers appeared in the destination directory.

Restoring Windows 10 drivers from a backup

In order to install the drivers saved in this way, for example, after a clean installation of Windows 10 or reinstall it:

  1. Open the Device Manager console (Devmgmt.msc).
  2. Right click on the device for which you want to install the driver and select Update Driver Software.
    backup drivers device managert
  3. Select Browse my computer for driver software and specify a path to the directory where the backup copy of the drivers is stored.
    backup drivers browse
  4. Make sure that the option Include subfolders is selected. Now press Next and install the required driver from the list.

In addition, you can import all drivers from the backup folder using the /Add-Driver parameter of the DISM utility.

dism /online /Add-Driver /Driver:C:\BackupDriversPS /Recurse

The post How to Backup Drivers and Restore them in Windows 10 appeared first on TheITBros.

GPT or MBR: How to Check HDD Partition Table Style

$
0
0
Check HDD Partition Table Style

The modern versions of Windows and other operating systems can use one of two standards to store information about hard disk partitions structures. This is an old standard MBR (Master Boot Record) and a new one GPT (GUID Partition Table). In the Windows OS family, the topic of the GPT and MBR disk partition tables became relevant after the distribution of computers and laptops with pre-installed Windows 10/Windows 8. In this guide, we will show you a several simple ways on how to determine which Partition Table Style (GPT or MBR) has your disk (this can be a standard HDD or an SSD drive) using Windows built-in tools.

Note. GPT replaced the MBR (uses BIOS) as a new standard for placing tables on a physical disk. In turn, GPT uses UEFI (Unified Extensible Firmware Interface), which replaced the BIOS. Unlike MBR, which is located at the beginning of the disk (it is a  boot sector), GPT is a partition table on the disk (GUID table) and assigns a unique global identifier to the each partition. In Microsoft Windows, the partition table reserves 128 entries, which allows you to create up to 128 partitions. The important difference between the GPT partition table and the MBR is the ability to create a partition larger than 2 TB on the disk.

In order to determine which partition table is used by your disk (GPT or MBR), there are three useful, simple and accessible tools: Disk Management snap-in, command-line utility Diskpart and PowerShell.

How to view partition table style using Disk Management

  1. To open the Disk Management console, press the Win + R keys, type diskmgmt.msc and press Enter.
  2. The opened Disk Management window contains a list of all HDDs, SSD disks and USB-drives that connected to the computer.
  3. Right-click the drive which markup you want to know and select its Properties.
    disk management convert
  4. Switch to the Volumes tab.
  5. If this disk uses the GPT, the Partition Style item specifies the GUID Partition Table (GPT). For MBR drive Master Boot Record (MBR).
    mbr gpt

Get the partition style using DiskPart

To get the partition table type for each of the disks that are available in the system, run a Command Prompt with Administrator privileges and execute the following commands one by one:

diskpart

list disk

exit

disk part command prompt

Note the last column in the results of the command list disk. If there is a mark (asterisk), then this disk has the GPT partition style, those disks that do not have such marks MBR (usually MBR, because there may be other options, for example, the system can’t determine the disk type).

How to recognize the partitioning style on a disk using PowerShell

You can get the partition table style using Windows PowerShell. Run PowerShell console as Administrator and execute the following cmdlet:

Get-Disk

powershell partition style

For convenience, you can use this command:

Get-Disk | select Number, FriendlyName, PartitionStyle

get disk partition style

In the results of the command, pay attention to the last column named PartitionStyle in which you will see the partitioning style for each disk connected in the system. In our case, Disk 0 has a GPT partition style, and Disk 1 is an MBR disk.

The post GPT or MBR: How to Check HDD Partition Table Style appeared first on TheITBros.

How to transfer FSMO Roles using PowerShell

$
0
0
windows powershell

When you create a domain, all FSMO roles assigned to the first domain controller in the forest by default. You can transfer FSMO roles from one DC to another both the Active Directory graphics snap-ins and the PowerShell command line. Moving FSMO roles using AD PowerShell has the following benefits:

  • You do not need to connect with a MMC snap-ins to the future role owner;
  • Transferring or seizing FSMO roles does not require a connection to the current or future role owner. You can run AD-PowerShell module cmdlets on a Windows 7 client or on a member server running Windows Server (with the RSAT package installed);
  • To seize the FSMO role (if the current owner is not available), it suffices to use an additional parameter -force.

To get the current forest level FSMO role owners (Domain Naming Master and Schema Master roles) you can use the following PowerShell command:

Get-ADForest contoso.com| ft DomainNamingMaster, SchemaMaster

To view domain-wide FSMO roles (Infrastructure Master, PDC Emulator and Relative Identifier Master roles):

Get-ADDomain contoso.com | ft InfrastructureMaster, PDCEmulator, RIDMaster

get ad forest fsmo roles

Transfer FSMO Roles using PowerShell

To transfer FSMO roles between Active Directory domain controllers use the PowerShell cmdlet Move-ADDirectoryServerOperationMasterRole.

To use the Move-ADDirectoryServerOperationMasterRole cmdlet, you must meet the following requirements:

  • There must be at least one domain controller with a version of Windows Server 2008 R2 or higher;
  • Installed PowerShell 3.0 or newer;
  • Imported Active Directory module (2.0  or newer).

First of all, you need to load the Active Directory PowerShell module:

Import-Module ActiveDirectory

Tip. In Windows Server 2012 or later, the Active Directory module for PowerShell is loaded by default.

Unlike the Ntdsutil.exe utility, the Move-ADDirectoryServerOperationMasteRole cmdlet can be performed from any domain computer to migrate the Operations Master roles if you have the appropriate rights (Domain admins and Enterprise Admins).

For example, to transfer the PDC Emulator role to a domain controller named dc2, use the command:

Move-ADDirectoryServerOperationMasterRole -Identity "dc2" PDCEmulator

It is possible to transfer several roles at once:

Move-ADDirectoryServerOperationMasterRole -Identity “dc2” –OperationMasterRole DomainNamingMaster,PDCEmulator,RIDMaster,SchemaMaster,InfrastructureMaster

Tip. To simplify the command, you can replace the names of roles with numbers from 0 to 4. The correspondence of names and numbers is given in the table:

PDCEmulator 0
RIDMaster 1
InfrastructureMaster 2
SchemaMaster 3
DomainNamingMaster 4

Thus, the last command can be replaced by a shorter one:

Move-ADDirectoryServerOperationMasterRole “dc2” –OperationMasterRole 0,1,2,3,4

transfer fsmo roles

After entering the transfer command for all or several roles, a window appears asking whether you want to confirm your actions or cancel them.

In the event that the current owner of one or all of the FSMO roles fails, the forced transfer of FSMO roles is performed by the same command, but with the -Force option:

Move-ADDirectoryServerOperationMasterRole -Identity “dc2” –OperationMasterRole DomainNamingMaster,PDCEmulator,RIDMaster,SchemaMaster,InfrastructureMaster –Force

Important. After the FSMO roles has been seized, the domain controller from which the roles was seized should never be connected to the domain.

As you can see, to transfer FSMO roles using PowerShell just follow the steps above! It is quite simple.

The post How to transfer FSMO Roles using PowerShell appeared first on TheITBros.

Understanding Global Catalog (Active Directory)

$
0
0
active directory

In addition to the 5 FSMO roles in Active Directory, there is the sixth (unofficial) domain controller role Global catalog (GC). Unlike FSMO roles, any controller in a domain can have a Global Catalog role, i.e. it doesn’t require the uniqueness of a server within an Active directory domain or forest. However, the Global Catalog is the most important DC role from the practical point of view.

A Global Catalog server is a domain controller that stores copies of all Active Directory objects in the forest. It stores a complete copy of all objects in the directory of your domain and a partial copy of all objects of all other forest domains. Thus, the Global Catalog allows users and applications to find objects in any domain of the current forest by searching for attributes included to GC.

The Global Catalog contains a basic (but incomplete) set of attributes for each forest object in each domain (Partial Attribute Set, PAT). The GC receives data from all the domain directory partitions in the forest, they are copied using the standard AD replication service. Whether the attribute is copied to the Global Catalog is determined by the schema. If necessary, you can configure additional attributes that will be replicated to the GC using the Active Directory Schema snap-in. To add an attribute to the GC, you must select the option Replicate This Attribute To The Global catalog. As a result, the value of the isMemberOfPartialAttributeSet attribute parameter is set to true.

active directory account name properties

To find the list of DC’s that contains the Global Catalog in the current forest, run the command in the PowerShell console:

Get-ADForest |select -ExpandProperty GlobalCatalogs |Format-Table

expand global catalog active directory

Or this command:

dsquery server -forest –isgc

The first GC server was automatically created on the first domain controller in the forest when you were installing Active Directory Domain Services. In the case of a single site, even if it contains multiple domains, a single Global Catalog server is usually sufficient to process Active Directory requests. In a multi-site environment (in order to optimize network performance) consider adding GC servers to ensure a quick response to search queries and fast logon. Also, at least one GC server must be present on each AD site where Exchange is supposed to be installed.

You can assign additional domain controllers as GC by selecting the Global Catalog option in the Active Directory Sites And Services snap-in.

global catalog active directory

The global catalog server is used for the following purposes:

  • Object search if a user searches for an object by specifying All directory parameter in the query, this request is redirected to port 3268 and sent to the GC server. If, for any reason, there is no GC server in the domain, users and applications will not be able to perform searches in the forest;
  • Authentication the GC server is the source of authentication at the time the user logs on to the domain. The global catalog server resolves the user name if the authenticating domain controller does not have information about user’s account;
  • Verifying membership in universal groups in a multi-domain environment in the verification process, the domain controller verifies the authenticity of the user, after which the user receives authorization data to access the resources. To provide this information, the domain controller retrieves the security identifiers (SIDs) for all security groups that the user is a member of and adds these identifiers to the user’s access token. Because universal groups can contain user and group accounts from any domain in the forest, group membership in them can only be resolved by the GC Server that has catalog information at the forest level;
  • Checking references to objects within the forest Domain controllers use a Global Catalog to validate references to objects in other domains in the forest. That’s why if the domain controller contains an object with an attribute, that contains a reference to an object in another domain the domain controller checks the link by establishing a connection to the Global Catalog server;
  • Exchange Address Book Search when users in their Outlook clients want to find a person within their organization, they usually search through the global address list (GAL). The GAL is a list, that Exchange creates as a result of an LDAP query to search for all mail-enabled objects users, contacts, and groups. When a user tries to open an address book in Microsoft Outlook, or writes a message and enters a name or address in the To field, Outlook uses the GC Server specified by the Exchange server. To search for Global Catalog servers, Exchange mail servers use Active Directory and DNS.

For resiliency purposes it is important to keep at least a few domain controllers with the Global Catalog role. It will be better if each domain has a minimum of one GC. However, it is better to have a Global Catalog on every DC in the forest. This will also have a positive effect on load balancing, it is important to notice that from now on you will not have to worry about the infrastructure master FSMO role (for more details read this article).

If you can’t make all DCs the Global Catalog, then take care that the infrastructure master FSMO role does not reside on the GC Server, otherwise it will stop its functioning (phantom records will not be created/changed) and as a consequence you will get irrelevant data in AD.

If there is no Global Catalog server, users can not log in, and the Exchange mail server can’t send and receive mail. That’s why the Global Catalog is the most important role of the domain controller, without GC role the functioning of Active Directory is almost impossible.

The post Understanding Global Catalog (Active Directory) appeared first on TheITBros.

Guide to SQL Server Transaction Log Backup

$
0
0
backup transaction log

In case you use Microsoft SQL Server you might heard about the Simple and Full database recovery models. Probably you also know that a Simple recovery model l allows you to restore data only at the time of the backup, while Full  at any time (you only need to make regular backups of the transaction log). To restore data with the Full recovery model you will need to apply transaction log backups in a specific sequence. This can be done easily using SQL Server Management Studio (SSMS), but only on the SQL Server where the backups were created.

On a productive SQL server, transaction logs is needed to be backed up regularly to avoid overflowing the transaction log file and automatic growth operations. To get a report about the size of the transaction log (in MB) and in percentage terms with the size of the database itself, execute the T-SQL command:

DBCC SQLPERF(LOGSPACE);

GO

logspace

The account that is used to start the backup process must have BACKUP DATABASE and BACKUP LOG permissions. To do this, it is enough to add user to the sysadmin role or in one of the predefined database roles db_owner or db_backupoperator.

There are several ways to create a backup of the transaction log in SQL Server 2016 using SSMS, T-SQL or SQL Server PowerShell.

Backup a Transaction Log Using SQL Server Management Studio

  1. Run SQL Server Management Studio and connect to the desired SQL Server instance;
    sql server connect
  2. In Object Explorer window select your database, right click on the database name and select Tasks -> Backup;
    sql server object explorer back up
  3. Make sure that the database model recovery mode Full or Bulk_Logged is used;
    Tip. Simple recovery model does not support transaction log backups
  4. In the Backup type drop-down list select Transaction Log;
    sql server transaction log
  5. If necessary, create a new backup destination such as Disk, URL or Tape. In our example, a new file was created on a separate drive E:
    sql server destination back up log
  6. To create a backup, click OK;
  7. A message should appear “The backup of database DBNAME complete successfully”.
    log database backup

Backup a Transaction Log Using T-SQL

To create a backup of the DB transaction log using T-SQL, create a new Backup Device named DB1device.
sql server backup devices

To create a backup of the transaction log of the DWConfiguration database on the device DB1device, execute the following command:

BACKUP LOG DWConfiguration

TO DB1backup;

GO

sql server DWConfiguration

Or backup transaction log to one disk file:

BACKUP LOG DWConfiguration TO DISK = 'e:\backup\DWConfiguration.TRN';

GO

Backup Transaction Log Using PowerShell

Another way to create a backup of the transaction log is to use the SQL Server PowerShell cmdlet Backup-SqlDatabase.

Backup-SqlDatabase -ServerInstance SQL2016SP1HOL\MSSQLSERVER -Database DWConfiguration -BackupAction Log

After that, the transaction logs are cleared, and the released space can be overwritten with new transactions.

The post Guide to SQL Server Transaction Log Backup appeared first on TheITBros.

Accessing Hyper-V Virtual Machine Console Using RDCMan

$
0
0
rdcman hyperv

Remote Desktop Connection Manager (RDCMan) is an official utility from Microsoft to connect to servers via RDP (which replaced the Remote Desktops snap-in) and efficiently handle the daily management tasks by System Administrator. The version of RDCMan 2.7 has interesting feature it can be used to connect directly to the Hyper-V virtual machine console using VMConnect. The connection is made through Enhanced Session Mode, which uses the VMBus (a logical inter-partition communication channel between the Hyper-V host and the virtual machines).

To connect to a virtual machine, the first thing to do is to get its VM ID. You can get it using PowerShell, for example:

Get-VM -Name lon-dc01 | select ID

get vm rdcman

After you’ve got the virtual machine ID, open RDCMan and add a new server. Check item VM console connect. Then specify the name of the Hyper-V server on which the VM resides in the Server name field. In the id field specify its identifier obtained in the previous step and save the settings.

add server hyper v

To connect to the VM, you need to specify a user account with Hyper-V Administrator privileges.

Note. Even if your account is included in the local group Administrators, add it also to the Hyper-V Administrators group.

rdcman hyper v

Now you can connect to the virtual machine console on the hypervisor Hyper-V as to normal server. The advantage of connecting to the console is that the VM can be in the internal isolated private network, the access via RDP may be disabled, it may does not have a network adapter at all you are still able to connect to it.

Tip. On Hyper-V server TCP port 2179 must be opened.

boot vm rdcman

If you want to provide the ability to connect to a particular VM’s console to a regular user (not an Administrator), you must grant the appropriate permissions.

Grant-VMConnectAccess -ComputerName hv-srv-01 -VMName lon-srv-01 -UserName contoso\jpatrick

In case you are facing with “Unknown disconnection reason 3848” error when connecting, you need to configure a number of registry settings. The problem is that the CredSSS (Credential Security Service Provider) policy on Hyper-V host doesn’t allow to authenticate remote users by default.

rdcman hyper v disconnect

Start the PowerShell console with administrative privileges and run the following commands:

New-ItemProperty -Path HKLM:\SYSTEM\CurrentControlSet\Control\Lsa\Credssp\PolicyDefaults\AllowDefaultCredentialsDomain -Name Hyper-V -PropertyType String -Value "Microsoft Virtual Console Service/*" -Force
New-ItemProperty -Path HKLM:\SYSTEM\CurrentControlSet\Control\Lsa\Credssp\PolicyDefaults\AllowSavedCredentialsDomain -Name Hyper-V -PropertyType String -Value "Microsoft Virtual Console Service/*" -Force
New-ItemProperty -Path HKLM:\SYSTEM\CurrentControlSet\Control\Lsa\Credssp\PolicyDefaults\AllowDefaultCredentials -Name Hyper-V -PropertyType String -Value "Microsoft Virtual Console Service/*" -Force
New-ItemProperty -Path HKLM:\SYSTEM\CurrentControlSet\Control\Lsa\Credssp\PolicyDefaults\AllowFreshCredentialsDomain -Name Hyper-V -PropertyType String -Value "Microsoft Virtual Console Service/*" -Force
New-ItemProperty -Path HKLM:\SYSTEM\CurrentControlSet\Control\Lsa\Credssp\PolicyDefaults\AllowFreshCredentials -Name Hyper-V -PropertyType String -Value "Microsoft Virtual Console Service/*" -Force
New-ItemProperty -Path HKLM:\SYSTEM\CurrentControlSet\Control\Lsa\Credssp\PolicyDefaults\AllowFreshCredentialsWhenNTLMOnly -Name Hyper-V -PropertyType String -Value "Microsoft Virtual Console Service/*" -Force
New-ItemProperty -Path HKLM:\SYSTEM\CurrentControlSet\Control\Lsa\Credssp\PolicyDefaults\AllowFreshCredentialsWhenNTLMOnlyDomain -Name Hyper-V -PropertyType String -Value "Microsoft Virtual Console Service/*" -Force
New-ItemProperty -Path HKLM:\SYSTEM\CurrentControlSet\Control\Lsa\Credssp\PolicyDefaults\AllowSavedCredentials -Name Hyper-V -PropertyType String -Value "Microsoft Virtual Console Service/*" -Force
New-ItemProperty -Path HKLM:\SYSTEM\CurrentControlSet\Control\Lsa\Credssp\PolicyDefaults\AllowSavedCredentialsWhenNTLMOnly -Name Hyper-V -PropertyType String -Value "Microsoft Virtual Console Service/*" -Force

Now try to connect again. It should work!

So, using RDCMan you can remotely connect to any virtual machine console running on the Hyper-V host, regardless of the guest OS (whether it’s Window, Linux, MacOs, or anything else).

The post Accessing Hyper-V Virtual Machine Console Using RDCMan appeared first on TheITBros.

Move FSMO Roles and Upgrade Domain to Windows Server 2016

$
0
0
fsmo roles

In this article we will show you how to promote a new domain controller with Windows Server 2016 in the Active Directory domain, move FSMO roles from an old domain controller (running Windows Server 2012 R2/2008), raise the domain functional level to Windows Server 2016 and then demote the DC from Windows Server 2012/2008 to the domain member server.

We assume that you already have a new server running Windows Server 2016. Our task is to install the Active Directory Domain Services role on it. In our lab, we have an installed domain contoso.com with one PDC domain controller on Windows Server 2012 R2. We will add the second domain controller with Windows Server 2016 and transfer all the FSMO roles to it.

How to move FSMO Roles from old DC?

To install a domain controller and transfer FSMO roles, your account must be in the Domain Admins and Enterprise Admins groups. You can install the ADDS role from the Server Manager console GUI (screenshot below), but it’s much more convenient and easier to install a AD role from the PowerShell console.

active directory domain services roles

On a new server run elevated PowerShell command line. Import the ServerManager module to the PowerShell session and install the ADDS services and the management tools.

Import-Module ServerManager

Install-WindowsFeature -name AD-Domain-Services –IncludeManagementTools

Wait until the ADDS role and management tools have been installed. A server reboot is not required.

import module powershell

To promote this server to a domain controller, run the following command (replace the domain, first DC and site names to your own!):

Install-ADDSDomainController `

-NoGlobalCatalog:$false `

-CreateDnsDelegation:$false `

-CriticalReplicationOnly:$false `

-DatabasePath "C:\Windows\NTDS" `

-DomainName "contoso.com" `

-InstallDns:$true `

-LogPath "C:\Windows\NTDS" `

-NoRebootOnCompletion:$false `

-ReplicationSourceDC "dc.contoso.com" `

-SiteName "NewYork" `

-SysvolPath "C:\Windows\SYSVOL" `

-Force:$true

install adds domain controller

You must specify the local DSRM password and confirm it. After the role is configured, the server will automatically reboot.

move fsmo roles powershell

Now you can transfer all (or only a part of) FSMO roles to the new DC.

You can transfer FSMO roles from one DC to another using GUI consoles or via PowerShell. By using PowerShell the transfer becomes much easier.

Make sure that all FSMO roles are located on the old (Windows 2012r2) domain controller:

netdom query fsmo

netdom query fsmo powershell

Now you can transfer all 5 FSMO roles to a new DC:

Move-ADDirectoryServerOperationMasterRole -Identity "dc3-2016" -OperationMasterRole 0,1,2,3,4

move addirectory server operation master role

After the transfer is complete, make sure that the new DC with Windows Server 2016 is the new FSMO roles owner:

Get-ADDomain | Select-Object InfrastructureMaster, RIDMaster, PDCEmulator

Get-ADForest | Select-Object DomainNamingMaster, SchemaMaster

Get-ADDomainController -Filter * |

Select-Object Name, Domain, Forest, OperationMasterRoles |

Where-Object {$_.OperationMasterRoles} |

Format-Table -AutoSize

get addomain powershell

After transferring all of the roles, you can remove the old DC by demoting it with the following Powershell commands:

Import-Module ADDSDeployment

Uninstall-ADDSDomainController -DemoteOperationMasterRole -RemoveApplicationPartition

The command prompts you to specify a new password for the local server Administrator.

uninstall adds domain controller

After the command completes, reboot the server.

The last thing to do is update the functional level of your Active Directory domain to Windows 2016. Make sure that the current domain level is Windows2012R2Domain:

Get-ADDomain | fl Name,Domainmode

get ad domain powershell

To upgrade the functional level of you AD from 2012r2 to 2016, run the command:

Set-ADDomainMode –identity contoso.com -DomainMode Windows2016Domain

set ad domain mode

So, in this way we have successfully upgraded the Active Directory domain to Windows Server 2016.

The post Move FSMO Roles and Upgrade Domain to Windows Server 2016 appeared first on TheITBros.


Installing WebDAV client on Windows Server 2016

$
0
0
windows server 2016

WebDAV (Web Distributed Authoring and Versioning) is an extension of the HTTP/1.1 protocol. The WebDAV protocol allows to access files on the remote server and perform common actions: reading, writing, deleting files. Typically, this protocol is used by users to work together with remote files. Simply put, WebDAV is essentially a web-based shared folder. To access the WebDAV shares, WebDAV client must be installed on the client side.

In Microsoft server operating systems there is no WebDAV client by default. For example, in Windows Server 2008 R2,2012/2012 R2, the WebDAV client is included to the Desktop-Experience feature. Therefore, to access WebDAV resources from these OSs, you must install this feature.

Install-WindowsFeature Desktop-Experience

Tip. In Windows Server 2008 R2, the Install-WindowsFeature cmdlet is missing, instead you need to use the Add-WindowsFeature.

Windows Server 2016 has a separate WebDAV-Redirector component. To install it, run the following command (you will need to reboot the server):

Install-WindowsFeature WebDAV-Redirector –Restart

After the reboot, verify that you have the WebDAV-Redirector feature installed:

Get-WindowsFeature WebDAV-Redirector | Format-Table –Autosize

WebDAV redirector

Two 2 new services will appear in the system:

  • WebClient (get-service WebClient) — Enable Windows-based programs to create, access, and modify Internet-based files;
  • MRxDAV (get-service MRxDAV) — File system driver (WebDav Client Redirector Driver).

MRxDAV

By default, the WebClient service and the MRxDAV driver are disabled and configured to run in Manual mode when a trigger event occurs. Apparently, according to the idea of the developers, the service should have been launched when it first accessed from the driver MRXDAV.SYS, but, alas, it does not work everywhere. Therefore, we will force Automatic option for the service.

Set-Service WebClient -StartupType Automatic

Set-Service MRxDAV -StartupType Automatic

Start the services by running the following commands:

Start-Service WebClient

Start-Service MRxDAV

start service MRxDAV

The WebClient service is configured through the registry. All available settings are located in the registry key HKLM\SYSTEM\CurrentControlSet\Services\WebClient\Parameters.

webclient parameters

From a practical point of view, the following parameters of the WebClient service may be of interest.

AcceptOfficeAndTahoeServers — Ability to connect to Web servers with SharePoint and Office Web Server (1 –by default);

BasicAuthLevel — The type of authentication used by the WebClient service. Available values:

  • 0 — Basic authentication disabled;
  • 1 — Basic authentication enabled for SSL shares only (default value on Windows Server 2016);
  • 2 or greater — Basic authentication enabled for SSL shares and for non-SSL shares (Not safe, because The username and password are sent in plain text);

FileSizeLimitInBytes — maximum size (bytes) for file transfers  (by default 50 MB).

To test the operation of WebDav Client, let’s use the webdav-enabled share on live.sysinternals.com. This web directory stores popular sysadmin’s utilities from Sysinternals.

You can mount WebDAV drive on Windows Server 2016 in the following ways:

  • Without SSL:
    net use * \\live.sysinternals.com\
  • With SSL:
    net use * \\live.sysinternals.com@ssl\
  • You can specify credentials to authenticate on a remote WebDav share:
    net use * \\live.sysinternals.com@ssl\ /user:itbros *
  • You can specify a specific TCP port:
    \\live.sysinternals.com@80\folder

    or

    \\live.sysinternals.com@ssl\share
  • To delete the connected WebDav drive, run the command:
    net use * /del /y

DAV root

In case you’ll face with System error 67 has occured. The network name cannot be found after mounting the Webdav drive via explorer or cmdfollow the steps below to fix it:

  1. Check if WebClient service is started;
  2. Change the value of the registry parameter BasicAuthLevel to 1;
  3. Restart the computer.

The post Installing WebDAV client on Windows Server 2016 appeared first on TheITBros.

How to Add or Remove SMTP Alias to Exchange 2016 Mailbox

$
0
0
exchange 2016

Sometimes you need to add another email address to the existing user. In Exchange, in addition to the primary address, each mailbox can be assigned to several additional ones (called aliases or proxy addresses). In Active Directory, additional aliases are stored in the recipient’s multi-valued attribute named proxyAddresses. Proxy addresses allow user to receive mail sent to different addresses. Any email sent to the user’s proxy address is delivered to the primary e-mail address mailbox, called the default response address.

For example, we need to assign a user with the primary SMTP address JunminH@contoso.com a shorter name (surname) alias address — hao@contoso.com.

In Exchange Server 2016 you can add an additional SMTP alias to the user using the Exchange Admin Center or the Exchange Management Shell.

To add an SMTP alias to a user using EAC, follow these steps:

  1. Select Recipients -> Mailboxes;
  2. In the list of users, select the desired user and double-click on it (or press on the pencil icon);
    exchange admin center alias
  3. Click on the Email address tab and press +;
  4. In the Email address field enter a new alias email address (hao@contoso.com);
    exchange email SMTP
  5. Press OK -> Save.

Also you can manage SMTP aliases by using the PowerShell console. Run the Exchange Management Shell with Administrator privileges. For example, you can display the list of a SMTP aliases and the primary address for the junminh mailbox using this command:

Get-Mailbox junminh | fl EmailAddresses, PrimarySmtpAddresses

email address exchange

You can change SMTP addresses associated with the mailbox by using the Set-Mailbox cmdlet with the EmailAddresses parameter, but there is one subtlety here. The fact is that EmailAddresses is a multi-valued attribute, so to add addresses to the list, you need to use the add method, for example:

Get-Mailbox junminh | Set-Mailbox -EmailAddresses @{add=”hao@contoso.com","junminh@contoso.local",”manager@contoso.com”}

get email address exchange

Accordingly, you can remove proxy addresses by using the remove method, for example:

Get-Mailbox junminh | Set-Mailbox -EmailAddresses @{remove="manager@contoso.com"}

And one more way to change addresses! This method works somewhat differently — it completely removes the original list and replaces it with the specified one. For example:

Get-Mailbox junminh | Set-Mailbox -EmailAddresses SMTP:junminh@contoso.local, manager@contoso.com

If you have many users whom you need to assign a new SMTP aliases, you need to create .csv file of the following kind (comma delimited):

proxyaddresses,mail
jsmith@contoso.com,john@contoso.com
kabrams@contoso.com,ken@contoso.com

And run the following command in the Powershell console:

Import-Csv -Path "C:\PS\user_proxyadresses.csv" | ForEach-Object { Set-Mailbox $_."mail" -EmailAddresses @{Add=$_."proxyaddresses"} }

PowerShell commands that is described above work on Exchange 2010, 2013 and 2016.

The post How to Add or Remove SMTP Alias to Exchange 2016 Mailbox appeared first on TheITBros.

Time Configuration for a Virtualized Domain Controllers

$
0
0
time synchronization

Today we will talk about some of the features of time configuration on a virtualized domain controllers. Typically, the time synchronization scheme in the Active Directory domain is as follows:

  • The PDC emulator is the main time source on the domain and must be configured to synchronize time with the external time source;
  • All other domain controllers are synchronized with the controller that owns the PDC emulator role;
  • All member servers and workstations synchronize their time with the nearest domain controller.

Tip. For more information about configuring NTP time in a domain, see the article Configure NTP Time Sync using Group Policy.

For example, this is how the time settings look on our virtual domain controller. As you can see, it uses group policies to configure time setting and synchronize time with the external source pool.ntp.org.

ntp server policy

However, if you check the current time source (w32tm /query /source), you can find it unexpectedly, because you can see a strange time source named VM IC Time Synchronization Provider.

vm time synchronization provider

The fact is that Hyper-V virtual machines synchronize their time with the host by default, and regardless of the settings of the time service inside the machine. As a result, it can turn out to be a rather strange situation when the Hyper-V host is a member of the domain and synchronizes time with the domain controller, which in turn is a virtual machine and synchronized with the host (Recursion?).

In order to avoid this, you must disable time synchronization with the host for virtual domain controllers. There are two ways to do this.

The first way is to disable time synchronization in VM properties. To do this, open the properties of the virtual machine in the Hyper-V Manager snap-in, go to the Integration Services section and check off Time synchronization.

dc settings time synchronization

The same can be done using the PowerShell console on the Hyper-V server. For example, with this command, get the service status for the VM:

Get-VMIntegrationService -VMName dc1 -Name ‘Time synchronization’

The following command will disable time synchronization:

Get-VMIntegrationService -VMName dc1 -Name ‘Time synchronization’ | Disable-VMIntegrationService

get vm integration service time sync

If you are using VMWare ESXi as the virtualization host, you can disable the time synchronization with the host in the virtual machine settings.

VM->Edit Settings -> VM Options tab -> Check off Synchronize guest time with host.

vm options synchronize time

The second way is to edit the registry inside the guest virtual machine with ADDS role. To disable synchronization, run Regedit.exe, go to branch HKLM\SYSTEM\CurrentControlSet\Services\W32Time\TimeProviders\VMICTimeProvider and change the value for the Enabled parameter to 0.

VMICTimeProvider

The same setting can be made from the Command Prompt by running the command:

reg add HKLM\SYSTEM\CurrentControlSet\Services\W32Time\TimeProviders\VMICTimeProvider /v Enabled /t reg_dword /d 0

VMICTimeProvider reg add

In addition, it is desirable to make the following settings:

  1. Change the NTP server polling period:
reg add HKLM\SYSTEM\CurrentControlSet\Services\W32Time\TimeProviders\NtpClient  /v SpecialPollInterval /t reg_dword /d 900
  1. Configure the correct response of the time service to a non-standard time change of more than 52 hours
reg add HKLM\SYSTEM\CurrentControlSet\Services\W32Time\Config /v MaxNegPhaseCorrection /t reg_dword   0xFFFFFFFF

reg add HKLM\SYSTEM\CurrentControlSet\Services\W32Time\Config /v MaxPosPhaseCorrection /t reg_dword /d  0xFFFFFFFF

After disabling synchronization by any of the described methods, it is necessary to restart the time service, this will reset it to a new source. On a domain controller with the PDC-emulator role, you must restart the w32time service and run the synchronization:

net stop w32time

net start w32time
 w32tm /resync /force

net stop w32 time

On all other AD domain controllers, you need to additionally execute the command:

w32tm/config /syncfromflags:DOMHIER /update

This will cause the Time Service to select the PDC emulator as the source according to the domain hierarchy. In this way, we will configure the correct time synchronization scheme in the domain.

The post Time Configuration for a Virtualized Domain Controllers appeared first on TheITBros.

Arrays Basics on PowerShell

$
0
0
array arr powershell cover

Arrays are used very often when creating PowerShell scripts, so you need to understand how to work with them. In this article we’ll take a look at the basic examples of using arrays in PowerShell.

Usually an array is a set of elements arranged one after the other in a certain order. Each element of the array has its own sequence number. To access the desired array element, you need to specify its number (index).

Let’s create a simple array with three elements:

$arr1 = "one", "two", "three";

To add a new element to an array, run the following command:

$arr1 = $arr1 + "four"

Let’s display the contents of this array:

$arr1

array powershell arr

You can get the number of array elements using the Length property:

$arr1.Length

If you need to access a specific element of an array, you must specify its sequence number when accessing it. The index of the elements of the array begins with 0. To refer to the first element of the array $arr1, use the command:

$arr1[0]

You can also specify a negative value for the sequence number. So, for example, [-1] means the last element of the array:

$arr1[-1]

The last element of the array is also numbered as Length-1 (which is logical, since the numbering starts from zero). This is convenient, since you don’t need to look at the total number of array elements, but simply select a range, for example:

$arr1[2..($arr1.Length-1)]

array powershell arr length

If you need to increase the length of the array, you can use the + or += operators:

$arr1+=5,6
$arr1

array arr powershelll

In fact, in this case we did not add elements to the existing array, but created a new one into which the contents of the old array were copied and new elements were added.

By the same logic, we can’t remove elements from an already existing array, but we can create a new array and copy all the elements there, except unnecessary ones:

$arr2=$arr1[0,1 + 4..($arr.Length-1)]

It is quite easy to combine arrays:

$arr3=$arr1 + $arr2

arr powershelll

To delete an array, use the Remove-Item cmdlet (del alias) and remove the array from the virtual disk named variable.

Del variable:arr3

array powershell arr variable

Each element of the array can have its own type. When working with arrays, remember that by default PowerShell tries to determine the type of data by itself. For example, create a new variable and put a few numbers into it, and then check the data type in the variable:

$arr2 = 1, 2, 3
$arr2.GetType()

As you can see, to create an array we need to assign values to its elements and get an array (System.Array type). But if you put one value into a variable, then PowerShell will not create an array:

$notarr = 1
$notarr.GetType()

system array powershell

As the example shows, PowerShell determines the type of data in a variable, depending on the number of objects. To create an array consisting of one element:

$arr4 = ,1
$arr4.GetType()

By default, all arrays in PowerShell are polymorphic, i.e. can contain elements of different types. If necessary, you can restrict the members of the array to a specific data type (a typed array). For example, you can only specify integer values as array elements:

[int32[]]$arr5 = 1

And in this way we can define system process as array members:

[System.Diagnostics.Process[]]$arr6 = Get-Process

arrays arr powershelll process

You can also create an array with the help of the subexpression operator of the array “@”, which forms the array in any case (even with complete absence of objects). It is very convenient to first initialize the array variable and then add the necessary objects to it without worrying about their number:

$arr0 = @()

The post Arrays Basics on PowerShell appeared first on TheITBros.

Using Powershell cmdlet Invoke-Command

$
0
0
Invoke Command cmdlet

Nowadays PowerShell Remoting is the main tool for remote management of Windows operating systems. Therefore, any Windows administrator should know about tool’s capabilities and to be able to use it. To run commands on remote computers using PowerShell Remoting, you can use the Powershell cmdlet Invoke-Command (alias icm).

The Invoke-Command cmdlet functionality is based on protocol Web Services for Management (WS-Management) and the Windows Remote Management (WinRM) service is used for communication. Communication between computers is performed via HTTP (default) or HTTPS. All traffic between the two computers is encrypted at the protocol level (except when SSL is used). Several authentication methods are supported, including NTLM and Kerberos. The possibility of creating remote sessions in Powershell appeared in version 2.

How to use Powershell cmdlet Invoke-Command?

To be able to remotely connect to a computer on it, you need to make a number of settings:

  1. At first you need to enable remote connection:
     Enable-PSRemoting -Force
  2. Then start the WinRM service:
     Start-Service WinRM
  3. Now allow incoming connections in the Windows firewall.

The client computer (from which the remote connection via PowerShell Remoting is established) also requires some additional configuration:

  1. You must enable connection to the remote systems. To access any computers, you can use the following command:
     Set-Item wsman:\localhost\client\trustedhosts * -Force
  2. Verify that the firewall does not block outbound connections.

Now to run the command on a remote computer through Powershell (for example, you want to restart the Spooler service), you need to run this command:

Invoke-Command -computername server1 -credential domain\user1 -scriptblock { Restart-Service spooler}

This command executes the Restart-Service spooler command on the remote computer server1. The Credential parameter is used to execute the command in the security context of the user domain\user1.

Windows PowerShell displays a dialog box in which you must specify the password for the account user1. Then the command is executed on server1 and returns the results. After executing the command, the PoSh session ends.

invoke-command

To run the task in the background, you can optionally specify the -AsJob parameter.

Remember that when you start command in the background, PowerShell does not return the result. To receive it, you must use the Receive-Job cmdlet.

Get-job –id 3 |Receive-Job

In order to run the script, the Invoke-Command cmdlet has the -FilePath option, which can be used instead of -ScriptBlock to specify the path to script file. For example, we created a small PoSh script that displays a list of stopped services and launched it on a remote computer server1:

Invoke-Command -computername server1 -FilePath .\list.ps1

invoke cmdlet

To execute this script, you do not need to copy the script files on the remote computer. The result of the script is displayed on the local computer.

Quite often there is a need to simultaneously perform a specific task on several computers. You can do that in a simple way using the same Invoke-Command. For example, you can enumerate computer names by commas:

Invoke-Command -ScriptBlock {Restart-Service spooler} -ComputerName server1,server2

Place to an array:

$srv_list = @(″server3″,″server4″,″server5″)
 Invoke-Command -ScriptBlock {Restart-Service spooler} -ComputerName $servers

Or take from the text file:

Invoke-Command -ScriptBlock {Restart-Service spooler} -ComputerName`
 (Get-Content .\servers_list.txt)

Each computer individually executes the command and returns the result to the console.

Note. Invoke-Command has a ThrottleLimit parameter that limits the maximum number of computers that can be controlled at the same time. By default, this parameter is set to 32. If necessary – it can be changed (but note that increasing this parameter will increase the load on the processor and memory of your computer, so this operation must be performed with great care).

If the ActiveDirectory module is installed, it becomes possible to run commands on multiple systems using pipelines:

Get-ADComputer -Filter * -properties name | select {Name="computername";Expression={$_."name"}}| Invoke-Command -ScriptBlock {hostname}

Each time an Invoke-Command is executed, a new session is created, which takes time and resources to create. To avoid this, you can open one session in which to execute all the commands. For example, open a session named computer1 on the computer and put it into the $session variable, and then perform your task on this session:

$session = New-PSSession -ComputerName computer1  -Name computer1
 Invoke-Command -ScriptBlock { Restart-Service spooler } -Session $session

The session will be active until you close the PowerShell console. You can also close the session – Disconnect-PSSession or delete it – Remove-PSSession.

The post Using Powershell cmdlet Invoke-Command appeared first on TheITBros.

Add Calendar Permissions in Office 365 via Powershell

$
0
0
add calendar permissions office 365 powershell

This is a tutorial on how to add calendar permissions in Office 365 for your users via Powershell. You can add permissions onto a specific mailbox, or you can add it onto a security group.

By default, Exchange (and Office 365) users can’t view messages or calendar items of other users. The only permission that is provided to all users by default is the ability to view free/busy information in the calendar of other users (AvailabilityOnly role).

Office 365 Calendar Permissions

Step 1

The first is step is to launch Windows PowerShell. We recommend running it as Administrator.

set calendar permissions office 365 powershell

Step 2

Run the following command to login to 365 via Powershell and login with your Office 365 admin credentials:

$LiveCred = Get-Credential

calendar permissions office 365 powershell

Step 3

Now you need to create a new session:

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

Step 4

Now you need to import the Office 365 session:

Import-PSSession $Session

powershell office 365 calendar permissions

Step 5

 

You can view current calendar permissions of the specified mailbox by using following:

Get-MailboxFolderPermission username:\calendar

As you can see by default on a calendar folder assigned only AvailabilityOnly role.

office 365 calendar permissions

You can get the list off all user’s calendars default permissions using the following command:

Get-Mailbox –database mbxdbname| ForEach-Object {Get-MailboxFolderPermission $_”:\calendar”} | Where {$_.User -like “Default”} | Select Identity, User, AccessRights

Step 6

You can use these available access roles:

  • Owner — read, create, modify and delete all items and folders. Also this role allows manage items permissions;
  • PublishingEditor — read, create, modify and delete items/subfolders;
  • Editor — read, create, modify and delete items;
  • PublishingAuthor — read, create all items/subfolders. You can modify and delete only items you create;
  • Author — create and read items; edit and delete own items NonEditingAuthor – full read access and create items. You can delete only your own items;
  • Reviewer — read only;
  • Contributor — create items and folders;
  • AvailabilityOnly — read free/busy information from calendar;
  • LimitedDetails;
  • None — no permissions to access folder and files.

Step 7

Now run the following command. In the example below, user2 would be able to open user1 calendar and edit it:

Add-MailboxFolderPermission -Identity user1@domain.com:\calendar -user user2@domain.com -AccessRights Editor

If you need to change the Default permissions for the calendar folder (in order to allow all users view calendar of the specified user), run the command:

Set-MailboxFolderPermission -Identity user1@domain.com:\calendar -User Default -AccessRights Reviewer

In some cases, you need to grant Reviewer permissions on a calendar folder in all mailboxes to all users in your Exchange organization. You can make this bulk permission change using simple PowerShell script. To change Default calendar permission for all mailbox in mailbox database to Reviewer:

Get-Mailbox –database mbxdbname | ForEach-Object {Set-MailboxFolderPermission $_”:\calendar” -User Default -AccessRights Reviewer}

To remove permission use Remove-MailboxFolderPermission cmdlet:

Remove-MailboxFolderPermission -Identity user1@domain.com:\calendar –user user2@domain.com

Now you can disconnect from Office 365 your session:

Remove-PSSession $Session

Alternative Script

Also see this 365 script for setting calendar permissions: Set Calendar Permission in Office 365 Exchange Online.

If the above information helped you, make sure to check out our official Office 365 Migration Guide.

The post Add Calendar Permissions in Office 365 via Powershell appeared first on TheITBros.

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

$
0
0
get service command

Using the Get-Service cmdlet you can get a list of all the services installed on the operating system, its 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 using Get-Service to get the status of a service on local or remote machines, the type of services startup, we’ll cover how to determine the dependencies of services.

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

Get-Service

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

get service powershell

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.

get service where object

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).

get service get member

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

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

DisplayName : Windows Update

Status : Stopped

CanPauseAndContinue : False

CanShutdown : False

CanStop : False

get service get member

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

Get-Service | select -property name,starttype

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

get-service wi*

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

To check the existence of a service on the system (usually used in various scripts), execute the following commands:

if (Get-Service "SomeService" -ErrorAction SilentlyContinue)

{

"SomeService exists"

}

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 argument. 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

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

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 required by the LanmanWorkstation service.

Get-Service -Name LanmanWorkstation –RequiredServices

get service name

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

Get-Service -Name LanmanWorkstation -DependentServices

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


The RPC server is unavailable 0x800706BA

$
0
0
the rpc server is unavailable fix

Most likely, a lot of you already faced with an error The RPC server is unavailable. (Exception from HRESULT: 0x800706BA), when you tried to connect to a remote computer or server through a specific MMC management snap-in, WMI, PowerShell, WinRM or another remote control tool.

The easiest way to test RPC connectivity is to use a simple WMI query against remote computer.

In our case, we tried to poll a remote computer through WMI from the PowerShell console.

PS C:\Windows\system32> Get-WmiObject Win32_ComputerSystem –ComputerName 192.168.0.14

Get-WmiObject : The RPC server is unavailable. (Exception from HRESULT: 0x800706BA)

At line:1 char:1

+ Get-WmiObject Win32_ComputerSystem –ComputerName 192.168.0.14

+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

+ CategoryInfo          : InvalidOperation: (:) [Get-WmiObject], COMException

+ FullyQualifiedErrorId : GetWMICOMException,Microsoft.PowerShell.Commands.GetWmiObjectCommand

the rpc server is unavailable 0x800706BA

In this example, you can see that the remote computer is not accessible by RPC.

Now you need to check the next things in order to fix the error The RPC server is unavailable 0x800706BA:

  1. Check if you have entered the incorrect IP address or computer name; check if the remote computer is now in the shutdown/startup state;
  2. Verify that Remote Procedure Call (RPC) and Windows Management Instrumentation services are running on the remote computer. You can check the status of services using the following commands: sc query Winmgmt and sc query rpcss. In the event that these services are started, the commands are returned STATE: 4 RUNNING. If the services are stopped, run them with the command:
    net start rpcss & net start Winmgmt

    0x800706BA

  3. Perhaps access to the remote computer over RPC ports is blocked by firewalls (this is a very common reason). If there are no firewalls on your network, try to temporarily disable the firewalls on the client and server side and check the RPC connection. Additionally, for the RPC protocol to operate, you must check the availability of port TCP/135 on the server side. The easiest way is to do this with a PoSh command:
    tnc 192.168.1.14 -port 135

    If the RPC service is enabled and access to it is not blocked, the TcpTestSucceeded line should contain True.
    error rpc server is unavailable 0x800706BA

If you are facing error The RPC server is unavailable 0x800706ba when performing the automatic registration of a certificate on a domain controller or in a certification authority, you can find the following error event in the application log on the server:

Source: CertificateServicesClient-CertEnroll Event ID: 13
Certificate enrollment for Local system failed to enroll for a DomainController certificate with request ID N/A from ServerCA.contoso.com\ ServerCA (The RPC server is unavailable. 0x800706ba (WIN32: 1722))

Or:

Source: CertificateServicesClient-AutoEnrollment EventID: 6
 Automatic certificate enrollment for local system failed (0x800706ba) The RPC server is unavailable.

the rpc server is unavailable

This problem can have several solutions, but in most cases the source of the problem is that your computer is a member of the group DCOM access group (DCOM access to certificate service) or the incorrect permission are issued. Follow the next steps:

  1. On the domain of the controller on which the certification service is deployed, you need to make sure that there is a domain group CERTSVC_DCOM_ACCESS or Certificate Service DCOM Access;
  2. Add the following domain groups to the CERTSVC_DCOM_ACCESS/Certificate Service DCOM Access group: Domain Users, Domain Controllers, Domain Computers;
  3. Update the DCOM security settings on the server with the CA role using the commands:
    certutil -setreg SetupStatus -SETUP_DCOM_SECURITY_UPDATED_FLAG
    
    net stop certsvc & net start certsvc
  1. On a server with the deployed CA, check the COM Security permissions. For this group, Remote access and Remote Activation permissions should be allowed.

After that, try to restart the computer and check the issuance of the certificate.

The post The RPC server is unavailable 0x800706BA appeared first on TheITBros.

How to Extract Group Members from Active Directory and Export It to CSV file

$
0
0
extract group members from active directory

In this article we’ll take a look at few examples of using PowerShell to extract group members from Active Directory different groups. This article should teach you how to build a list of accounts in a specific Active Directory group and export it to a CSV file, which is convenient to process in MS Excel and other Office programs.

Previously, to build a list of users in Active Directory group, you had to use VBS scripts, or DSQuery or CSVDE command-line utilities, which were not flexible enough and convenient.

To interact with Active Directory from PowerShell, Microsoft developed a special module Active Directory Module for Windows PowerShell. For the first time this module appeared in Windows Server 2008 R2 and in order to use it you must load it into your PowerShell session at first:

Import-Module ActiveDirectory

In Windows Server 2012/R2/Windows Server 2016 this module is automatically installed and loaded when the ADDS (Active Directory Domain Services) role is installed on the server when the server is promoted to a domain controller. In desktop operating systems (Windows 10/Windows 7), the Active Directory Module for Windows PowerShell is included in the Remote Server Administration Tools, which you need to download, install and enable separately.

extracting active directory group members

Please note that in order to use the ActiveDirectory module, you don’t need to be a member of the Domain Admins group, any authenticated domain user can obtain information about Active Directory users and groups using AD PowerShell module.

To get the information about the user accounts that are included in the Active Directory security group, use the Get-ADGroupMember cmdlet.

For example, to display the list of members of the Domain Admins group, run the following command:

Get-ADGroupMember ‘Domain Admins’

powershell get ad group members

If you do not know the exact name of the group, you can display the full list of groups in Active Directory using the command:

Get-ADGgroup -filter * | sort name | select Name

You can display only usernames:

Get-ADGroupMember -Identity ‘Domain Admins’| ft name

powershell get active directory group members

If the specified group contains other Active Directory groups, you must use the Recursive parameter to list members of Active Directory based on nested groups.

Get-ADGroupMember -Identity ‘Domain Admins’ -Recursive | ft name

The -recursive switch instructs the Get-ADGroupMember command to parse each nested group and display only objects that are not containers (user or computer). This command will display even those users who do not directly belong to the specified group.

You can display more detailed information about the accounts in this group in this way:

Get-ADGroupMember -Identity ‘Domain Admins’ | foreach { Get-ADUser $_ -Properties * }

You can use the more complex PowerShell command, which allows you to list all members of a certain domain security group with information about the company, department and job title, followed by sorting and grouping depending on the specific attribute (company):

Get-ADGroupMember -Recursive ‘Domain Admins’ | ForEach {

Get-ADUser -filter {samaccountname -eq $_.SamAccountName}  -Properties displayName, company, title, department

}  | Sort-Object company,displayName | Format-Table displayName,company,department,title -GroupBy company -AutoSize

list members of ad group

In order to extract group members from Active Directory into a text file, add the following command:

| Out-File -Width 5000 "C:\PS\ADGroupUsersByCompany.txt"

To export the list to the CSV csv, add the following pipe:

| Export-Csv -NoTypeInformation .\ADGroupUsersByCompany.csv -Encoding Unicode

You can calculate the total number of users in a group:

(Get-ADGroupMember -Identity Administrators).Count

Here is another useful example. Let’s try to find all AD groups containing the *Admin* keyword in the name, and display the users that are added in these groups. To display only unique objects, use the -uniq argument:

Get-ADGroup -filter 'SamAccountName -like "*Admin*"' | Get-ADGroupMember -recursive|Select-Object -uniq

In some cases, you can face error, which occurs during the execution of the Get-ADGroupMember command:

Get-ADGroupMember : The specified directory service attribute or value does not exist

This means that the group includes users from other forests (foreign security principals). The Get-ADGroupMember cmdlet doesn’t support working with users of different forests in Active Directory.

The post How to Extract Group Members from Active Directory and Export It to CSV file appeared first on TheITBros.

Add User to Active Directory Group Using Add-ADGroupMember

$
0
0
add user to active directory group ADGroupMember

The Active Directory Module for Windows PowerShell includes the Add-ADGroupMember cmdlet, which can be used to add user to Active Directory security or distribution groups. In order to use cmdlets from the ActiveDirectory module, at first you must load this module into your PowerShell session (on domain controllers with Windows Server 2012 or higher, this module is automatically loaded):

Import-Module ActiveDirectory

To add user1 to the domain group “TestGroup1”, run the following command in the PowerShell console with administrator privileges:

Add-ADGroupMember "TestGroup1" user1

Add ADGroupMember

You can add several users to the group at once, their accounts should be enumerated by comma:

Add-ADGroupMember "NYTraders" KDunkelman,SSmith

These are the simplest examples of using the Add-ADGroupMember cmdlet to add users to AD groups. Let’s consider some more complex methods.

For example, you need to get a list of users of one group (NYTraders) and add these accounts to another AD group (USTraders). To obtain a list of users of the NYTraders group, we will use the Get-ADGroupMember cmdlet. The resulting command might look like this:

Get-ADGroupMember “NYTraders” | Get-ADUser | ForEach-Object {Add-ADGroupMember -Identity “USTraders” -Members $_}

You can add to the group all users from a particular OU:

Get-ADUser -Filter * -SearchBase ‘OU=Users,OU=NY,OU=USA,DC=theitbros,DC=com’|

ForEach-Object -process {Add-ADGroupMember -identity "NY Users" -Members $_.SamAccountName}

After executing the command, you can open the ADUC console and make sure that all users have been added to the specified group.

Add_ADGroupMember identity

You can select users based on the value of some AD attribute and then add them to the particular group. For example, to add all users to the USAUsers group that have the United States in the co field, run the command:

Get-ADUser -filter {(co -eq "United States")} | ForEach-Object -process {Add-ADGroupMember -identity "USAUsers" -Members $_.SamAccountName}

You can create an Excel file (or a text CSV file) with a list of users that you want to add to a specific AD group. The file should be a list of samAccountNames of your users. You can use the following file format:

add user to active directory group

Below is the code of PowerShell script for adding users from CSV to the group:

$List = Import-CSV .\users.csv

$ErrorActionPreference='Continue'

$error.Clear()

ForEach ($User in $List)

{

Add-ADGroupMember -Identity ‘USTraders’ -Member $User.username

}

if ($error.Count -gt 0)

{

echo "Errors count: " $error.Count

}

$success=$($i-$error.Count)

if ($success -gt -1)

{

echo $success " users added successfully"

}

Similarly, you can add users to the Exchange distribution group:

Import-CSV .\Users.csv | ForEach-Object -process {Add-DistributionGroupMember -Identity "USTradersMailList" -Member $_.username }

The post Add User to Active Directory Group Using Add-ADGroupMember 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 CLI window 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 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 dialog elements. For example, our task is to write a simple GUI for script that shows the last password change time for the Active Directory user. In this example we use PowerShell 3.0+.

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):

$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 bounds, we use the AutoSize property.

$main_form.AutoSize = $true

Now you can display the form on the screen.

$main_form.ShowDialog()

powershell gui scripts

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

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 that were obtained 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 when the password was changed for the selected user:

$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)

Let’s add an event to this button, when user click on it. 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, it fills the drop-down list with the names of the accounts from AD. 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 examples

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

  • CheckBox
  • RadioButton
  • TextBox
  • ChekedListBox
  • GroupBox
  • ListBox
  • TabControl
  • ListView
  • TreeView
  • DateTimePicker
  • TrackBar
  • PictureBox
  • ProgressBar
  • HScrollBar
  • VScrollBar
  • ContextMenu
  • Menu

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 gui editor

And get ready PoSh code for your GUI scripts.

powershell gui editor script

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

Using Quest Active Directory Cmdlets for PowerShell

$
0
0
quest active directory powershell

Almost 10 years ago Quest Software released a free set of cmdlets to simplify interaction with Active Directory. This set of cmdlets provides quite flexible options for administering Active Directory, managing AD objects, AD ACLs, password settings, and security.

Up to version 1.5.1 Quest Active Directory cmdlets were provided for free. Later, Dell acquired the Quest company and began selling licenses for the later versions. Later, the product was renamed to Active Roles and you can download it here: https://www.oneidentity.com/products/active-roles/. However, the majority of administrators know this PowerShell module as Quest Active Directory Cmdlets for Powershell.

Despite the fact that you can’t download the Active Roles module from the official website for free, it’s easy to find an archive with the old free version of QAD cmdlets (1.5.1) on the Internet – Quest_ActiveRolesManagementShellforActiveDirectoryx64_151.msi.

In this article we’ll take a look at the installation and usage of the Quest Active Directory module Cmdlets for Powershell to administer the AD domain.

To install this PoSh module on your computer, you must have .Net Framework 3.5 installed. Installing the module is quite simple – run the MSI file and follow the instructions of the installer.

quest active directory

After the installation is completed, you need to import the module into the PoSh session with the command:

Add-PSSnapin Quest.ActiveRoles.ADManagement

You can display the list of available cmdlets for the Quest module with the command:

get-command *qad*

quest ad powershell

An example of cmdlets from a module:

  • Get-QADUser
  • Set-QADUser
  • New-QADUser
  • New-QADGroup
  • Add-QADGroupMember
  • Remove-QADGroupMember
  • Connect-QADService
  • Disconnect-QADService

First of all, let’s connect to the domain controller:

$pwd = read-host "Enter domain user password" -AsSecureString

Connect-QADService -service 'dc01.theitbros.com:389' -ConnectionAccount 'theitbros\user1' -ConnectionPassword $pwd

List the users and computers accounts in the domain:

Get-QADUser

Get-QADComputer

quest ad

You can get the information about a certain user and AD parameter. Format-List is required to display all the received properties:

Get-QADUser -Name JKelly -IncludeAllProperties | Format-List *

Let’s check if the user account is disabled:

(Get-QADUSer -Name "JKelly").AccountIsDisabled

You can also get a list of accounts in the group and save it to a csv file:

(Get-QADGroup "Domain Admins").members | Get-MemberName | Export-Csv "C:\PS\AdminGroupMembers.csv"

For example, create a new user account:

New-QADUser -name 'TJones' -ParentContainer 'OU=Users,OU=USA,DC=theitbros,DC=com' -UserPassword ‘P@ssw0rd!!’

Now let’s list the users who have not registered in the domain within 2 months and save the list to the HTML file:

$2months = (Get-Date).AddMonths(-2)
Get-QADUser -IncludedProperties LastLogon | where { $_.lastLogon -le
$2months} | Select DisplayName, LastLogon, AccountIsDisabled | ?{-not
$_.AccountIsDisabled} | ConvertTo-Html | Out-File c:\ps\inactiveusers.html

Accordingly, to disable, enable or unlock you can use: Disable-QADUser, Enable-QADUser and Unlock-QADUser. Cmdlets starting with Set are used to set and change parameters, they are often used in scripts.

Get-QADUser -Department Sales | Set-QADUser -ObjectAttributes @{"Department"="New Sales";"Description"="Sales dept"}

Disable all accounts that were not registered within 2 months:

Get-QADUser -IncludedProperties LastLogon | where { $_.lastLogon -le $2months} | where {-not $_.AccountIsDisabled} | Disable-QADUser

Of course, in Quest AD there is a big drawback: this module is not a part of the OS and is not supported by Microsoft, for its operation it is necessary to install the appropriate provider. These cmdlets were released by Quest before Microsoft had its own module for interacting with the AD – ActiveDirectory module for Windows PowerShell, which was introduced in Windows Server 2008 R2/Windows 7. Most of the functionality available in Quest AD cmdlets is now also available in the Active Directory module for Windows, so Quest AD cmdlets are used less and less.

The post Using Quest Active Directory Cmdlets for PowerShell appeared first on TheITBros.

Viewing all 91 articles
Browse latest View live