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

How to Use ForEach Loop in PowerShell?

$
0
0

Like other programming languages, PowerShell has the concept of loops. The loop (cycle) allows you to execute several times a certain set of commands.

The ForEach loop allows you to iterate over the array’s values. Its task is to perform certain actions for all items of the array. Unlike regular for, it is used to iterate over objects in an array.

Hint. We remind you that PowerShell is an object-oriented programming language.

The ForEach loop has the following syntax:

ForEach ($item in $array){

Scriptblock

}

The $item variable inside the loop points to the current element of the $array.

For example, create a simple array and use the foreach loop to list all its values:

$PCs = "PCName1", "PCName2", "PCName3"

foreach ($PC in $PCs)

{

write-host $PC

}

 

foreach loop in powershell

In some programming languages, processing in order to process such an array you must perform 2 steps. First, you need to get the length of the array, and then perform an action for each element. In PowerShell, everything is simpler. You do not need to calculate the number of elements in the array. It just sequentially goes through all the elements.

Now try to get a list of files in a specific directory. Now, using the ForEach loop, display the file names and the creation date of each file:

$Files = (Get-ChildItem "C:PS*")

foreach ($File in $Files) {

write-host $File.name $File.CreationTime

}

As you can see, inside the ForEach loop you can access all the properties and methods of each object in the array.

powershell foreach

Let’s consider another example of using a For-Each loop in AD. For example, you need to copy a specific file to all computers in Denver (it is assumed that all computers joined to the Active Directory domain and placed in the same Organizational Unit):

# Get a list of active AD computers in OU Denver

$ADComps = Get-ADComputer -Filter {enabled -eq "true"}

# Now, using the ForEach loop, copy the file from the network shared folder to the root directory (C: drive) of each computer

$SourceFile= “denv-fs01docdistrmy.cfg”

foreach ($computer in $ADComps)

{

$Hostname = $Computer.Name

$TargetPath = "$HostnameC$"

Copy-Item $SourceFile $TargetPath -Force

}

Note that there is a ForEach-Object cmdlet (with the alias ForEach), and a ForEach loop. This may be misleading. The ForEach-Object command is most often used in pipelines. The ForEach loop cannot be used in the pipeline.

For example, the ForEach-Object command:

Get-Service | ForEach-Object {$PSitem.Name}

Or, using an alias:

Get-Service | ForEach {$PSitem.Name}

And now the ForEach loop:

$services= Get-Service

ForEach ($service in $services) {

write-host $service.displayname

}

The PowerShell understands by a general construction syntax when to use the ForEach cmdlet and when to use a loop.

One of the differences between foreach loop and a foreach cmdlet is the ability to use continue and break operators.

The continue statement allows you to skip the execution of the remainder part of a and immediately go to the next array element.

The break statement completely stops enumeration of elements in a loop. It is used, we are looking for a specific value and you need to exit the loop when it is found:

$num=0

$computers = 'PC1','PC2','Server1','PC3'

foreach ($computer in $computers) {

if ($computer -like '*Server*') {

break

}

$num++

}

$num

In this example, the loop stopped at third elements.

powershell foreach line in file

Three special variables are available in the ForEach loop::

  • $foreach.MoveNext() – go to next item;
  • $foreach.current – current item pointer;
  • $foreach.reset() – resets the iteration. Iterating will start anew, leading to an endless loop.

PowerShell ForEach loops have a very large scope. This helps in server administration, managing services, processes and files, operations with Active Directory objects, etc.

The post How to Use ForEach Loop in PowerShell? appeared first on TheITBros.


How to Transfer FSMO Roles Using PowerShell?

$
0
0

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 using both the Active Directory graphics snap-ins and the PowerShell command prompt.

There are several tools to manage FSMO roles in an AD domain: MMC snap-ins, Ntdsutil.exe command line utility and PowerShell. In our opinion, the PowerShell is the most convenient way to manage AD FSMO roles today. The only drawbacks are the unusual syntax. Otherwise, there are only pluses, PowerShell allows you to transfer, or seize roles with just a one command.

Transfer FSMO roles using PowerShell cmdlets from the Active Directory PowerShell module has the following benefits:

  • You do not need to connect with the 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 10 desktop 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), use the additional -force parameter.

Import Active Directory module to the current PowerShell session:

Import-Module activedirectory

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

