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

Using PowerShell Commands for SharePoint Online Management Shell

$
0
0
sharepoint online management shell cover

Most SharePoint administration functions are performed through the graphical portal interface. However, if you frequently perform the same tasks, you can automate them using PowerShell. Administrators can use PowerShell to manage various tasks in SharePoint. Microsoft provides separate sets of cmdlets for managing on-premises SharePoint and SharePoint Online. The number of PowerShell cmdlets for SharePoint Online is less than for the on-premises version of SharePoint.

Installing SharePoint Online Management Shell

To connect to SharePoint Online, you need to install SharePoint Online Management Shell. This PowerShell module allows you to manage SharePoint Online subscription in the Office 365. To install this module, PowerShell 3.0 (included in Windows Management Framework 3.0) must be installed on your computer. Download SharePoint Online Management Shell here:

https://www.microsoft.com/en-US/download/details.aspx?id=35588

Depending on your OS, you need to download 32 or 64 bit MSI distribution.

sharepoint online management shell

Installation of the module is quite simple. Just follow the instructions of the installation wizard.

sharepoint online management shell setup

After the installation is complete, you can start the SharePoint Online Management Shell from the Start menu, or import the SharePoint PowerShell module into your PoSh session:

Import-Module Microsoft.Online.SharePoint.PowerShell

sharepoint online management shell windows 10

SharePoint Online Management Shell Commands

A complete list of available commands of the module Microsoft.Online.SharePoint.PowerShell.dll can be displayed in the way like this:

Get-Command –Module Microsoft.Online.SharePoint.PowerShell

Alternatively, you can display all available SharePoint Online cmdlets using the command:

Get-Command *-SPO*

sharepoint online management shell commands

The most frequently used cmdlets are listed below:

  • Add-SPOUser
  • Connect-SPOService
  • Disconnect-SPOService
  • Get-SPOExternalUser
  • Get-SPOSite
  • Get-SPOSiteGroup
  • Get-SPOTenant
  • Get-SPOUser
  • New-SPOSite
  • New-SPOSiteGroup
  • Remove-SPOSite
  • Remove-SPOSiteGroup
  • Remove-SPOUser
  • Set-SPOUser
  • Set-SPOUser
  • Test-SPOSite
  • Upgrade-SPOSite

Now you can connect to SharePoint using the Connect-SPOService cmdlet. If you are connecting to SharePoint Online, you need to specify the tenant URL and admin account name.

Connect-SPOService –Url https://theitbrostenant.sharepoint.com –Credential admin@theitbrostenant.onmicrosoft.com

You can check the version of SharePoint as follows:

Get-SPFarm | Select BuildVersion

To list all site collection use the Get-SPOSite cmdlet.

sharepoint online management shell console

Using the Get-Member cmdlet, you can define the properties and methods of any object. For example, using the following command you can see all the properties of the SPSite object:

Get-SPSite | Get-Member

To remove a site collection, use the Remove-SPOSite cmdlet

Remove-SPOSite -Identity theitbrostenant.sharepoint.com/sites/SiteCollectionName –NoWait

To create multiple sites from a CSV file in the following format:

Name,URL,Owner,StorageQuota,ResourceQuota,Template
First Site,https://theitbrostenant.sharepoint.com/sites/site1,user1@theitbros.com,1024,300,STS#0
Corporate Blog, https://theitbrostenant.sharepoint.com/sites/blog,user2@theitbros.com,512,100,BLOG#0

Use the following script:

Import-Csv .\SitesToAdd.csv| % {New-SPOSite -Owner $_.Owner -StorageQuota $_.StorageQuota -Url $_.Url -NoWait -ResourceQuota $_.ResourceQuota -Template $_.Template -Title $_.Name}

Get the list of groups:

Get-SPOSite | ForEach-Object {Get-SPOSiteGroup -Site $_.Url} |Format-Table

Get a list of all users:

Get-SPOSite | ForEach-Object {Get-SPOUser -Site $_.Url}

Add new Site Collection administrator:

Set-SPOUser -Site {Corporate Blog} -LoginName root@theitbros.com -IsSiteCollectionAdmin $true

To remove a user from the Site Collection Administrator group:

Remove-SPOUser -LoginName root@theitbros.com -Site {Corporate Blog}

Available templates can be viewed with the command:

Get-SPWebTemplate

List of installed components:

Get-SPFeature -Limit ALL | Where-Object {$_.Scope -eq "SITE"}

List of available site templates:

Get-SPWebTemplate | where {$_.Title -match "business"}

List of running SharePoint services:

Get-Service | Where-Object {$_.DisplayName -like "Sharep*"}

Check the content database for errors:

Test-SPContentDatabase -name WSS_Content –webapplication http://blog

The post Using PowerShell Commands for SharePoint Online Management Shell appeared first on TheITBros.


Managing Office 365 Using Azure Active Directory Module for Windows PowerShell

$
0
0
azure AD module for windows powershell

The Office 365 platform includes a PowerShell module that allows you to manage Office 365 organization settings, configure users and licenses from the Command prompt. As with Exchange, there are several things that you can’t simply perform from the GUI in Office 365. To connect to Office 365 from PoSh CLI, you need to install additional software.