To get the forest level FSMO role holders in the specified domain (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 role owners (Infrastructure Master, PDC Emulator and Relative Identifier Master roles):

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

transfer fsmo roles powershell

Or you can get information about all roles in your AD using the following PowerShell one-liner:

et-ADDomainController -Filter * | Select-Object Name, Domain, Forest, OperationMasterRoles | Where-Object {$_.OperationMasterRoles}

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, your environment must meet the following requirements:

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

Check the current Active Directory schema version:

Get-ADObject (Get-ADRootDSE).schemaNamingContext -Property objectVersion

move fsmo roles powershell

In this case, the AD objectVersion is 87. This corresponds to the version of the AD schema in Windows Server 2016, so we can transfer the FSMO roles from PowerShell.

Unlike the Ntdsutil.exe utility, the Move-ADDirectoryServerOperationMasteRole cmdlet can be performed from any domain computer.

Note. In order to migrate the Operations Master roles, your account must be a member of privileged domain groups: 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

You can run this command on any domain controller, including one that is neither the old nor the new role holder.

It is possible to transfer several roles at once:

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

Tip. To simplify the Move-ADDirectoryServerOperationMasterRole cmdlet usage, you can replace the names of roles with numbers from 0 to 4. The correspondence of names and numbers is given in the following table:

PDCEmulator
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

powershell transfer fsmo roles

Do you want to move role ‘PDCEmulator’ to server ‘dc2.theitbros.loc’ ?

[Y] Yes  [A] Yes to All  [N] No  [L] No to All  [S] Suspend  [?] Help (default is “Y”): A

After entering the FSMO transfer command for all or several roles, a prompt appears asking whether you want to confirm your actions or cancel them. To transfer all roles press A -> Enter. To skip confirmation, you can add the -Confirm:$false parameter to the previous command.

If you want to execute the FSMO transfer command under another user account, you can use the -Credential parameter:

$cred = Get-Credential

Move-ADDirectoryServerOperationMasterRole -OperationMasterRole SchemaMaster -Identity AD -Verbose -Force -Credential $cred

powershell move fsmo roles

Seizing FSMO Roles Using PowerShell

If the current owner of one or all of the FSMO roles fails, you can receive the following error when trying to use the Move-ADDirectoryServerOperationMasterRole cmdlet:

Move-ADDirectoryServerOperationMasterRole : The directory service is unavailable

In this case, you can force the transfer (seize) of FSMO roles using the -Force option:

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

Use the –force parameter when you receive the error when trying to move the FSMO roles using the graphical snap-ins: The transfer of the operation master role cannot be performed because: The requested FSMO operation failed. The current FSMO role holder could not be contacted.

move-addirectoryserveroperationmasterrole

When transferring or seizing the FSMO roles, keep in mind the following restrictions:

  • Do not assign the Infrastructure Master role to a domain controller that is a Global Catalog server, as it won’t update object information in domain. The reason for this behavior is that the global catalog server maintains partial replicas of all objects in the forest;
  • After the FSMO roles have been seized, the domain controller from which the roles were seized should never be connected to the domain (don’t forget to remove this DC computer account from the domain using the ADUC snap-in).

As you can see, PowerShell really allows you to perform FSMO role management tasks much faster and easier than the Ntdsutil tools and the MMC snap-ins.

The post How to Transfer FSMO Roles Using PowerShell? appeared first on TheITBros.

The RPC server is unavailable 0x800706BA

$
0
0

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 snap-in, WMI, PowerShell, WinRM, or another remote management tool.

Troubleshooting RPC server unavailable error 0x800706BA

The easiest way to test the RPC connectivity between local and remote computers is to use a simple WMI query against a remote host.

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.

Note. If the RPC communication between your hosts is working fine, you should get the remote computer info in the command output:

automatic certificate enrollment for local system failed (0x800706ba) the rpc server is unavailable.

There are several common problems that can cause the RPC server unavailable error:

  • The RPC service is stopped/failed on the remote computer;
  • The RPC Endpoint Mapper port TCP/135 is not accessible on the remote computer;
  • The Dynamic RPC range is blocked by firewalls installed between your computer and the remote computer.

First of all, make sure that RPC Endpoint Mapper port 135 in listening on a remote computer/ Use the following command:

netstat -ano | find "135"

the rpc server is unavailable. 0x800706ba

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 correct IP address or computer name; check if the remote computer is not in the shutdown/startup state now;
  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. If these services are started, the commands should return STATE: 4 RUNNING. If the services are stopped, run them with the command:
    net start rpcss & net start Winmgmt
  3. Or you can run the Service management console (services.msc) and make sure that the Remote Procedure Call (RPC) and DCOM Server Process Launcher services are in the running state and configured to start automatically.
    the rpc server is unavailable. 0x800706ba (win32: 1722 rpc_s_server_unavailable)

    rpc server is unavailable 0x800706ba

It is possible that 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 temporarily disable the firewall apps (including Windows Defender Firewall with Advanced Security) 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 (RPC Endpoint Mapper) on the remote computer side. The easiest way is to test for open/closed port is to use the following PowerShell command:

Test-NetConnection 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.

the rpc server is unavailable. (exception from hresult: 0x800706ba)

If port 135 (RPC Endpoint Mapper) is available, but the error “The RPC server is unavailable” is still present, you need to ensure that firewalls are not blocking communication on a dynamic RPC port range. The RPC Dynamic Ports is a TCP port range from 49152 to 65535, that must be open for RPC technology to work properly.

You can use a small command line tool PortQry from Microsoft to get a list on RPC Dynamic ports via the RPC Mapper service. Use the following command to get the list of RPC endpoints from a remote Endpoint Mapper Database:

PortQry.exe -e 135 -n 192.168.1.201

get-wmiobject : the rpc server is unavailable. (exception from hresult: 0x800706ba)

In this case, 151 endpoints were found. Each RPC point has a dynamic TCP port number next to it that it is listening on. You can check the availability of the RPC port for the desired service using the PowerShell command:

Test-NetConnection 192.168.1.201 -port 49703

Many firewalls block RPC and SMB / NetBios (NetScreen) even if you have any-any rules enabled. In this case, you must specifically create a rule/policy to explicitly allow RPC dynamic ports

Certificate Enrollment Error – 0x800706ba The RPC server is unavailable

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 Event Viewer > 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.

0x800706ba rpc

When you trying to enroll the certificate you can see the following message:

An error occurred while enrolling for a certificate.
The certificate request could not be submitted to the certification authority.
The RPC server is unavailable. 0x800706ba (WIN32: 1722 RPC_S_SERVER_UNAVAILABLE)

rpc 0x800706ba

In this case, the domain controller or other client fails to enroll for certificates from CA.

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 controller on which the certification service is deployed, you need to make sure that there is a domain security 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;
    an error occurred while enrolling for a certificate the rpc server is unavailable
  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
  4. On a server with the deployed CA, check the COM Security permissions. This group must have Remote Access and Remote Activation permissions allowed.
  5. After that, try to restart the computer and check the certificate enrollment.

If the above solution doesn’t work, use the nltest command to find out problems with netlogon calls to domain controller:

Nltest /Server:dc01 /query

0x800706ba

Then check the Active Directory CA request interface responding:

Certutil -ping

the certificate request could not be submitted to the certification authority rpc server unavailable

Server “test-DC01-CA” ICertRequest2 interface is alive (62ms)

CertUtil: -ping command completed successfully.

If you receive the error “Server could not be reached: The RPC server is unavailable. 0x800706ba (WIN32: 1722)” from the non-domain joined computer, please ensure that “Authenticated Users” group is added to the “Certificate Service DCOM Access” group on the CA server.

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

Understanding Global Catalog (Active Directory)

$
0
0

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. This role doesn’t need to be unique within an Active Directory domain or forest. However, the Global Catalog is the most important DC role from the practical point of view.

What is the Global Catalog?

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.

A typical domain controller stores a complete replica of objects in its own domain, but not for other domains in the forest.

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 via standard AD replication service. The set of attributes that are copied to the Global Catalog is defined in the AD schema. If necessary, you can configure additional attributes that will be replicated to the GC using the Active Directory Schema mmc 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.

global catalog

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

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

active directory global catalog

You can check that the current DC you are on has the global catalog role enabled:

Get-ADDomainController | ft Name,IsGlobalCatalog

Or to check GC role in all DC in an AD site:

Get-ADDomainController-Filter {Site -eq 'New-York'}} | FT Name,IsGlobalCatalog

Or use the dsquery command:

dsquery server -forest –isgc

The first GC server was automatically created on the first domain controller in the forest when you promote DC during installing Active Directory Domain Services role. In the case of a single AD 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.

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 the port TCP/3268 and sent to the GC server. If, for any reason, there is no GC server in the domain, users and applications won’t be able to perform searches across AD 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 (the UserPrincipalName attribute is used in this case);
  • 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 accounts and groups from any domain in the forest, the 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 want to find a person within the organization in the Outlook, 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 distribution groups. When a user tries to open an address book in Microsoft Outlook, or writes a message and enters a name or recipient address in the To field, Outlook uses the GC Server specified by the Exchange server. Exchange mail servers use Active Directory and DNS to locate Global Catalog servers.

How to Optimize Global Catalog Server Placement?

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 make all DCs in the forest as Global catalog servers. This will also have a positive effect on load balancing. Also, it is important to notice that from now on you won’t 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, make sure the infrastructure master FSMO role do not hosted 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 are no Global Catalog servers available, users can not log in, and the Exchange mail server can’t send and receive e-mail items. 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.

How to Enable/Disable the Global Catalog Role on a Domain Controller?

You can enable the Global Catalog role on a domain controller in several ways:

  • Using the graphical Active Directory Sites and Services mmc console;
  • Using PowerShell;
  • Using the dsmod.exe tool;

Run the mmc snap-in “Active Directory Sites and Services” (Start > Windows Administrative Tools, or run the dssite.msc command).

ad global catalog

Expand the Sites section and find the AD site that contains your domain controller. Expand it, right click on NTDS Settings and then select Properties.

Set the Global Catalog checkbox on the General tab to enable the GC role, or uncheck it to disable it. Click OK to save your changes.

global catalog active directory

You can enable the Global Catalog role on a DC using the PowerShell command:

Set-ADObject -Identity (Get-ADDomainController DC03).ntdssettingsobjectdn -Replace @{options='1'}

To disable the GC role, use the command:

Set-ADObject -Identity (Get-ADDomainController DC02).ntdssettingsobjectdn -Replace @{options='0'}

These commands can be used to move the global catalog server functionality from one domain controller to another.

You can also use the dsmod.exe command to enable the GC role. For example:

dsmod server "CN=dc03,OU=USA,DC=theitbros,DC=com" -isgc yes

The amount of time it takes to publish the Global Catalog in a forest depends on the replication topology. The domain controller doesn’t publish the DNS record that it has become a global catalog server until it receives all partial domain directory partitions through AD replication.

You can check the registration of a global catalog server in DNS by using the dnsmgmt.msc snap-in. Make sure you have an SRV record named _gc for your DC in the _tcp forward lookup zone.

global catalog server

After activating the Global Catalog role on DC, you can check its readiness. For this, the ldp.exe utility is used. Run the utility, select Connection > Connect > specify the DC name and a 389 as a connection port. Click Ok.

global catalog domain controller

Verify the isGlobalCatalogReady: TRUE value in the LDP window. This means that your GC is ready.

Also, you can check GC readiness from the command prompt:

nltest /server:dc01 /dsgetdc:test.com

domain controller global catalog

Check for a GC value in the Flags field.

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

How to Seize FSMO Roles From Dead Domain Controller?

$
0
0

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

How to Seize FSMO Roles From a Dead Domain Controller?

Suppose, we have two Windows Server 2012 R2 domain controllers in our Active Directory domain.

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

There are two ways to reassign FSMO roles in Active Directory:

  • Transferring FSMO roles — is used for planned demotion of a domain controller (for example, when you decommission a server), or when a DC is temporarily disconnected while performing maintenance tasks on a physical server;
  • Seizing FSMO roles — used when the physical server has failed (and you do not have an up-to-date Active Directory backup of this DC to perform non-authoritative restore of Active Directory Domain Services) or Windows Server is faulty; or after you have forcibly demoted a domain controller to a member server using the dcpromo /forceremoval command.

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

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

dsquery server -forest

seize fsmo roles from dead domain controller

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.

Note. When you create a new Active Directory domain, all FSMO roles are assigned to the first domain controller in the forest.

how to seize fsmo roles from a dead dc

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

Note. Administrators should take extra care when seizing FSMO roles. You should seize the FSMO role only as a last resort, when you cannot back your old DC with FSMO role online. If the domain controller hosting the FSMO role is temporarily unavailable, don’t worry about it. Your Active Directory network will survive without it for a day or two.

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

regsvr32 schmmgmt.dll

seize fsmo roles

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

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

roles

connections

connect to server DC2

q

primary domain controller failed

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

During the seizing of each role, you will be prompted to confirm.

force fsmo role transfer

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

transfer fsmo roles when dc is down

This domain has only one AD site called Boulder. Select 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

seize schema master

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:

Hint. Cleaning up metadata in Active Directory only needs to be done on older versions of Windows Server. In Windows Server 2012 R2 and newer, it is sufficient to remove the domain controller account using the graphical ADUC snap-in.

select domain 0 q

Delete the selected server (DC1):

remove selected server

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

seizing fsmo roles from dead server

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

Open the Administrative Tools > Active Directory Sites and Services snap-in (dssite.msc). Expand the site that contains the removed DC1, select it, and choose Delete. Confirm the removal of a DC1 twice.

how to seize fsmo roles

Then, open the DNS mmc snap-in (dnsmgmt.msc) and remove the PTR and A records remaining from DC1 server.

Now, open the Active Directory Users and Computers mmc snap-in (dsa.msc) and the expand “Domain Controllers” Organizational Unit (OU). If only DC2 is displayed there, then everything is fine. And if DC1 present in that container, you need to remove removed it from the Active Directory (unlikely, but check it out).

seize fsmo

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

Seizing FSMO Roles Using PowerShell