As a workstation, only 64 bit versions of Windows 10, 8.1, Windows 7 SP1 or Windows Server 2016/2012 R2 / 2012 / 2008R2 with .NET Framework version not lower than 3.5.1 can be used.

  1. Download and installMicrosoft Online Services Sign-In Assistant (https://www.microsoft.com/en-us/download/details.aspx?id=41950)
  2. Install the module Azure Active Directory Module for Windows PowerShell from the NuGet or PowerShellGallery repository using the command:
    Find-Module -Name MSOnline | Install-Module -Force
    

    (https://www.powershellgallery.com/packages/MSOnline/1.1.183.8)
    windows azure active directory module for windows powershell

Now you can connect to your Office 365 subscription in Azure Active Directory.

Run the PowerShell console and import the module into your session:

Import-Module MSOnline

If you are using Multifactor Authentication (MFA), run the command

Connect-MsolService

In the Azure Active Directory PowerShell window that appears enter the username (use full UPN – User principal name) and the password for Office 365, and enter the confirmation code from your phone.

Note. Your account must be a member of the administrative role of Office 365.

azure active directory module for windows powershell

For usual authentication by the username and password, first save the Office 365 administrative credentials to a PoSh variable:

$o365Credential = Get-Credential

And then connect to your subscription with the command:

Connect-MsolService -Credential $o365Credential

Upon completion of the command, a connection with your Office 365 tenant will be established.

The list of accepted domains in your organization can be displayed by the command:

Get-AcceptedDomain

List the available licenses in your account:

Get-MsolAccountSku

The cmdlet returns all SKUs belonging to the organization. You will receive detailed licensing information, find out how many licenses are available and how much is used.

Now display the list of Office 365 users:

Get-MsolUser

As you can see, the list indicates whether the license is assigned to the user or not.

office 365 powershell module

You can check the user license type:

GetMsolUser –UserPrincipalName user1@theitbros.com

You can create a new user using the New-MsolUser cmdlet:

New-MsolUser -UserPrincipalName andyhornet@theitbros.onmicrosoft.com -DisplayName 'Andy Hornet' -FirstName Andy -LastName Hornet' -LicenseAssignment theitbros:ENTERPRISEPACK -UsageLocation US

If you do not specify the -Password argument when creating a user, a random password will be generated and assigned for the user.

To set a password that will never expire for Office 365 user (not recommended), you should run the following command:

Get-MSOLUser –UserPrincipalName andyhornet@theitbros.onmicrosoft.com| Set-MsolUser -PasswordNeverExpires $true

For the convenience for choosing a specific license, use this command:

$LicenseSKUid = Get-MsolAccountSku | Out-GridView -Title 'Select a license type’-OutputMode Single | Select-Object -ExpandProperty AccountSkuId

List the users who are not assigned a license:

$Users = Get-MsolUser -All -UnlicensedUsersOnly

Assign usage location for the users that was found:

$Users | Set-MsolUser -UsageLocation US

Now you can assign licenses to all selected users:

$Users | Set-MsolUserLicense -AddLicenses $LicenseSKUid

The post Managing Office 365 Using Azure Active Directory Module for Windows PowerShell appeared first on TheITBros.

How to Install and Configure SNMP Service on Windows 10?

$
0
0
snmp service cover

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

How to Install SNMP Service in Windows 10?

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

Get-Service -Name snmp*

Most likely the service has not been installed yet.

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

snmp service

You can also install SNMP service using PowerShell:

Enable-WindowsOptionalFeature -online -FeatureName SNMP

Configure SNMP on Windows 10 Machine

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

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

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

microsoft snmp service windows 10

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

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

snmp service windows 10

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

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

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

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

snmp service windows

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

Save the changes and restart the SNMP service.

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

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

Changing Local and Active Directory User Password Using PowerShell

$
0
0
change local active directory user

The administrator can change the password of the local users on the computer using the Local Users and Groups (lusrmgr.msc) graphic snap-in. To change the password of an AD domain user, the Active Directory Users and Computer (ADUC) GUI console is mainly used. However, in some cases, the administrator may need to change the user’s password from the command prompt or within some script. In this article we will show how to manage user’s passwords (both local and domain) using PowerShell.

How to Change Active Directory User Password with PowerShell?

To change an Active Directory user password, use the Set-ADAccountPassword cmdlet from the Active Directory module for Windows PowerShell. Of course, the user who runs the cmdlet must have domain administrator privileges or should be delegated to reset passwords of an AD users.

Before using the Set-ADAccountPassword cmdlet, you must import this module into a PowerShell session:

Import-Module ActiveDirectory

The password in the computer’s memory should preferably be stored in a protected form, so you can ask the administrator to specify the password as follows:

$newPass=Read-Host "Enter the new user password" -AsSecureString

Enter the new password in the PowerShell console.

change local active directory user password

It is better to specify the AD account name in the form of samAccountname. For example, to change the password for user jkelly, run the command:

Set-ADAccountPassword jkelly -NewPassword $newPass

adaccount password

You can set a new user password directly inside the script code:

Set-ADAccountPassword jkelly–NewPassword (ConvertTo-SecureString -AsPlainText –String "St0ngPwd@d" -force)

If you want the user to change the password on the next login, perform the command:

Set-ADUser jkelly -ChangePasswordAtLogon $True

change password logon

You can reset the password for several users at once (assume that account names are stored in a plain text file user_to_reset.txt). Use this script:

Get-Content C:\PS\user_to_reset.txt | Set-ADAccountPassword -NewPassword $newPass -Reset

How to Change the Password for a Windows Local Accounts?

To change the passwords of local Windows users, you can use the ADSI (Active Directory Services Interface) API, which can be used to interact with Active Directory or with stand-alone computers.

Open the PowerShell command prompt and list the local user accounts on the current computer:

get-wmiobject win32_useraccount

change password active directory logon

You can also display a list of local users like this:

[adsi]$localPC = "WinNT://."

$localPC.Children | where {$_.Class -eq "user"} | ft name, description –auto

To reset a local user password, first select the user (in this example the local account name is ConfRoom):

[adsi]$user = "WinNT://./ConfRoom,user"

Set the password:

$user.SetPassword("newP@s32w02rd")

Additionally, you can request a password change at the next login:

$user.Put("PasswordExpired",1)

It remains to save the changes to the user account:

$user.SetInfo()

set password active directory user

The same commands can be used to change the user’s password on remote computers. It is enough to replace [adsi]$user = ″WinNT://./ConfRoom,user″ with the command [adsi]$user = ″WinNT://RemotePCName/ConfRoom,user″.

To set the same password for all local users, use the following script:

$NewPass = "ThisIsNewP@33"

$localusers = Get-WmiObject -Class Win32_UserAccount -ComputerName $env:COMPUTERNAME -Filter LocalAccount='true' | select -ExpandProperty name

foreach ($user in $localusers)

{

$user

([adsi]"WinNT://$env:COMPUTERNAME/$user").SetPassword("$NewPass ")

}

The post Changing Local and Active Directory User Password Using PowerShell appeared first on TheITBros.

Viewing Active Directory Groups Using DSGet Group

$
0
0
dsget active directory group

The dsget utility can be used to view various information about Active Directory catalog objects. In this article we will show how to use the dsget group command to list info about different groups in the AD domain.

To use the dsget command, the Microsoft Windows Administration Tools Pack – Adminpak.msi (for Windows XP/Windows Server 2003 and below) or Active Directory Domain Services (AD DS) Tools from the Remote Server Administration Tools (RSAT) package (in modern versions of Windows) must be installed on your computer.

The dsget group command without parameters displays a list of all groups in the Active Directory domain (if there are a large number of groups in the domain, the command will run for a rather long time). To get the properties of a specific AD group, run the following command:

dsget group "CN=Domain Admins,CN=Users,DC=theitbros,DC=com"

dsget group active directory

The group name must be specified in the DistinguishedName (DN) format.

By default, the group DN and its description are displayed.

The full syntax and attributes available for the dsget group command is:

dsget group <GroupDN ...> [-dn] [-samid] [-sid] [-desc] [-secgrp]  [-scope] [{-s <Server> | -d <Domain>}] [-u <UserName>]  [-p {<Password> | *}] [-c] [-q] [-l] [{-uc | -uco | -uci}]  [-part <PartitionDN> [-qlimit] [-qused]]

For example, to find out the group SID, run:

dsget group "CN=Domain Admins,CN=Users,DC=theitbros,DC=com" -sid

To check the group type: Security (yes) or Distribution (no), run:

dsget group "CN=Domain Admins,CN=Users,DC=theitbros,DC=com" -secgrp

To determine group membership allows another dsget group command optional parameters: -Members and -Memberof. The -Members parameter indicates which users and groups are included to this group, and the -Memberof parameter — which groups this group belongs to. Suppose you want to list current members of the Domain Admins group. Run the command:

dsget group "CN=Domain Admins,CN=Users,DC=theitbros,DC=com" –members

dsget group ad

To display a complete list of users, including nested groups (recursively), run:

dsget group "CN=Domain Admins,CN=Users,DC=theitbros,DC=com" –members -expand

Similarly, you can get a list of groups in which this group consists:

dsget group "CN=Domain Admins,CN=Users,DC=theitbros,DC=com" –memberof

-expand

As you can see, the last two commands, when displaying the list of users/groups, return them in DN format, which is not very convenient. Therefore, to get usernames (or other fields) you need to use the command in conjunction with dsget user:

dsget group "CN=Domain Admins,CN=Users,DC=theitbros,DC=com" -members | dsget user -samid -upn -desc

ds get group active directory

As you remember, the group name for the dsget group command must be specified in the distinguishedName format. In order not to specify the DN of the group, you can use the dsget group command together with the dsquery command. For example, to get a list of users in the ‘Domain Admins’ group and export it to a text file, run the command:

dsquery group -samid "Domain Admins" | dsget group -members > c:\ps\exportgoupmembers.txt

As you can see, now you do not need to specify the group DN.

If you do not know the exact name of the group, you can specify only part of the name. The wildcard character *is used. For example, you want to find all the groups whose names begin with NY:

dsquery group -name NY* | dsget group -dn -scope -secgrp

In a similar way, you can list, for example, all email addresses of users who consist in a group and save the list to a CSV file:

dsquery group -samid "Domain Admins" | dsget group -members | dsget user -email >admin_emails.csv

The post Viewing Active Directory Groups Using DSGet Group appeared first on TheITBros.

How to Get List of Installed Programs in Windows 10?

$
0
0
list installed apps windows 10

In this simple guide we will show you two different ways of how to get list of installed programs in Windows 10, 8 or Windows 7 using built-in command line tools. When it may be necessary? For example, the list of all installed programs can be useful when you re-install Windows, audit installed software in inventory scenarios or when you want to find the unwanted programs.

How to Get Windows 10 Installed Programs List?

The easiest way to get a complete list of applications with icons is to press the Win + R key combination and enter the command: shell: AppsFolder.

However, you cannot export this program list to a text file.

how to get a list of installed programs

Let’s see how to get a list of installed programs using Windows command prompt and using PowerShell.

How to Get a List of Installed Programs by Using Command Prompt Utility WMIC?

The list of programs that installed in the system can be obtained by using WMIC command line utility, that can access the WMI namespace. Run cmd.exe as an administrator and run the following command:

wmic product get name,version

List of Installed Programs Windows 10

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

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

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

windows 10 list of installed programs

After command execution, open file InstalledApps_* which is located in the folder C:\Dist. In this file in CSV format in addition to programs list will be specified the current computer name (it may be useful for further analysis). Open this file using any text editor (notepad.exe in our example).

As you can see, the resulting table displays the name and the version number of the installed apps.

get list of installed programs windows 10

How to get a list of installed programs in Windows 10 by using PowerShell?

Let’s see how to get a list using PowerShell! The list of programs that user sees in the section Programs and Features of the Control Panel is built on the base of the contents of the registry key HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall

The specified registry key contains only programs installed “for all users” of Windows.

windows 10 program list

Tip. For 32-bit application on 64-bit operating system additionally you need to get the contents of branch HKEY_LOCAL_MACHINE\SOFTWARE\Wow6432Node\Microsoft\Windows\CurrentVersion\Uninstall

If an application was installed in the “for this user” mode, then it should be present in the registry key:

HKCU\Software\Microsoft\Windows\CurrentVersion\Uninstall

Accordingly, to get a complete list of installed software, you will need to scan information from all three branches of the registry.

Let’s get the contents of branch HKLM:\Software\Wow6432Node\Microsoft\Windows\CurrentVersion\Uninstall\. Open PoSh console by pressing Win+R key and entering powershell. Then, run the following command:

Get-ItemProperty HKLM:\Software\Wow6432Node\Microsoft\Windows\CurrentVersion\Uninstall\* | Select-Object DisplayName, DisplayVersion, Publisher, Size, InstallDate | Format-Table -AutoSize

windows 10 programs list

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

To export a list of programs in text file (c:\docs\list-installed-programs.txt), you can use the command as follows:

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

The above method can only get a list of the Classical desktop Windows programs, but not the Modern applications from Windows Store 10.

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

get-appxpackage list

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

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

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

Compare-Object -ReferenceObject (Get-Content C:\Install\list-installed-programs.txt) -DifferenceObject (Get-Content C:\Install\list-installed-programs2.txt)

powershell compare object

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

Another way to get list of installed programs in Windows 10 – to use the Get-WmiObject cmdlet. Simply copy and paste next command:

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

how to find installed programs in windows 10

Get the List of Installed Software on Remote Computers Using PowerShell

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

Usually for remote inventory of remote computers we use the following PowerShell script (if this account doesn’t have permissions to connect remotely to a computer, the script will display a window for entering an account credentials for authorization on remote computers):

Function Get-InstalledApps

{

    [CmdletBinding()]

    param (

    [Switch]$Credential,

    [parameter(ValueFromPipeline=$true)]

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

    )




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




    process

    {  

        $ComputerName | Foreach {

        $Comp = $_

        if (!$Credential)

        {

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

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

            $SubKeys=$regkey.GetSubKeyNames()




            Foreach ($i in $SubKeys)

            {

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

                $ReadUninstall=$reg.OpenSubKey($NewSubKey)

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

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

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

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

            }

        }




        else

        {

            $Cred = Get-Credential

            $connect = New-Object System.Management.ConnectionOptions

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

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




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

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

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

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

            $inputParams.sSubKeyName = $key

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




            foreach ($i in $outputParams.sNames)

            {

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

                $inputParams.sSubKeyName = $key + $i

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

                    $inputParams.sValueName = $_

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

                    $outputParams.sValue

                }

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

            }

        }

     }

  }

}

To list installed programs on the current computer, run the command:

Get-InstalledApps

getting a list of installed programs

To get lists of installed software from several remote computers, run the following command:

Get-InstalledApps PCName1,PCName2,PCName3,PCName4

That’s all! Hope this article will be helpful!

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

Viewing Office 365 User Account Details Using Get-MsolUser

$
0
0
Get-MsolUser cover

In this article we’ll show you how to get a various information about Office 365 user accounts using the Get-MsolUser PowerShell cmdlet. The Get-MsolUser cmdlet allows you to view the properties of one or several Office 365 accounts, this is an analogue of the Get-ADUser cmdlet for on-premises Active Directory. The Get-MsolUser cmdlet is part of the Azure AD PowerShell module (MSOnline), which allows you to connect to your Office 365 subscription. Therefore, to use this cmdlet you must first download and install this module. You can download and install the MSOnline manually (exe/msi installer), or install it online from the PowerShell Gallery. To do this, just run the command in the PoSh console:

Find-Module -Name MSOnline | Install-Module -Force

Get-MsolUser

To connect to an Office 365 subscription, save your credentials to a variable:

$MSOCred = Get-Credential

In the window that appears, enter account’s credentials with the permissions to connect to your Office 365 tenant.

Get-MsolUser command

Now connect to your subscription with saved credentials:

Connect-MsolService -Credential $MSOCred

After connecting, run the command:

Get-MsolUser

This command will return a list of all Office 365 users. By default, the UPN, Display name and the isLicensed attributes are returned.

Get-MsolUser command PowerShell

To display information about a specific user, you can specify its UserPrincipalName. You can display all user attributes:

Get-MsolUser -UserPrincipalName "youraccount@o365.onmicrosoft.com”| Select-Object *|Format-List

using Get-MsolUser command

The user account contains a number of attributes that determine their properties, parameters and personal info (phone number, department, company, etc.). You can only request for a specific attributes:

Get-MsolUser -UserPrincipalName “youraccount@o365.onmicrosoft.com” | Select-Object UserPrincipalName, DisplayName, Department, UsageLocation

This list can be exported to a CSV file (convenient for opening in Excel):

Get-MsolUser | Select-Object UserPrincipalName, DisplayName, PhoneNumber, Department, UsageLocation| Export-CSV c:\ps\o365userlist.csv –NoTypeInformation

Below are some useful queries for getting data about Office 365 users using the Get-MsolUser cmdlet.

You can display all users of a specific department:

Get-msoluser | Where {$_.Department -eq “Sales Dept”}

Let’s display the list of users and licenses assigned to them:

Get-MsolUser | Where-Object {$_.isLicensed -like "True"} | FT DisplayName, licenses, islicensed

List of assigned license options:

(Get-MsolUser –UserPrincipalName ).Licenses[0].ServiceStatus

List of users without a license:

Get-MsolUser –UnlicensedUsersOnly

List of deleted account (useful if you accidentally delete an Office 365 account, when you urgently need to restore it):

Get-MsolUser -ReturnDeletedUsers | FL UserPrincipalName,ObjectID

List the time of the last password change for Office 365 users:

Get-MsolUser -All | select DisplayName, LastPasswordChangeTimeStamp

List the active (enabled) accounts:

Get-MsolUser -EnabledFilter EnabledOnly -ALL

List the disabled accounts:

Get-MsolUser -EnabledFilter DisabledOnly -ALL

Display a list of users who haven’t changed their passwords for more than 90 days:

Get-MsolUser | Where-Object { $.LastPasswordChangeTimestamp -lt (Get-Date).AddDays(-90)} | Select-Object DisplayName,UserPrincipalName,LastPasswordChangeTimestamp,Licenses,PasswordNeverExpires | Format-Table

The post Viewing Office 365 User Account Details Using Get-MsolUser appeared first on TheITBros.

How to Configure DHCP Conflict Resolution?

$
0
0
fix windows has detected an ip adress conflict

An IP address conflict occurs between two devices on the same LAN if both are assigned the same IP address. Than a conflict occurs on both devices (if they are running Windows family OSs), an error message appears:

Network Error

Windows has detected an IP address conflict

Another computer on this network has the same IP address as this computer. Contact your network administrator for help resolving this issue. More details are available in the Windows System event log.

In this case, you can find a record with EventID 4199 from the TCPIP source in the Event Viewer with the following text:

The system detected an address conflict for IP address 192.168.10.16 with the system having network hardware address 0A:1B:1A:BB:BB:BB. Network operations on this system may be disrupted as a result.

When an IP address conflict occurs, only the device that first appeared on the network has LAN access. On the second one there is no access to the IP network. Diagnosing an IP address conflict is quite a complicated and tedious task. As a rule, it is necessary to look at the port status on network switches in order to determine the MAC address of the device where a non-unique IP address is assigned.

DHCP server is used to automatically assign the IP addresses, and thus prevents the occurrence of IP address conflicts on the same network (it cannot issue the same IP address to different devices). However, using a DHCP server doesn’t guarantee you the absence of the appearance of IP conflicts in your LAN. For example, a new device may appear on your network with a static IP address specified in its settings (this could be a computer, sender, printer, etc.). This IP address may be included in a pool of dynamic IP addresses distributed by a DHCP server. Theoretically, a situation may arise when a DHCP server issues an IP address to a new client, the same IP as set on some device on the network. As a result, an IP address conflict will occur.

To avoid this situation, the DHCP server must check if this address is being used on a device on the same subnet before issuing an IP address to a new client.

In the DHCP server running on Windows Server 2016, there is a special option for checking IP address conflicts. To do this, open the DHCP management console, and open the properties of the IPv4 (or IPv6) node.

fixing windows has detected an IP address conflict

Click the Advanced tab. Note the option Conflict detection attempts. Here you can specify how many times the DHCP server should check the IP address before issuing for a conflict. You can specify a value from 0 to 5. By default, 0 is specified here—it means the DHCP server doesn’t check the IP address before issuing it.

error windows has detected an IP address conflict

If the ConflictDetectionAttempts parameter is greater than 0, the DHCP service, before issuing a free IP address to the client, pings the IP address to check whether it is available or not. Each additional attempt to detect a conflict delays the response of the DHCP server for 1 second (usually it’s not recommend to set this value greater than 2).

You can view the current IP address conflict resolution settings on a DHCP server using PowerShell, run the command:

Import-Module DHCPServer
Get-DhcpServerSetting

To change the settings for the ConflictDetectionAttempt parameter (for example, to 1), run the command:

Set-DhcpServerSetting -ConflictDetectionAttempts 1

You can also change these settings with the netsh command. View settings:

netsh dhcp server show detectconflictretry

Ping Retry setting for the current Server : 0

windows has detected an IP address conflict on windows server

To change the detectconflictretry setting, run:

netsh dhcp server show detectconflictretry 1

The post How to Configure DHCP Conflict Resolution? appeared first on TheITBros.


Manage and Disable Windows Defender Using PowerShell

$
0
0
windows defender

Windows Defender first appeared as an anti-virus utility for Windows XP. Since Vista it was built into all Microsoft OS as a protection against viruses, worms, trojans and other type of malicious software. In Windows 8 it was merged with another antivirus product—Microsoft Security Essentials, and now it is a full-featured antivirus software. Windows Defender is productive enough and has low system requirements. It can be updated from online Microsoft website or from an internal WSUS server. That allows you to use it not only on home computers, but also in SMB and enterprise corporate networks. In this article we will take a closer look on how to manage different settings and enable/disable Windows Defender using PowerShell.

Manage and Enable/Disable Windows Defender Using PowerShell

The main advantage of Defender is that it is easy to use, it’s already pre-installed in Windows 10 and 8.1, enabled by default and practically doesn’t need manual configuration.

windows defender status

Tip. At the moment, Windows Defender is a part of the only client side OS and not available in the current versions of Windows Server. Although, in a recent preview versions of Windows Server 2016, Windows Defender can be installed as a server feature (Install-WindowsFeature-Name Windows-Server-Antimalware).

In most cases, Windows Defender works well with the default settings, but sometimes user needs to change its behavior. A large number of settings available from the PowerShell console, through a special module Defender. It appeared first time in PowerShell 4.0 and designed specifically for Windows Defender management. This module contains 11 cmdlets, which we are reviewing today.

Windows Defender list of PowerShell cmdlets

To display a list of cmdlets contained in the module, run following command:

Get-Command -Module Defender

powershell module defender

  • Add-MpPreference—used to change Windows Defender settings;
  • Get-MpComputerStatus—allows you to get the status of anti-virus software on your computer;
  • Get-MpPreference—used to get Windows Defender scan and update options for;
  • Get-MpThreat—view the history of detected threats on your computer;
  • Get-MpThreatCatalog—allows you to get known threats from the definitions directory;
  • Get-MpThreatDetection—displays a list of active and recent threats detected on the computer;
  • Remove-MpPreference—allows you to remove Windows Defender settings or exceptions;
  • Remove-MpThreat—allows you to remove active threats from your computer;
  • Set-MpPreference—used to change scan and update options;
  • Start-MpScan—run a computer scan;
  • Update-MpSignature—anti-virus definition database update;
  • Start-MpWDOScan—launch Windows Defender offline scan;

To get full help on a specific cmdlet of the Defender module, use the command:

Get-Help cmdlet name –Full

If you need only examples of PowerShell commands, run:

Get-Help cmdlet name -Examples

Before using PowerShell cmdlets to control Windows Defender, it is advisable to check that the service is running. Run the command:

sc query Windefend

windefend

Get-MpComputerStatus allows you to display current status of Windows Defender: enabled options, virus definition date and version, last scan time and other.

Add-MpPreference

To display current Windows Defender settings you can use cmdlet Get-MpPreference, to change settings use – Set-MpPreference.

In the Windows Defender settings the IPS, removable disk check, email and some others checks are disabled by default. For example, you need to enable scanning of removable drives. Let’s get the current settings using command:

Get-MpPreference | fl disable*

As you can see, scan removable drives is disabled (DisableRemovableDriveScanning = True). Turn it on using following command:

Set-MpPreference -DisableRemovableDriveScanning $false

get-mppreference

By default, Windows Defender doesn’t check the archive files (RAR, ZIP, CAB), which can potentially contain malicious files. You can enable the checking of archive files by running:

Set-MpPreference -DisableArchiveScanning 0

After that, Windows Defender will start scanning all opened archive files in real time, as well as when scanning a disk.

Also, to change or remove the antivirus settings, you can use Add-MpPreference and Remove-MpPreference cmdlets. For example, let’s add some folders to the antivirus exclusion path:

Add-MpPreference -ExclusionPath C:\Video, C:\install

Display a list of path exceptions for Windows Defender:

Get-MpPreference | fl excl*

To exclude anti-virus scanning of certain processes, run the following command:

Set-MpPreference -ExclusionProcess "word.exe", "vmwp.exe"

To remove an exception for a particular directory:

Remove-MpPreference -ExclusionPath C:\install

set-mppreference

Windows Defender has a hidden function to protect unwanted programs (Potentially Unwanted Program—PUP, Potentially Unwanted Application—PUA). By default, it is accessible only in Windows 10 Enterprise edition, but with the help of the following command you can enable PUP/PUA protection in any Windows 10 edition:

Set-MpPreference -PUAProtection 1

After you turn on protection, when you try to launch or install potentially unwanted programs on your computer, you will receive the following notification from Defender in Windows 10.

Windows Defender took action

Your settings caused Windows Defender Antivirus to block an app that may potentially perform unwanted actions on your device.

windows defender took action

Using UpdateSource Argument

To start the antivirus signature update, you can use command Update-MpSignature. By default, Windows Defender updates with standard computer settings, but using UpdateSource argument let you to specify where exactly you want to take the virus definition updates.

The following sources are available:

  • MicrosoftUpdateServer
  • MMPC Microsoft Malware Protection Center;
  • FileShares
  • InternalDefinitionUpdateServer — internal WSUS server

To update antivirus from file share, at first you need to download necessary definition update files from https://www.microsoft.com/security/portal/definitions/adl.aspx and place them into shared network folder on a file server in your network. Then you have to specify that Windows Defender should be updated from a network shared folder (use UNC path):

Set-MpPreference -SignatureDefinitionUpdateFileSharesSources \\DESKTOP-V20E3PO\Updates

To run virus update and malware definitions manually:

Update-MpSignature -UpdateSource FileShares
Update-MpSignature

powershell update mpsignature

In some cases, after receiving an incorrect update, Windows Defender may not work correctly. In this case, it is recommended to reset the current thread definition databases and reload them from source:

"%PROGRAMFILES%\Windows Defender\MPCMDRUN.exe" -RemoveDefinitions -All
"%PROGRAMFILES%\Windows Defender\MPCMDRUN.exe" –SignatureUpdate

To perform antivirus scanning of your computer use the Start-MpScan cmdlet. With ScanType argument, you can choose one of three scan modes:

  • FullScan — scan is performed for all files on your computer, as well as the system registry and and currently running apps;
  • QuickScan — analysis of only those areas that are most likely may be infected by malware (registry,active RAM, system folders);
  • CustomScan — user selects the folders and drives to be scanned.

For example, run a custom scan for check system folder “C:\Program Files”:

Start-MpScan -ScanType CustomScan -ScanPath ”C:\Program Files”

powershell start mpscan

All Defender module cmdlets can be performed both for the local and remote computers. To connect to remote computer you need to use CimSession option. For example, to get the date of the last scan from the remote computer with hostname lnd_wks21 run the following commands (WimRM must be enabled):

$session = NewCimSession -ComputerName lnd_wks21
 Get-MpComputerStatus -CimSession $session | fl fullscan*

Disable Windows Defender using PowerShell

If you want to disable Defender real-time protection:

Set-MpPreference -DisableRealtimeMonitoring $true

To completely disable Windows Defender on a computer use the command:

New-ItemProperty -Path “HKLM:\SOFTWARE\Policies\Microsoft\Windows Defender” -Name DisableAntiSpyware -Value 1 -PropertyType DWORD -Force

powershell newitemproperty

The post Manage and Disable Windows Defender Using PowerShell appeared first on TheITBros.

How to Run PowerShell Script on Remote Computer?

$
0
0
windows powershell

The functionality of remote command execution in PowerShell is called PowerShell Remoting (appeared in PowerShell 2.0) and is 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, temporary or permanent connection. In this article, we will take a look at several examples of using PowerShell to run script on remote computer.

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 following command:

get-service winrm

run powershell script on remote computer in windows

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

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

Enter-PSSession Server1

The PoSh CLI view will change. At the beginning of the line there will be present the name of the remote computer to which you are connected via WinRM. After the 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 PoSh version and modules.

To end an interactive session run the command:

Exit-PSSession

run powershell script on remote computer windows

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

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 obtain background job information, use the Receive-Job cmdlet.

how to run powershell script on remote computer on windows

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

how to run powershell script on remote computer windows

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

You can save the list of computers in a text file and remotely execute the PS script on all computers:

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

By default, it sends the PS1 script to 32 remote computers from the list at the same time. If there are more than 32 computers, then PoSh monitors the execution status of the script on the first 32 computers, and 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.

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

How to Remotely Enable Remote Desktop (RDP) Using PowerShell

$
0
0
windows powershell

The easiest way to enable Remote Desktop RD on the Windows OS family is to use the GUI. To do this, 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 RD. You can usually ask user for this (need administrator privileges), or local technical support. However, what to do if there is no one in the remote office who could enable the Remote Desktop locally? By default, remote desktop is disabled in both desktop versions of Windows and in Windows Server.

powershell enable remote desktop

If you want to remotely enable Remote Desktop (RDP) on the remote host (server or computer), but you have not access to the local device console, we will show you how to do it by using PowerShell. To do this, the WinRM service (Windows Remote Management) must be enabled 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 RD 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 Firewall must be disabled or the rules that allow remote access through PowerShell Remoting should be enabled.

Enable Remote Desktop Remotely Using PowerShell

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

Enter-PSSession -ComputerName server.domain.local -Credential domain\administrator

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 machine. Run the command:

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

powershell enable rdp

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"

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

netsh advfirewall firewall add rule name="allow RemoteDesktop" dir=in protocol=TCP localport=3389 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 from your computer, you can check that TCP 3389 port on the remote host has become available. 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 rdp remotely powershell

This means that RDP on the remote host is enabled and you can establish a remote desktop connection using mstsc client.

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

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 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 remote desktop via powershell

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

(Get-WmiObject -Class Win32_TerminalServiceSetting -Namespace root\CIMV2\TerminalServices -Computer 192.168.1.90 -Authentication 6).SetAllowTSConnections(1,1)

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

Changing Active Directory krbtgt Account Password

$
0
0
krbtgt

Krbtgt user account is automatically created when promoting a new Active Directory domain. However, many AD administrators do not have sufficient knowledge of this account, which is very important from security point of view and the entire domain operation. Let’s try to fix it!

The krbtgt account with RID 502 is created in the Users container when the first domain controller is installed. This account is disabled and added only to two AD security groups: Domain Users and Denied RODC Password Replication Group. You cannot change the name of this account, enable it, or delete. This account is key to the operation of the KDC and Kerberos services in the AD domain.

The KDC service (Kerberos Distribution Center) is running on each domain controller AD, which processes all requests for Kerberos tickets. To create a secret key that is used to encrypt and decrypt TGT tickets (issued by all KDCs in the domain), the password for the krbtgt account is used.

krbtgt

In most cases, the krbtgt account password does not change from the moment of AD deployment and if the hash of this password falls into the hands of a hacker (for example, using mimikatz or similar utilities), he can create his own Golden Ticket Kerberos, bypassing the KDC and authenticating to any service in the AD domain using Kerberos.

Note. The hash of the krbtgt account password is not stored on the Read-Only Domain Controller (RODC) domain controllers, since each RODC has its own krbtgt account.

You can get information about the krbtgt account and the date of the last password change using PowerShell:

Get-AdUser krbtgt -property created, passwordlastset, enabled

krbtgt account

In our example, you can see that the krbtgt password has not changed since the creation of the AD domain.

For security reasons and to counter an attack of the type Golden Ticket Attack, you need to periodically change the password of the domain account krbtgt (once a year and when any domain administrator leaves your company). You need to change the password twice (with a delay sufficient to perform replication in the entire domain), because the current and previous password of the krbtgt account is stored in the domain. Even if the attackers issued the Golden Ticket with a long period of validity, after changing the password krbtgt, this ticket will become useless.

Note. When you raise the functional level of the domain (for example, from Windows Server 2012 R2 to Windows Server 2016), the password of the krbtgt account changes automatically.

You can change the krbtgt password as for any regular user through the ADUC snap-in (Reset Password), or you can use a ready PowerShell script

Reset the krbtgt account password/keys (https://gallery.technet.microsoft.com/Reset-the-krbtgt-account-581a9e51), which not only changes the account password, but additionally launches and tracks the replication of this password in the domain.

krbtgt service

Use a strong password for krbtgt!

If you make a second change of the krbtgt account password during replication delays, you may face problems with some domain services (for example, Exchange). To minimize risks after changing the krbtgt password, you need to restart the Kerberos Key Distribution Center service on all domain controllers manually via the services.msc console (select the Kerberos Key Distribution service and click “Restart”).

service name krbtgt

Or (much easier), restart the KDC service using PowerShell:

$DCs=Get-ADDomainController
Get-Service KDC -ComputerName $DCs | Restart-Service

The post Changing Active Directory krbtgt Account Password appeared first on TheITBros.

How to Map a Network Drive in Windows 10?

$
0
0

In Windows you can connect any SMB network shared folder located on a remote computer or server as a mapped drive. In this way, you connect a NAS network drive, or a USB flash drive connected to your home router. The mapped network folder is assigned a separate drive letter, which can be accessed through Explorer, file managers and all apps. You can map a network drive from the Windows GUI, cmd, or PowerShell.

How to Map a Network Drive in File Explorer?

To map a network folder from the Windows File Explorer, locate a shared folder, right-click on it and select “Map network drive”.

map network drive windows 10

You need to specify the drive letter that you want to assign to the folder (Drive) and whether you need to reconnect the drive at the next login (Reconnect at sign-in).

map drive windows 10

Mapped drives are displayed in File Explorer and contain the path to the network shared folder in addition to the drive letter.

windows network drive

Using Net Use to Map Network Drive

If you know the full UNC path to the share network directory you want to mount as a separate drive, you can use the NET USE command.

NET USE general syntax:

net use <drive:> <path>
  • Drive: – drive letter to be assigned to a shared folder;
  • Path – UNC path to network folder.

All available parameters of the net use command can be displayed as:

Net use /?

net use map drive

NET USE

[devicename | *] [\\computername\sharename[\volume] [password | *]]

[/USER:[domainname\]username]

[/USER:[dotted domain name\]username]

[/USER:[username@dotted domain name]

[/SMARTCARD]

[/SAVECRED]

[/REQUIREINTEGRITY]

[/REQUIREPRIVACY]

[[/DELETE] | [/PERSISTENT:{YES | NO}]]

To connect the \\lon-fs01\docs\sales folder and assign a drive letter U, run the command:

net use U: \\lon-fs01\docs\sales

windows 10 map drive

If you need to authenticate to access the shared folder, a window will appear in which you need to prompt your credentials to access. If you don’t want to input credentials on every access, you can specify the user name and password using the command:

net use U: \\lon-fs01\docs\sales /user:your_user_name Your_P@ssw0rd

By default, the connected drive is not permanent and disappears when the computer is restarted. If you want to automatically map a drive the next time the user logs in, you need to use the /persistent:yes option.

The complete command for connecting a permanent disk looks like this:

net use U: \\lon-fs01\docs\sales /user:your_user_name Your_P@ssw0rd /persistent:yes

If there are several users on the computer, you can automatically map a shared folder to all users at login. To do this, create a text file map_drive.bat with the following code:

net use Z: /delete
net use Z: “\\PC1\docs\sales" /user:PC1\pc1_user_name P@ssw0rdd

Where:

  • PC1 – the name of the remote computer where the network folder is stored;
  • pc1_user_name – the local user on a PC1 with a permissions to access folder.

It remains to copy your bat file to the directory C:\ProgramData\Microsoft\Windows\Start Menu\Programs\Startup. As a result, this script will run at of each user login and map a network drive.

command to map network drive

To unmap a network drive, use the parameter /delete.

To disconnect a previously connected mapped drive U:, use the command:

net use U: /delete

map folder to network driveTo remove all mapped drives, specify *.

net use * /delete

Network Drive Mapping with PowerShell

You can also manage mapped drives with PowerShell (PowerShell version 3.0 or newer).
To permanently map a drive using PowerShell under the a_smith account, run the command.

New-PSDrive -Name Z -PSProvider FileSystem -Root “\\lon-fs01\docs\sales” -Credential theitbros\a_smith –Persist

windows 10 map a network drive

This will open a window in which you need to specify the password of the specified account to access the network folder.

To display a list of mapped network drives, use the command:

Get-PSDrive -PSProvider FileSystem | Select-Object Name, DisplayRoot | Where-Object {$_.DisplayRoot -ne $null}

how to map a network drive

In PowerShell 5.0+, you can use another cmdlet—New-SmbMapping:

New-SmbMapping -LocalPath Z -RemotePath “\\lon-fs01\docs\sales” -Persistent:$true

In this article, we looked at how to use mapped network drives in Windows 10 using NET USE and PowerShell.

The post How to Map a Network Drive in Windows 10? appeared first on TheITBros.

PowerShell: Switch Statement Usage

$
0
0
Switch Statement Usage in PowerShell

Usually, an if-else construct is used to test conditions in PowerShell scripts. If you need to immediately check several conditions instead of doing complex constructions with if-else, it is much easier to use the switch statement.

The syntax of the construction with the Switch operator is looks like follow:

Switch -options (value) { 
Pattern 1 {action1} 
Pattern 2 {action2} 
Pattern x {action3}
default { defaultaction}}

The Switch statement compares the value of each item in turn with each condition (pattern), and if it matches, it performs the action specified for this condition.

PowerShell: Switch operator

Let’s look on an example of a simple PowerShell script that checks the value of the var1 variable against one of the following values.

$var1 = 2
Switch ($var1) { 
1 {write-host ″Action one″} 
2 {write-host ″Action two″} 
3 {write-host ″Action three″} 
}

powershell switch statement

In this example, the value of the var1 variable matches the second condition, so the ″Action two″ is displayed.

In the example above, if the value of $var1 = 0, the Switch statement doesn’t perform any actions. You can create a default action that applies when none of the conditions are met. To do this, use the Default key.

$var1 = 0
Switch ($var1) { 
1 {write-host ″Action one″} 
2 {write-host ″Action two″} 
3 {write-host ″Action three″}
Default {″No action″; exit}
}

The Switch statement sequentially checks all conditions. If after a match with a condition you want to leave the Switch structure, use the Break operator.

For example:

1 {write-host ″Action one″;break}

You can check the value of a certain object using the Switch statement. For example, check the status of the DNS Client service using the cmdlet Get-Service, and if the service is stopped, we will start it. If the service is in the Stopping state, the script will restart it (let it be the default action).

switch (Get-Service | where {$_.name -eq 'Dnscache'})
{
{$_.status -eq 'Running'} {'DNS client service is running'}
{$_.status -eq 'Stopped'} {'DNS client service is stopped'; Start-Service Dnscache }
Default { Restart-Service Dnscache; {'DNS client service restarting' }; exit}
}

powershell switch

One of the most useful features of the switch statement is the built-in ability to work with regular expressions with the -regexp key.

For example, using a regular expression, you can verify that the following line begins or ends with a specific character:

switch -regex ("theitbros")
{
'^t' { "Begins with t" }
's$' { "ends with s" }
'^a' { "Begins with a" }
}
Begins with t
ends with s

powershell switch example

Also in the scripts, the following PowerShell switch statement parameters may be useful:

  • Wildcard — you can use wildcards in the expression (*,?, [asd]);
  • Exact — exact, case-insensitive comparison of the string;
  • CaseSensitive — the case sensitive check (if the condition is not a string, this parameter is ignored);
  • File — input data is taken from a file. For example:
switch -file c:\ps\test.txt
{
'cat' {write-host 'I found a cat'}
'dog' { write-host 'I found a dog'}
'bird'{ write-host 'I found a bird'}
Default {write-host ‘nothing found’}
}

The post PowerShell: Switch Statement Usage appeared first on TheITBros.

Using WhatIf Parameter in PowerShell

$
0
0
WhatIf Parameter in PowerShelll

The -WhatIf parameter in PowerShell scripts is typically used to avoid accidental changes to managed objects. Adding the -WhatIf parameter to the PowerShell command will display the objects to be changed by this command and the changes made. At the same time, no changes are actually made.

For example, you decided to delete some user accounts in the Active Directory domain according to certain criteria using the PowerShell script. To make sure that the PowerShell script deletes only the users you expect, you can add the –WhatIf parameter to the command.

With WhatIf, you can make sure that the changes made to these objects meet your expectations without worrying about changing these objects.
The -WhatIf parameter is a switch parameter and is found in many PowerShell cmdlets.

You can list the PowerShell cmdlets that support the –WhatIf parameter with the command:

Get-Command | where { $_.parameters.keys -Contains "WhatIf"}

powershell whatif

The -WhatIf parameter is added at the end of the PowerShell command. The presence of this cmdlet indicates that this command is executed in a test mode, and no changes will be made, but the list of objects will only be displayed on the PoSh console screen.

For example, the following command will select all inactive computers from the beginning of the year in the Active Directory domain and delete them. If, before deleting objects in AD, you want to see the list of computers to be deleted, add the –WhatIf switch to the command.

Search-ADAccount -AccountInactive -ComputersOnly -DateTime ‘1/1/2019’|Remove-ADComputer -WhatIf

The previous command will print the following text to the console:

What if: Performing the operation “Remove” on target “CN=us-PC1,OU=Workstations,OU=NY,DC=theitbros,DC=com”.

powershell whatif parameter

Together with the –WhatIf parameter, the –Confirm parameter is often remembered, which will ask you to confirm that you really want to perform this operation before performing an action. When using this switch, the command asks for confirmation for each action before continuing execution (by default, the mode –Confirm:$true is present in all PowerShell cmdlets starting with Clear-, Disable-, Dismount-, Move-, Remove-, Stop-, Suspend-, Uninstall-.

The code of the above PowerShell script with the –Confirm switch might look like this:

Search-ADAccount -AccountInactive -ComputersOnly -DateTime ‘1/1/2019’|Remove-ADComputer -confirm

use powershell whatif parameter

As you can see, a confirmation request has appeared:

Are you sure you want to perform this action?

Performing the operation “Remove” on target …

Usually, the –WhatIf parameter is used when testing and configuring PowerShell scripts, and in ready-made PoSh scripts, if you want to receive confirmation of a change, the –Confirm parameter is used.

The post Using WhatIf Parameter in PowerShell appeared first on TheITBros.


Using GPUpdate to Update Group Policy Settings

$
0
0
Using GPUpdate command

After changing any Group Policy setting using the local GPO editor (gpedit.msc) or domain policy editor (gpmc.msc), the new policy setting is not immediately applied to the user/computer. You can wait for automatic updating of GPO (up to 90 minutes), or you can update and apply policies manually using the GPUpdate command. The GPUpdate command is used to force the update of the computer and/or user group policy settings.

Note. The secedit/refreshpolicy command was used in Windows 2000 to manually refresh group policies. In the following versions of Windows, it was replaced by the GPUpdate utility.

The full syntax of the gpupdate tools looks like this:

Gpupdate [/Target:{Computer | User}] [/Force] [/Wait:<value>] [/Logoff] [/Boot] [/Sync]

gpupdate

When you run the gpupdate command without parameters, only new and changed user and computer policy settings are applied.

gpupdate command

Updating policy…

Computer Policy update has completed successfully.

User Policy update has completed successfully.

You can only update user or computer policies using the /target option. For example,

  • gpudate /target:user
  • gpupdate /target:computer

To enforce the update of group policy settings you can use the GPUpdate /force command.

What is the Difference Between GPUpdate and GPUpdate /force?

The gpupdate command applies only changed policies, and the GPUpdate /force command reapplies all client policies—both new and old (regardless of whether they have been changed).

In most cases, you need to use gpupdate to update the policies on the computer. In large Active Directory domains, frequent use of the /force switch when updating GPOs places a heavy load on domain controllers (because computers re-request all policies targeted at them or users).

As we said earlier, group policies are updated automatically every 90 minutes or during computer startup. Therefore, in most cases you shouldn‘t use the gpupdate /force command (especially in various scenarios) due to the high load on client computers and domain controllers.

You can add a delay (up to 600 seconds) before updating policies using the /wait parameter:

Gpupdate /wait:30

Because some user policies cannot be updated in the background, but only at a user logon (installation of programs, folder redirection, etc.), you can log off for the current user with the command:

gpupdate /logoff

Some computer policy settings can only be applied at startup, so you can initiate a computer reboot using the /Boot parameter:

gpupdate /Boot

The /Sync parameter specifies that the next policy application should be performed synchronously. Active policy enforcement occurs when a computer is restarted or when a user logs on.

Invoke-GPUpdate cmdlet has been added to PowerShell 3.0, which can be used to update policies on remote computers. For example, the following command will launch a remote group policy update of on the computer PC1:

Invoke-GPUpdate -Computer PC1 -Force

You can force policy updates on all computers in the specified Active Directory OU using the commands:

$Comps = Get-AdComputer -SearchBase "OU=Computers,OU=Mun,OU=DE,DC=theitbros,DC=com" -Filter *

Foreach ($Comp in $Comps) {invoke-gpupdate -Computer $Comp.Name}

The post Using GPUpdate to Update Group Policy Settings appeared first on TheITBros.

PowerShell Function Parameters: How to Add?

$
0
0
Adding Parameters to PowerShell Function

When developing your PowerShell functions, sometimes you need to put some input values to your functions, such as a file name, string, or any other value. In PowerShell, there are two ways to pass parameters to functions: through the $Args variable and by setting formal parameters.

Passing Parameters to the PoSh Function Through the $Args Variable

Let’s look at the simplest PowerShell function example that displays some text on screen:

Function TestPoShArgs { 

“I love PowerShell”

}

Add the $Args variable to the function:

Function TestPoShArgs { 

“I love PowerShell $Args”

}

And run it with a few parameters:

TestPoShArgs One Two Three

powershell function parameters

In this example, we passed 3 parameters to the function input, separated by spaces. At the output of the function, they also appear with spaces. You can change the output delimiter using the special variable $OFS.

Function TestPoShArgs { 

$OFS=","

“I love PowerShell $Args”

}

TestPoShArgs One Two Three

Now the returned values in the function results are separated by commas.

powershell function parameter

The $Args variable is a simple PowerShell array and you can access its individual values by sequence numbers (starting from 0).

Function TestPoShArgs { 

"Total args number: $($Args.Count)" 

For($i=0; $i -lt $Args.Count; $i++) {$Args[$i]}

}

TestPoShArgs One Two Three Four

As you can see, the function calculated the number of arguments that were passed to it and listed them line by line.

powershell function param

Passing Formal Parameters to PowerShell Functions

As in other programming languages, you can set a number of formal parameters for PowerShell functions. During the function execution, the values of these parameters will be replaced by the arguments passed by user.

Formal parameters are passed in parentheses after the function name:

Function TestPoShParam ($curwidth, $curheight) { 

 $summ=$curwidth+$curheight

 “Current summ $summ"

}

TestPoShParam 800 600

This function accepts two parameters as input and displays their sum.

powershell function arguments

When specifying function arguments, you can specify parameter names; in this case, their order doesn’t matter:

TestPoShParam -curheight 800 -curwidth 800

By default, PowerShell itself tries to determine the type of value in the parameter. But you can specify the type of the variable manually. For example:

Function TestPoShParam ([int] $curheight_meter, [string] $curname) {

“The mountain " + $curname + " is about " + ($curheight_meter/1000) +" km”

}

TestPoShParam 8848 'Everest' 

powershell function default parameter

If you swap parameters with the given types, Powershell functions will return an error:

TestPoShParam : Cannot process argument transformation on parameter ‘curheight_meter’. Cannot convert value

“Everest” to type “System.Int32”. Error: “Input string was not in a correct format.”

Also in the PowerShell function, you can specify that some parameters are mandatory required and their order. The following syntax is used for this:

Function TestPoShParam { 

PARAM (

 [PARAMETER(Mandatory=$True,Position=0,HelpMessage ="Specify full DB path")][ValidateLength(1,20)][String]$DBPath,

 [PARAMETER(Mandatory=$True,Position=1,HelpMessage ="Specify max DB size")][String]$MaxSize,

 [PARAMETER(Mandatory=$False,Position=2)][String]$Type='MSSQL'

)

 Return("Path:" +$DBPath + " DB_size:" + $maxsize + " DB_type:" + $Type) 




}

TestPoShParam -DBPath 'c:\mysql\' -MaxSize 20

powershell function parameter types

In this example, additional arguments appeared near the Parameter switch:

  • Mandatory – if True is specified, this function parameter is strongly required;
  • HelpMessage – help for the user on the function parameter;
  • Position – position of the argument when calling the function (Parameters must be specified in a strictly defined order. If you don`t specify one of the parameters, then PowerShell will automatically remind you of this and offer to enter the missing information);
  • ValidateLength – maximum argument length (you cannot use a value with a length that is greater than the specified argument limit).

The post PowerShell Function Parameters: How to Add? appeared first on TheITBros.

PowerShell: Function Return

$
0
0
PowerShell Function Return

Most PowerShell newbies believe that PowerShell functions can return a value only through the Return statement. The return statement usually terminates the function and returns control to the calling function. But in Windows PowerShell, this is not entirely true…

In this article, we will look at how to return values from PowerShell functions using the Return command.

In traditional programming languages, functions usually return a single value of a particular type, but in Windows PowerShell, the results of the function are sent to the output stream.

Let’s look at the simplest PowerShell function:

function TestReturn($param) {

 $x = $param + 5

 "text"

 2*2

 return $x

}

If you run this function with a parameter 5 (TestReturn (5)) in a classical programming language, such a construction should return 10 (integer value).

However, in the case of PowerShell, we will see the output:

text

4

10

powershell function return

As you can see, PowerShell function returned 3 values as a result.

Note. It is not necessary to specify a Return command in a PowerShell function., The value of any variable or object that is displayed directly in the body of the function will be available as the function output.

Assign the value of the function to a variable and check its type with the following commands:

$MyTestVar=TestReturn (5)

$MyTestVar.GetType().FullName

The value returned by the function is of type System.Object [], i.e. this is an array. If the output of the function contains objects, the returned object instances will also fall into the collection (dynamic array).

You can display the length of the array and the values contained in it:

$MyTestVar.length

$MyTestVar[0]

$MyTestVar[1]

$MyTestVar[2]

powershell function return value

By default, PowerShell functions work so that when executed, they write to the $Result array all the values that were displayed during the function’s operation. This not always convenient when writing PowerShell functions.

In order not to send extra values to the output stream of the function, you must use the Write-Host cmdlet. This cmdlet will output function data to the console (on the screen), and not to the output stream:

function TestReturn($param) {

 $x = $param + 5

 Write-Host "text"

 Write-Host 2*2

 return $x

}

$MyTestVar = TestReturn (5)

$MyTestVar

As you can see, the function returned only the value that we expected – 10.

powershell function return type

You can also hide extra information from the output stream using the Return statement (it resembles the Break command in PowerShell loops).

function TestReturn($param) {

 “This line is displayed”

 return 

 “ This line is not displayed”

}

$MyTestVar = TestReturn (5)

$MyTestVar

powershell function return multiple values

The post PowerShell: Function Return appeared first on TheITBros.

PowerShell: Script for Loop through Files and Folders

$
0
0
PowerShell Script to Loop through Files

In this article, we will look at examples of using constructions to loop over all files and folders on a disk or in a specific directory that you can widely use in your PowerShell scripts.

Usually, the task of iterating over all file system objects in a directory arises when you need to perform a certain action with all nested objects. For example, you need to delete, copy, move files, add or replace lines in all files in the specific directory by some criteria.

To get a list of child objects (folders and files) in a directory, use the Get-ChildItem PowerShell cmdlet. This is the most popular file system cmdlet. There are several aliases for ChildItem: gci, dir, ls.

The Get-ChildItem cmdlet displays a list of child (nested) objects on a specified drive or directory. The path to the directory is specified through the –Path attribute.

For example, to list the files in the C:\PS directory, run the command:

Get-ChildItem -Path ‘C:\PS’

powershell script for loop

However, it displays a list of objects located in the root of the specified directory. You can also display the contents of child directories using the –Recurse parameter:

Get-ChildItem -Path ‘C:\PS’ –Recurse

As you can see, the contents of each subdirectory are displayed sequentially.

powershell script loop through files

Now, let’s look at the general structure of the ForEach loop when using the Get-ChildItem cmdlet.

Get-ChildItem –Path "C:\PS\" |

Foreach-Object {

#Do something with $_.FullName

}

Also you can use such a loop structure (but we like it less):

foreach($file in Get-ChildItem $SomeFolder)
{
# Do something
}

For example, you can delete all files with the *.log extension in the specified directory and all subfolders (we won’t really delete the files from disk by adding the parameter WhatIF):

Get-ChildItem –Path "C:\PS\" -Recurse -Filter *.log

|

Foreach-Object {

Remove-Item $_.FullName -WhatIF

}

The script found 3 files with the extension log and indicated that they could be deleted by this script.

Consider a script that deletes files older than 10 days in a directory (it can be used when you need to clean up the logs folder, or public network folders).

Get-ChildItem C:\ps\ -Recurse |

Where-Object { $_.CreationTime -lt ($(Get-Date).AddDays(-10))} |

ForEach-Object { remove-Item $_.FullName –whatif }

The following file loop example allows for all *.log files in the directory to find files containing the text ‘flush_log’ or ‘error’ and saves the found lines to files with a new extension (_outlog):

$files = Get-ChildItem C:\ps\ -Recurse *.log

foreach ($f in $files){

$outfile = $f.FullName + "_outlog"

Get-Content $f.FullName | Where-Object { ($_ -match 'flush_log' -or $_ -match 'error') } | Set-Content $outfile

}

Such a PowerShell script can be useful when searching for specific event entries in log files and filtering out all that is unnecessary.

The post PowerShell: Script for Loop through Files and Folders appeared first on TheITBros.

PowerShell Comparison Operators

$
0
0
Comparison Operators in PowerShell

PowerShell comparison operators allow you to find out if the value of a variable contains a string, is it larger, smaller, or equal to some value, etc. Most programming languages use symbols as comparison operators, like <, >, !=, =, however, in PowerShell, pseudo-commands are used instead of these special characters. For example, -eq (equal), -lt (less then), etc.

The table below contains the main PowerShell comparison operators:

-eq Equal (=)
-ne Not equal (<>)
-ge Greater than or equal (>=)
-gt Greater than (>)
-lt Less than (<)
-le Less than or equal (<=)
-like Wildcard comparison
-notlike Wildcard comparison
-match Regular expression comparison
-notmatch Regular expression comparison
-replace Replace operator
-contains Containment operator
-notcontains Containment operator

When performing the comparison operation, PowerShell returns True or False:

echo ("test" -ne "test1")

powershell comparison operators

By default, all PowerShell comparison operators are not case sensitive. However, if you need to perform case-sensitive comparisons, you must add the “c” prefix to the operator. For example, the –ne operator for case-sensitive comparison should be used as follow –cne.

If you need to explicitly indicate that a case-insensitive check is used, the prefix “i” is used. For example, -ine.

You can combine several comparison operators in one expression using the operators: –and, -or, -xor, -not,!:

{$_.Name -eq "John" -and $_.JobTitle -like “*manager*”}

In the similarity operations -like and –notlike, the symbol “*” is used as a wildcard (filter). For example:

($Object.Name -notlike "*system*")

Let’s look at a few examples of using PowerShell comparison operators.

$a=10

if($a -gt 5)

{

Write-host $a " greater than 5"

}

In this example, the comparison operator is used as a condition. If the condition is True, the command contained inside the If condition is executed. In this example, the screen will display the message: “10 greater than 5”.

powershell compare operators

Using comparison operators, you can compare strings with each other. For example:

$Address = “9650 Queensway CARLISLE CA10 5XL”

if($Address -clike "*CARLISLE*")

{

Write-host "Your address matches the pattern!"

}

In this example, we compared the $address variable to the case-sensitive string(-clike).

powershell string comparison operators

Also, you can use a regular expressions:

"London" -match "$ondon^"

"London" -notmatch "$don^"

Comparison operators let you compare the values of PowerShell arrays.

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

if($arr1 -contains "three")

{

Write-host "It’s OK!"

}

powershell equals operator

You can compare different types of variables and PowerShell objects.

Check that it’s 8 month now:

(Get-Date).Month -eq 8

Check that Windows has a running process called “notepad” that loads the CPU by more than 10%:

Get-Process | where {$_.Processname -eq "notepad" -and $_.CPU -gt 10}

powershell not equal operator

The post PowerShell Comparison Operators appeared first on TheITBros.

Viewing all 91 articles
Browse latest View live