The Active Directory PowerShell module has a special cmdlet that makes it much easier to seize FSMO roles without using the ntdsutil tool. The Move-ADDirectoryServerOperationMasterRole cmdlet can be used to transfer or seize FSMO roles from any domain controller.

Hint. The Move-ADDirectoryServerOperationMasterRole cmdlet is available in the Active Directory module 2.0 or newer on domain controllers with Windows Server 2008 R2 or higher.

Import the ActiveDirectory module into your PowerShell session:

Import-Module ActiveDirectory

Use the following commands to find out which DC holds the FSMO role in your AD forest:

Get-ADDomain | Select PDCEmulator, RIDMaster, InfrastructureMaster | Format-List

Get-ADForest | Select SchemaMaster, DomainNamingMaster | Format-List

The following PowerShell command is used to seize FSMO roles from the original non-operational DC to a different operational DC:

Move-ADDirectoryServerOperationMasterRole -Identity dc02 –OperationMasterRole 0,1,2,3,4  -Force
  • -Identity — specifies the target DC to which the FSMO role should be seized
  • -OperationMasterRole — here it is indicated which FSMO roles to transfer (you can use role numbers or their names from the table below)
  • -Force — parameter is used to seize the FSMO roles when the source DC is offline

In order to accept roles transfer type A > Enter.

force transfer fsmo roles

Operation Master Role Name Number
PDCEmulator 0
RIDMaster 1
InfrastructureMaster 2
SchemaMaster 3
DomainNamingMaster 4

If FSMO roles are taken over, the domain controller that previously owned those roles should never come back online and communicate with the existing domain controller in the AD forest. Otherwise, a conflict will arise that can cause serious problems in the domain.

After capturing the FSMO roles, check for errors in the Directory Services and DNS logs in the Event Viewer. If you have problems, first use the following commands to help you fix the most common errors automatically:

dcdiag /v /fix

netdiag /v /fix

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 AD forest. The transfer of FSMO roles from the failed domain controller is now complete.

The post How to Seize FSMO Roles From Dead Domain Controller? appeared first on TheITBros.

Configuring Live Migration in Hyper-V

$
0
0

Hyper-V Live Migration allows you to move a running virtual machine between hosts without stopping it. Initially, Live Migration in Hyper-V was only available under Windows Failover Cluster with Cluster Shared Volumes (CSV). Starting from Windows Server 2012, Hyper-V Live Migration doesn’t require a cluster or shared storage. For VM migration, it is sufficient that the Hyper-V hosts are connected to a fast shared Ethernet network. This type of migration is called Shared-nothing Live Migration.

Hyper-V Live Migration Requirements:

  • At least two hosts with Hyper-V 3.0 or newer;
  • VM hardware version not lower than 5.0;
  • The target host must have enough resources to run the VM;
  • Hosts must use processors with the same architecture or you must enable the compatibility mode for VM( Migrate to a physical computer with a different processor version: Set-VMProcessor testvm1 -CompatibilityForMigrationEnabled $true);
  • It is desirable to have at least 1GB Ethernet network between hosts (it is recommended to allocate a separate NIC for Live Migration). On network adapters, you must enable the Client for Microsoft Networks and File and Print Sharing for Microsoft Networks protocols
  • Each server must have access to its own virtual machine storage (local disks, SAN LUNs, or SMB 3.0 shared network folders);
  • Virtual switches on all Hyper-V hosts must be named the same (this will help avoid many migration errors).

You need to enable Live Migration in the Hyper-V configuration of both hosts. Open Hyper-V Settings and enable the option “Enable incoming and outgoing live migration”. You can change the maximum number of simultaneously moving virtual machines. To avoid high load on hosts and the network, it is better to leave the default value—two simultaneous migrations.

In the Incoming live migration section, you can specify which Hyper-V hosts can migrate VMs to this host.

live migration hyper v

Then go to the Advanced Features section and select the Kerberos authentication protocol (Use Kerberos).

hyper v live migration step by step

You can do the same using PowerShell (remember to configure all Hyper-V hosts):

Enable-VMMigration

Set-VMMigrationNetwork 192.168.1.2 192.168.1.4

Set-VMHost -VirtualMachineMigrationAuthenticationType Kerberos

Hint. Compression is used by default for faster migration. However, you can use SMB Direct for migration. To speed up Live Migration, you can disable end-to-end encryption of SMB data:

Set-SmbServerConfiguration -EncryptData $false -RejectUnencryptedAccess $false

When using Kerberos authentication to transfer VMs between hosts, you need to configure Kerberos Constrained Delegation in the properties of Hyper-V hosts in Active Directory. Run the ADUC console, open properties for Hyper-V host account and go to Delegation tab. Select the option Trust this computer for delegation to specified services only > Use Kerberos Only.

Click the Add button > select the second Hyper-V host and select Microsoft Virtual System Migration Service.

hyper v to hyper v migration

Hint. In Hyper-V on Windows Server 2016/2019, when using this setting, you may face an error during migration “No credentials are available in the security package” (Event ID 20306). The point is that in these versions of Windows Server, Hyper-V services run in the NETWORK SERVICE context. To fix this error, you will have to use the less secure Unconstrained Delegation (Use any authentication protocol) mechanism.

Similar settings must be made on all servers participating in Live Migration.

Now try to migrate VM:

  1. Right click on the virtual machine and select Move;
    hyper v migration
  2. Select the move type Move the virtual machine;
    hyper v migration virtual machine
  3. Specify the name of the Hyper-V host to which you want to migrate the VM;
  4. Select the following move option: Move the virtual machine’s data to a single location;
    hyper v migration options
  5. Wait for the virtual machine to migrate to another Hyper-V host.

You can also run Live-Migration using PowerShell:

Move-VM testvm1 lon-hv2 -IncludeStorage -DestinationStoragePath E:\vm\testvm1

The post Configuring Live Migration in Hyper-V appeared first on TheITBros.

How to Connect to Exchange Online Using PowerShell?

$
0
0

In this article, we will show you how to install the Exchange Online PowerShell V2 (EXO V2) module and connect to Exchange Online. You can manage your Exchange Online tenant using the Exchange Admin Center (EAC) GUI or PowerShell. The Exchange Online PowerShell V2 module is used for connectivity and Exchange Online management. You can use EXO V2 module to connect to your Exchange Online in Microsoft 365 environment to manage settings, create/delete/modify mailboxes.

The EXO V2 module can be installed online from the PowerShell gallery, but you must have Windows PowerShell 5.1 or higher installed on your computer.

Hint. By using the REST API, EXO Module V2 is much faster and more reliable than the previous version of the Exchange Online PowerShell module (v1).

The new EXO V2 module supports Modern Authentication. This means you can connect to an Exchange Online tenant using MFA or non-MFA enabled account.

Note. Microsoft recommends enabling Multifactor Authentication for all Admin accounts. Basic EXO authentication will be decommissioned in 2021.

Installing the Exchange Online PowerShell V2 Module

Before installing the EXO V2 module, you need to change the settings for the PowerShell script execution policy. Open a PowerShell console as an administrator and run the command:

Set-ExecutionPolicy RemoteSigned

Confirm the change to the execution policy setting by pressing Y > Enter.

exchange online powershell

Close your current PowerShell console and start a new one:

start powershell.exe;exit

Now you need to install the PowerShellGet module:

Install-Module PowershellGet –Force

Confirm the import of the NuGet provider.

Now you can install the EXO V2 module:

Install-Module -Name ExchangeOnlineManagement

connect to exchange online powershell

To check which version of the EXO V2 module is installed, run the command:

Get-Module ExchangeOnlineManagement| ft name,version

In our case, the version is ExchangeOnlineManagement 2.0.3 is installed.

There are 17 cmdlets available in this version of the module. To list the available cmdlets, run the command:

Get-command -Module ExchangeOnlineManagement

connect exchange online powershell

The following cmdlets are available for managing Exchange Online:

  • Connect-ExchangeOnline;
  • Connect-IPPSSession;
  • Disconnect-ExchangeOnline;
  • Get-WrappedCommand;
  • IsCloudShellEnvironment;
  • UpdateImplicitRemotingHandler;
  • Get-EXOCasMailbox;
  • Get-EXOMailbox;
  • Get-EXOMailboxFolderPermission;
  • Get-EXOMailboxFolderStatistics;
  • Get-EXOMailboxPermission;
  • Get-EXOMailboxStatistics;
  • Get-EXOMobileDeviceStatistics;
  • Get-EXORecipient;
  • Get-EXORecipientPermission;
  • Get-UserBriefingConfig;
  • Set-UserBriefingConfig.

Hint. Please note that EXO V2 has changed the comnadlet names from Exchange Online PowerShell v1. For example, Get-EXOMailbox is used instead of Get-Mailbox, or Get-EXOMailboxStatistics is used instead of Get-MailboxStatistics, etc.

If you want to update a module, run the command:

Update-Module ExchangeOnlineManagement

Connect to Exchange Online with EXO PowerShell Module V2

To import the EXOv2 module into the PoSh current session, run the command:

Import-Module ExchangeOnlineManagement

If you are using an MFA (Multi-Factor Authentication) enabled administrator account, use the following cmcommand to connect to the Exchange Online:

Connect-ExchangeOnline -UserPrincipalName admin@theitbros.com

connect to exchange online

Enter your account password, then enter your verification code received in SMS and click Verify.

exchange online powershell module

If you are using a non MFA enabled account, use the following commands to connect to Exchange Online:

# Enter your Office 365 admin credentials

$Creds = Get-Credential

# Connect to Exchange Online under saved credentials

Connect-ExchangeOnline -Credential $Creds

powershell connect to exchange online

When you connect to Exchange Online, a banner appears in PowerShell listing the new cmdlets. To hide this banner, use the command:

Connect-ExchangeOnline -UserPrincipalName admin@theitbros.com -ShowBanner:$false -ShowProgress $true

You can now manage your Exchange Online mailboxes using PowerShell. For example, to get information about the d.brinkman mailbox, run the command:

Get-EXOMailbox d.brinkman@theitbros.com

To close a remote PowerShell session from Exchange Online, use the cmdlet:

Disconnect-ExchangeOnline -Confirm:$false

The post How to Connect to Exchange Online Using PowerShell? appeared first on TheITBros.

Filtering PowerShell Objects with Where-Object

$
0
0

The output of any PowerShell cmdlet is returns as objects. The Where-Object cmdlet is used in PowerShell to filter such objects. The Where-Object cmdlet allows you to filter the output of the previous command using a pipeline. In this article, we’ll show how to use the Where-Object cmdlet in PowerShell.

Let’s take a look at a simple example of using Where-Object. For example, we need to list the services running on the computer using the Get-Service cmdlet. To list only Windows services with a Running status, use the following command with Where-Object filter:

Get-Service | Where-Object Status -eq "Running"

powershell where filter

You can display all available cmdlet properties that can be used as a Where-Object filter using the command:

Get-Service | Get-Member -MemberType *Property*

powershell where object

There are two aliases for the Where-Object cmdlet — Where and the “?” character. The following two PowerShell commands are the same as the first command:

Get-Service | Where Status -eq "Running"

Get-Service | ? Status -eq "Running"

You can use multiple filter conditions in the Where-Object cmdlet. For example, we need to find all running services that contain the words Remote or Policy in DisplayName:

Get-Service | Where-Object {$_.Status -eq 'Running' -and $_.DisplayName -like 'Remote' -or $_.DisplayName -like '*Policy*'}

The number of conditions for filtering objects can be unlimited. If you need to use complex logic in a filter, limit the conditions with parentheses:

Get-Service | Where-Object {($_.Status -eq 'Running') -and ($_.DisplayName -like 'Remote' -or $_.DisplayName -like '*Policy*')}

Compare the results of the last two commands.

powershell where object filter

You can use different condition operators in the Where-Object cmdlet (the names of case-sensitive operators are shown in parentheses):

  • EQ (CEQ) — value is equal;
  • NE (CNE) — not equal;
  • GT (CGT) — the value is greater than;
  • LT (CLT) — less than;
  • LE (CLE) — less than or equal to;
  • GE (CGE) — more or equal;
  • Contains (CContains) — string entry;
  • NotContains (CNotContains) – occurrence in property;
  • Match (CMatch) — regular expression mask search;
  • NotMatch (CNotMatch) — no match by mask in regular expression;
  • Like (CLike) — filter by mask;
  • IS, IsNot — commonly used to check data types ($array | where {$_ -IsNot [int]}).

For example, the following command will list running processes that use more than 50MB of RAM, and sort them in a descending order:

Get-Process | ? {$_.WorkingSet -GT 50000*1024}|select processname,@{l="Working Memory (MB)"; e={$_.workingset / 1mb}} |sort "Working Memory (MB)" -Descending

where object filter in powershell

The Where-Object cmdlet is a powerful PowerShell filtering tool that comes handy when you need to select objects that match certain criteria from the returned objects.

The post Filtering PowerShell Objects with Where-Object appeared first on TheITBros.


How to Run PowerShell Script on Remote Computer?

$
0
0

The functionality of remote command execution in PowerShell is called PowerShell Remoting (appeared in PowerShell 2.0) and based on the capabilities of the Web Services for Management protocol (WS-Management). With PowerShell Remoting, you can run commands on one or several remote computers. You can use the interactive session mode with remote computers, a temporary, or permanent connection. Earlier we’ve covered how to run PowerShell script from Task Scheduler. In this article, we will take a look at several examples of how to execute a PowerShell script remotely.

Configuring WinRM for PowerShell Remoting

To connect to a computer remotely via PowerShell, the WinRM (Windows Remote Management service) must be enabled and configured on it (it is disabled by default). Communication between computers is performed over HTTP or HTTPS protocols, and all network traffic between computers is encrypted. You can use NTLM and Kerberos to authenticate on a remote computer.

To check the status of the WinRM service, run the Get-service command:

get-service winrm

run powershell script on remote computer

As you can see, the WS-Management service is running.

If the WinRM service is not running, you must enable it on the remote computer with the command:

Enable-PSRemoting

This command prepares the computer for remote management: starts the WinRM service, changes startup type to Automatic, and adds necessary exceptions to Windows Defender Firewall.

Hint. PowerShell Remoting uses TCP ports HTTP (5985) and HTTPS (5986) for network communications.

If the remote computer is in a workgroup (not joined to the Active Directory domain), and a Public network profile is applied to it (instead of Domain or Private), you need to explicitly allow incoming WinRM traffic in Windows Firewall:

Set-NetFirewallRule -Name "WINRM-HTTP-In-TCP-PUBLIC" -RemoteAddress Any

To test the connection to a remote server via WinRM use the following command:

Test-WSMan server1

powershell run script on remote computer

If you get a response, then the remote computer is accessible through PowerShell Remoting.

Hint. If you are connecting to a remote computer via PS Remoting by an IP address, you may receive an error:

Connecting to remote server 192.168.1.70 failed with the following error message: The WinRM client cannot process the request. Default authentication may be used with an IP address under the following conditions: the transport is HTTPS or the destination is in the TrustedHosts list, and explicit credentials are provided.

In this case, you need to install an HTTPS certificate for PowerShell Remoting on the remote computer (the long way), or add this host to the trusted ones on your management computer:

Set-Item wsman:\localhost\Client\TrustedHosts -value 192.168.1.70

Running Remote Commands with PowerShell Remoting

To interactively connect to a remote computer (with a hostname Server1) via PowerShell, run the following command:

Enter-PSSession Server1

The PowerShell CLI view will change. At the beginning of the line, there will be the name of the remote computer to which you are connected via WinRM. After the remote session is established, all commands that are being entered in the PowerShell console are executed on the remote computer. PS Remoting works as follows: the commands entered on the local computer are transmitted to the remote computer and are executed there, then the result is transmitted back. Since all commands are executed locally, there is no need to worry about compatibility with the PoSh version and modules.

To end the remote interactive session run the command:

Exit-PSSession

run powershell script remotely

Only the simple management tasks are typically performed on remote computers in the interactive mode. To run a complex command or run the PowerShell script remotely, use the Invoke-Command cmdlet.

Using Invoke-Command to Run PowerShell Scripts Remotely

The following command will create a remote connection with the computer Server1 and run the block of commands specified in the ScriptBlock parameter. After that, the remote session will automatically close.

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

You can run the task in the background by running Invoke-Command with the -AsJob parameter. But in this case, the command will not return the result to the PoSh console. To get the detailed background job information, use the Receive-Job cmdlet.

execute powershell script remotely

PowerShell allows you to run local PS1 scripts on remote computers. The idea is that you store all PowerShell instructions in a local .PS1 file on your computer. With PowerShell Remoting, you can transfer a PS1 file to a remote computer and execute it there.

To do this, use the -FilePath parameter in the Invoke-Command cmdlet instead of -ScriptBlock. For example, to run the c:\ps\tune.ps1 script on three remote servers, you can use the following command:

Invoke-Command -FilePath c:\ps\tune.ps1 -ComputerName server1,server2,server3

powershell execute remote script

The main advantage of this way of running PowerShell scripts is that you don’t need to copy the PS1 script file to remote computers. You can use not only the local script but also the PS script in a shared network folder that can be accessed from the local computer.

If you need to run PowerShell scripts with credentials other than the current user, you need to use the Credential parameter.

First, you need to get the credential and save them to a variable:

$cred = Get-Credential

execute powershell script on remote computer

Now you can run the PS script on remote computers under the saved credential permissions.

Invoke-Command -FilePath c:\ps\tune.ps1 -ComputerName server1,server2,server3 -Credential $cred

You can save the list of computers in a text file and run PowerShell script remotely on all computers at once:

Invoke-command -comp (get-content c:\ps\servers.txt) -filepath c:\ps\tune.ps1

By default, the Invoke-Command cmdlet sends the PS1 script to 32 remote computers from the list at the same time. If there are more than 32 computers, then PoSh checks the execution status of the script on the first 32 computers. If the script is completed, the command is executed on the next computer. With the ThrottleLimit parameter, you can increase this limit, but be careful not to overload your network.

Using Persistent PowerShell Connections (Sessions)

Each time you run Invoke-Command, a new session is created with the remote computer. This takes time and system resources. In PowerShell, you can create one session and execute all commands and scripts in it.

Using the New-PSSession cmdlet, you can create persistent PowerShell sessions with remote computers.

For example, let’s create sessions with three computers and save them in the $PSSess variable:

Invoke-Command -FilePath c:\ps\tune.ps1 -ComputerName server1,server2,server3

$PSSess = New-PSSession -ComputerName server1, server2, server3

After establishing a session, you can run it to run commands and scripts. Because sessions are persistent, you can get data from them and use in other commands and scripts.

For example, the following command will get a list of processes on remote servers and store them in the $RemoteProcesses variable:

Invoke-Command -Session $PSSess {$RemoteProcesses = Get-Process}

Now you can use this variable in other commands in the same sessions. In the following example, we use the Where-Object cmdlet to find processes that use more than 500MB of RAM):

Invoke-Command -Session $PSSess {$RemoteProcesses | where-object {$_.WorkingSet -GT 500000*1024}|select processname,@{l="Working Memory (MB)"; e={$_.workingset / 1mb}} |sort "Working Memory (MB)" -Descending}

powershell connect to remote computer and run command

The persistent remote PowerShell session will remain active until you close the PowerShell console, or forcefully close or delete the session using the Disconnect-PSSession or Remove-PSSession cmdlets, respectively.

As you can see, PowerShell provides ample opportunities for running scripts and commands on remote computers. Windows administrators surely can use PowerShell Remoting in addition to the classic PsExec tool from Sysinternals.

The post How to Run PowerShell Script on Remote Computer? appeared first on TheITBros.

How to Enable Remote Desktop (RDP) Remotely?

$
0
0

The most intuitive way to enable Remote Desktop on Windows is to use a GUI. To enable RDP on a local computer, you need to open the “System” Control Panel item, go to the “Remote Settings” tab and enable the Allow remote connections to this computer option in the Remote Desktop section. However, this requires local access to the computer on which you want to enable RDP. You can usually ask the user for this (local administrator permissions required), or local technical support. However, what to do if no one in the remote branch office could enable the Remote Desktop locally? By default, Remote Desktop is disabled on both desktop versions of Windows and Windows Server.

enable rdp remotely

If you want to remotely enable Remote Desktop (RDP) on a remote host (server or computer), but you don’t have access to the local device console, we’ll show how to do it using PowerShell.

Enable RDP Using Remote Registry Service

You can enable Remote Desktop on a remote computer using Registry Editor. This requires:

  • The remote computer must be accessible over the network;
  • You must know the credentials of an account with local administrator permissions on the remote computer;
  • The Remote Registry service must be running on the remote computer (you can enable it through the services.msc snap-in or GPO).

powershell enable remote desktop

So, to enable the remote desktop via remote registry, follow these steps:

  1. Press the Win + R key combination and in the Run window type regedit.exe > Ok;
    remotely enable remote desktop
  2. In the Registry Editor select File > Connect Network Registry;
    enable remote desktop remotely
  3. Specify the hostname or IP address of the remote computer.If the remote computer could not authorize you as the current user, you will be prompted to enter credentials;
    powershell enable rdp
  4. The registry of the remote computer will appear in the registry editor (only HKLM and HKEY_Users hives are accessible);
    enable remote desktop powershell
  5. Go to the following reg key on the remote computer: HKLM\SYSTEM\CurrentControlSet\Control\Terminal Server. Change the DWORD value of the fDenyTSConnections parameter from 1 to 0;
    how to enable remote desktop remotely
  6. If a firewall is enabled on the remote computer, you must enable the rule that allows remote desktop connections. You can enable it via GPO, via PowerShell Remoting (described in the next section of this guide), or using Psexec. In the latter case, the following commands are used:
    PsExec.exe \\server1 -u contoso\admin -p password cmd
    
    netsh advfirewall firewall add rule name="allow RemoteDesktop" dir=in protocol=TCP localport=3389 action=allow
    
    shutdown –f –r –t 0
  7. After rebooting, try to connect to the remote computer via RDP.

Enable Remote Desktop Remotely Using PowerShell

To enable RDP remotely, you need to configure and run the WinRM service (Windows Remote Management) on the remote computer. The WinRM service is enabled by default in all versions of Windows Server starting with Windows Server 2012. However, WinRM is disabled by default in client operating systems such as Windows 10. Thus, to enable Remote Desktop remotely via PowerShell, the remote computer must meet the following requirements:

  1. The WinRM service should be started;
  2. You must have administrator permissions on the remote device;
  3. Windows Defender Firewall with Advanced Security must be disabled or the rules that allow remote access through PowerShell Remoting should be enabled.

Suppose you want to remotely enable RDP on Windows Server 2012 R2/2016/ 2019. Open the PowerShell console on your computer and run the following command to connect to your server remotely:

Enter-PSSession -ComputerName server.domain.local -Credential domainadministrator

So, you have established a remote session with a computer and now you can execute PowerShell commands on it. To enable Remote Desktop, you just need to change registry parameter fDenyTSConnections from 1 to 0 on the remote computer. Run the command:

Set-ItemProperty -Path 'HKLM:\System\CurrentControlSet\Control\Terminal Server'-name "fDenyTSConnections" -Value 0

enable rdp powershell

When RDP is enabled in this way (as opposed to the GUI method), the rule that allows remote RDP connections is not enabled in the Windows Firewall rules. To allow incoming RDP connections in Windows Firewall, run the command:

Enable-NetFirewallRule -DisplayGroup "Remote Desktop"

Hint. By default, TCP/3389 port is used for incoming Remote Desktop connections on Windows. You can change the default RDP port number through the registry using the PortNumber parameter in the reg key HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Terminal Server\WinStations\RDP-Tcp.

If for some reason this firewall rule is missing, you can create it manually:

netsh advfirewall firewall add rule name="allow RemoteDesktop" dir=in protocol=TCP localport=3389 action=allow

If you want to restrict hosts or subnets that are allowed to connect to Remote Desktop, you can create a custom rule that allows Windows Firewall to solely accept incoming RDP connections from specific IP addresses, subnets, or IP ranges. In this case, instead of the previous command, you need to use the following one:

New-NetFirewallRule -DisplayName “Restrict_RDP_access" -Direction Inbound -Protocol TCP -LocalPort 3389 -RemoteAddress 192.168.1.0/24,192.168.2.100 -Action Allow

If you need to enable secure RDP authentication (NLA – Network Level Authentication), run the command:

Set-ItemProperty -Path 'HKLM:\System\CurrentControlSet\Control\Terminal Server\WinStations\RDP-Tcp' -name "UserAuthentication" -Value 1

Now you can check the availability of TCP port 3389 on the remote host from your computer. Run the command:

Test-NetConnection 192.168.1.11 -CommonTCPPort rdp

There should be a result like this:

ComputerName : 192.168.1.11

RemoteAddress : 192.168.1.11

RemotePort : 3389

InterfaceAlias : Ethernet0

SourceAddress : 192.168.1.90

TcpTestSucceeded : True

enable remote desktop windows 10 remotely

This means that RDP on the remote host is enabled and you can establish a remote desktop connection using mstsc.exe, RDCMan, or any alternative RDP client.

Hint. If you need to enable RDP on several remote computers at once, you can use the following PowerShell script:

$comps = “Server1”, “Server2”, “Server3”, “Server4”

Invoke-Command –Computername $comps –ScriptBlock {Set-ItemProperty -Path "HKLM:\System\CurrentControlSet\Control\Terminal Server" -Name "fDenyTSConnections" –Value 0}

Invoke-Command –Computername $comps –ScriptBlock {Enable-NetFirewallRule -DisplayGroup "Remote Desktop"}

By default, only members of the local Administrators group can connect via the RDP remotely. To allow RDP connections for non-admin users, just add them to the local Remote Desktop Users group.

You can add the desired users to the Remote Desktop Users locally by using the Local Users and Groups MMC snap-in (LUSRMGR.MSC).

how to enable rdp remotely

Or you can change RD Users group membership remotely using the PowerShell Remoting inside the Enter-PSSession. Use the following command to add the domain user ASmith to the local group:

net localgroup "remote desktop users" /add "contoso\asmith”

Alternatively, instead of the Enter-PSSession cmdlet, you can use another PS Remoting command Invoke-Command:

Invoke-Command -Scriptblock {net localgroup "remote desktop users" /add "contoso\asmith”

} -Computer Server1.contoso.com

How to Enable Remote Desktop over WMI?

If you want to enable RDP on a remote computer where WInRM is disabled (for example, on a regular computer with Windows 10), you can use the WMI PowerShell command.

To check if RDP access is enabled on the remote computer 192.168.1.90, run the command (see the value of the AllowTSConnections property):

Get-WmiObject -Class Win32_TerminalServiceSetting -Namespace root\CIMV2\TerminalServices -Computer 192.168.1.90 -Authentication 6

enable rdp remotely powershell

To enable RDP and add a Windows Firewall exception rule, run the following command:

(Get-WmiObject -Class Win32_TerminalServiceSetting -Namespace root\CIMV2\TerminalService

The post How to Enable Remote Desktop (RDP) Remotely? appeared first on TheITBros.

Fix: Unable to Find a Default Server with Active Directory Web Services Running

$
0
0

The error Cannot find the default server running Active Directory Web Services may appear when you import an ActiveDirectory module into your PowerShell session or when you run various cmdlets from that module. For example, when you transferring FSMO roles with Move-ADDirectoryServerOperationMasterRole, creating bulk AD users using New-ADUser, and all other cmdlets:

Import-Module ActiveDirectory

WARNING: Error initializing default drive: ‘Unable to find a default server with Active Directory Web Services running’

unable to find a default server with active directory web services running

Move-ADDirectoryServerOperationMasterRole -Identity dc01 –OperationMasterRole DomainNamingMaster,PDCEmulator,RIDMaster,SchemaMaster,InfrastructureMaster

CategoryInfo: ResourceUnavailable, ADServerDownException

ActiveDirectoryServer:1355,Microsoft.ActiveDirectory.Management.Commands.Move-ADDirectoryServerOperationMasterRole

unable to find default server with active directory web services running

This error occurs because your computer was unable to connect to Active Directory Web Services (ADWS) on the nearest domain controller.

The PowerShell AD module uses Active Directory Web Services on DC to communicate with ADDS. The TCP port 9389 on the domain controller must be accessible from your computer to communicate properly with ADWS.

Run the following command on any domain controller to find the nearest DC with the ADWS role:

Get-ADDomainController -Discover -Service ADWS

You can find a DC with the ADWS role in another AD site:

Get-ADDomainController -ForceDiscover -Discover -Service ADWS -NextClosestSite

To run AD PowerShell module cmdlets from your computer on a specific DC, use the Server parameter. For example:

New-ADUSer –Server DC02 …..

or:

Move-ADDirectoryServerOperationMasterRole -Server dc02 ……

unable to find a default server with active directory

Hint. Also, the ‘Unable to find a default server with Active Directory Web Services running’ error may appear if your computer joined to the Active Directory domain. In this case, you must specify the domain controller name in all PowerShell cmdlets using the parameter –Server {DC_FQDN/IP address}.

You can check the availability of port 9389 on the domain controller with the command:

Test-NetConnection DC01 -port 9389

If the command returns TcpTestSucceeded: False, it means the connection is blocked by the firewall, the ADWS service is not running, or the DC is down.

Connect to the desired DC and make sure the ADWS service is running on it. To do this, open the services.msc console, locate Active Directory Web Services and verify that it is in a Running state.

unable to find a default server with active directory web services

If the service is stopped, start it. If the service is running, restart the DC or restart the service with the PS command:

Restart-Service –name ADWS –verbose

powershell unable to find a default server with active directory web services running

ADWS is built into ADDS since Windows Server 2008 R2. If your Active Directory forest uses Windows Server 2003 R2/Windows Server 2008 domain controllers, this service must be installed separately.

ADWS is installed as an Active Directory Management Gateway Service package: KB969166 and KB968934. Learn more about ADMGS service requirements and installation here. ADMGS provides web-based management APIs on domain controllers running Windows Server 2003 SP2 and Windows Server 2008.

For the AD-PowerShell module cmdlets to work correctly, the ADWS service must be installed on at least one DC.

The post Fix: Unable to Find a Default Server with Active Directory Web Services Running appeared first on TheITBros.

Viewing all 91 articles
Browse latest View live