Category Archives: PowerShell

Use PowerShell to Explore Office 365

Use PowerShell to Explore Office 365

  1. Type Connect-MsolService
  2. Enter your office 365 credentials.
  3. Type Get-Command -Module MSOnline to see all available commands.

Examples:

To see your package and licenses:

PS C:\Users\guy.naftaly> Get-MsolAccountSku |ft -AutoSize

 

AccountSkuId         ActiveUnits WarningUnits ConsumedUnits

————         ———– ———— ————-

xxxxxxx:MIDSIZEPACK 61          0            44

How To Restore User Mailboxes in Office 365

Restore one or more users

When you restore a user account within 30 days after deleting it, the user account and all associated data are restored. The user can sign in to Office 365 with the same user ID, their mailbox is fully restored, and they have access to all services they previously accessed.

Before you restore a user account, make sure there are Office 365 licenses available that you can assign to the account. Also, when you restore an account, you may encounter conflicts with user names or proxy addresses, which you can resolve.

To restore one or more users

  1. Go to Admin > Office 365 > Users and groups > Deleted users.
  2. On the Deleted users page, choose the names of the users that you want to restore, and then click Restore users.
  3. In the confirmation box, click Close.

Delete or restore users – office365 suite.

How Connect to Exchange Online Office 365 using remote PowerShell

Remote PowerShell allows you to manage your Exchange Online settings from the command line. You use Windows PowerShell on your local computer to create a remote Shell session to Exchange Online. It’s a simple three-step process where you enter your Exchange Online credentials, provide the required connection settings, and then import the Exchange Online cmdlets into your local Windows PowerShell session so that you can use them.

 

What do you need to know before you begin?

·        

Estimated time to complete: 5 minutes

·         You can use the following versions of Windows:

o    Windows 8 or Windows 8.1

o    Windows Server 2012 or Windows Server 2012 R2

o    Windows 7 Service Pack 1 (SP1)*

o    Windows Server 2008 R2 SP1*

·         You need to install the Microsoft .NET Framework 4.5 or 4.5.1 and then either the Windows Management Framework 3.0 or the Windows Management Framework 4.0.

 

Connect to Exchange Online

 

1.     On your local computer, open Windows PowerShell and run the following command.

2.     $UserCredential = Get-Credential

In the Windows PowerShell Credential Request dialog box, type your Exchange Online user name and password, and then click OK.

3.     Run the following command.

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

5.     Run the following command.

6.     Import-PSSession $Session
7.     Be sure to disconnect the remote PowerShell session when you're finished. If you close the Windows PowerShell window without disconnecting the session, you could use up all the remote PowerShell sessions available to you, and you'll need to wait for the sessions to expire. To disconnect the remote PowerShell
               Remove-PSSession $Session
How do you know this worked?

 

After Step 3, the Exchange Online cmdlets are imported into your local Windows PowerShell session as tracked by a progress bar. If you don’t receive any errors, you connected successfully. A quick test is to run an Exchange Online cmdlet—for example, Get-Mailbox—and see the results.

If you receive errors, check the following requirements:

·         A common problem is an incorrect password. Run the three steps again and pay close attention to the user name and password you enter in Step 1.

·         To help prevent denial-of-service (DoS) attacks, you’re limited to three open remote PowerShell connections to your Exchange Online organization.

·         Windows PowerShell needs to be configured to run scripts. You only need to configure this setting once on your computer, not every time you connect. To enable Windows PowerShell to run signed scripts, run the following command in an elevated Windows PowerShell window (a Windows PowerShell window you opened by selecting Run as administrator).

·         Set-ExecutionPolicy RemoteSigned

 

·         The account you use to connect to Exchange Online must be enabled for remote Shell. TCP port 80 traffic needs to be open between your local computer and Exchange Online. It’s probably open, but it’s something to consider if your organization has a restrictive Internet access policy.

Connect to Exchange Online using remote PowerShell: Exchange Online Help.

How To Delete User Mailboxes in Office 365

·         You can delete Exchange Online mailboxes by deleting the corresponding Office 365 user account, removing the Exchange Online license, or by running the Remove-Mailbox cmdlet in the Shell.

·         When a mailbox is deleted, Exchange Online retains its contents for 30 days, by default. After 30 days, the mailbox is permanently deleted and is not recoverable.

·         You can recover a deleted mailbox within the retention period by using the Office 365 admin center to recover the corresponding Office 365 user account.

·         If the mailbox was deleted by removing the Exchange Online license, it can be restored within the retention period by reassigning the license to the corresponding user account. 

·         If you need to delete a mailbox, but preserve the mailbox contents indefinitely, you can enable an inactive mailbox. To do this, you have place the mailbox on In-Place Hold before you delete it. 

·         Before an inactive mailbox can be enabled, the mailbox must be assigned an Exchange Online (Plan 2) license or have an Exchange Online Archiving subscription so that an In-Place Hold can be placed on the mailbox before it’s deleted.

Use the Office 365 admin center to delete a user account

1.     Go to Admin > Office 365 > Users and groups.

2.     Choose the names of the users that you want to delete, and then click Delete .

3.     In the confirmation box, click yes.

Use the Shell to delete a mailbox

1.     Connect to Exchange Online Using Remote PowerShell:

a.     Run PowerShell as administrator.

b.    Configure PowerShell to run scripts. Set-ExecutionPolicy RemoteSigned

c.     $UserCredential = Get-Credential

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

e.     Import-PSSession $Session

2.     Remove-Mailbox -Identity “Nellie Rom”

3.     Disconnect the remote PowerShell session:

 

a.     Remove-PSSession $Session

via Delete or Restore User Mailboxes in Exchange Online: Exchange Online Help.

How to get a list of all Licensed Office 365 users with PowerShell

Install required software

1.     Ensure you are running Windows 8.1, Windows 8, or Windows 7.

2.     Make sure you have the .NET Framework 3.51 feature.

3.       Make sure you have the latest updates.

4.     Install the Microsoft Online Services Sign-In assistant.

5.       Install the Windows Azure Active Directory (Azure AD) module for the appropriate version of your operating system.

6.       Open powershell as administrator.

7.       Import-Module MSOnline

8.       Get-Credential (Windows PowerShell  dialog box appears)

9.       Enter your credentials.

10.   Connect-MsolService

11.   Get-MsolUser -All |Sort isLicensed

12.   Finish.

Via – Getting Started with Office 365 and PowerShell – Hey, Scripting Guy! Blog – Site Home – TechNet Blogs.

Getting Mailbox Sizes in PowerShell

In earlier versions of Exchange, we could look in the Exchange console and see mailbox sizes on a per database basis. Not bad, but better than what we have in the Exchange 2007 GUI.

Fortunately, we can use PowerShell to see the information we need. And, we have more control over how the information is displayed, as well as what information is displayed. Let’s fire up PowerShell and get started.

We can use the Get-MailboxStatistics cmdlet and supply a username like this:

Get-MailboxStatistics [username]

This shows the DisplayName, ItemCount, StorageLimitStatus, and LastLogonTime fields for the specified user.

But that doesn’t show what we need. We can have the cmdlet display just specific fields, such as DisplayName, ItemCount, and TotalItemSize, which will show the size of the mailbox. For that, we use the FT command, short for Format-Table, along with the fields we want.

Get-MailboxStatistics [username] | ft DisplayName, TotalItemSize, ItemCount

This shows us the size of the mailbox in bytes, as well as the number of items, and the username.

Showing data for all users

Now that we can see the specific fields, we can remove the [username] parameter and the command will show us the information all users.

Filtering results

As you can see, this will show us system mailbox sizes as well, which probably doesn’t do us any good. So let’s filter them out.

We add | where {$_.ObjectClass –eq “Mailbox”} right after Get-MailboxStatistics to help.

Note – that’s a pipe at the beginning. This code essentially says to only display those objects classified as mailboxes. From that, we get a cleaner list.

Sorting results

So that shows us all of the users and their sizes, but they appear in a random, unsorted order, which doesn’t do anyone any good. In PowerShell, we can sort using the Sort-Object cmdlet. Right after our filter, we add

| Sort-Object TotalItemSize –Descending

 

This tells PowerShell to sort according to the TotalItemSize parameter (the size of the mailbox) of the Get-MailboxStatistics results, in descending order.

Via Getting Mailbox Sizes in PowerShell.

Use PowerShell to Find and Remove Inactive Accounts from AD

Keeping Active Directory (AD) tidy can help reduce replication bandwidth if you have domain controllers in different sites, and make troubleshooting and management easier. In this Ask the Admin, I’ll show you how to easily remove a computer account from AD, and how to query the directory for accounts that haven’t been used in a long time.

Remove Computer Accounts Using PowerShell

To remove one or more computer accounts using PowerShell, log on to Windows Server 2012 R2, or a Windows 8 management workstation that’s a member of your Active Directory domain, using an account that has permission to delete AD objects. If you decide to run the commands on a machine that isn’t a domain controller, the AD module for PowerShell must be installed.

  • Open a PowerShell prompt, using either the icon on the desktop taskbar (Windows Server), or by switching to the Start screen, typing powershell and selecting Windows PowerShell from the search results (Windows 8).
  • In the PowerShell prompt, type remove-adcomputer -identity workstation01 and press ENTER, replacing workstation01 with the name of the computer account you want to remove.

Search AD for Inactive Computer Accounts

Now that we know how to remove computer accounts using the command line, let’s query AD for computer accounts that haven’t been used for a long time. Computer account passwords are automatically reset by AD every 30 days, so you can determine yourself what length of time you should let pass before deleting the accounts from AD. A year or more would likely be a safe option.

In this example, I’m going to use the get-adcomputer cmdlet, and the select and sort object cmdlets to format the results:

get-adcomputer -filter * -properties passwordlastset | select name, passwordlastset | sort passwordlastset

We need to add in the –properties parameter because the passwordlastset attribute is not displayed in the results by default. Select name and sort are then used to ‘pull out’ and order only the required information.

Now let’s add a more complex filter. We can use the get-date cmdlet to create a variable that sets the filter to show accounts that have had their accounts reset more than one year ago. To create the variable, type $date = (get-date).addyears(-1) and press Enter.

Now we can modify the command to include a less than (-lt) argument in the filter:

get-adcomputer -filter {passwordlastset -lt $date} -properties passwordlastset | select name, passwordlastset | sort passwordlastset

Finally, once we are sure the filter is right, we need to add the remove-adobject cmdlet as follows, without the select and sort cmdlets. Notice that I’m using the remove-adobject cmdlet and not remove-adcomputer, because remove-adcomputer is not able to delete accounts that have embedded ‘leaf’ objects, such as computer accounts for virtual machines.

 

get-adcomputer -filter {passwordlastset -lt $date} -properties passwordlastset | remove-adobject -recursive -verbose -confirm:$false

Via Use PowerShell to Find and Remove Inactive Accounts from AD.

Run PowerShell Scripts with Local Administrator Rights

Sooner or later, as you begin to hone your PowerShell skills, you’ll start writing scripts to automate repetitive tasks. If you run your workstation with standard user privileges, you’ll soon discover that it’s not possible to launch PowerShell scripts with administrative privileges by right-clicking the script and selecting Run as administrator from the context menu (which is available for most over types of executable). Today I’ll show you two ways that you can launch PowerShell scripts with admin privileges.

Modify a Script to Force Elevation

Add this snippet of code to the beginning of your PowerShell script, and a UAC prompt will appear, asking for administrative credentials or consent before any subsequent code is executed.

param([switch]$Elevated)

function Check-Admin {

$currentUser = New-Object Security.Principal.WindowsPrincipal $([Security.Principal.WindowsIdentity]::GetCurrent())

$currentUser.IsInRole([Security.Principal.WindowsBuiltinRole]::Administrator)

}

if ((Check-Admin) -eq $false)  {

if ($elevated)

{

# could not elevate, quit

}

 

else {

 

Start-Process powershell.exe -Verb RunAs -ArgumentList (‘-noprofile -noexit -file “{0}” -elevated’ -f ($myinvocation.MyCommand.Definition))

}

exit

}

Run a Code from an Elevated Instance of the Windows PowerShell Integrated Scripting Environment (ISE)

Alternatively, you can run scripts directly from inside the Windows PowerShell ISE. To start the ISE with administrative privileges:

  • Switch to the Start menu in Windows 8, type powershell ise, and make sure that PowerShell ISEis selected in the search results. Press CTRL+SHIFT+ENTER to start the ISE with elevated privileges and enter administrative credentials or give sent if prompted.
  • In the PowerShell ISE window, select Open from the File menu to load your script.
  • Once the script is loaded into the ISE, press F5 to run the script.

 

The Windows PowerShell ISE is a useful environment for creating and editing your scripts. You have access to all the installed PowerShell modules and their related commands, plus troubleshooting tools.

Via Run PowerShell Scripts with Local Administrator Rights.

Install Active Directory Management Service for Easy PowerShell Access.

Install Active Directory Management Service for Easy PowerShell Access – Hey, Scripting Guy! Blog – Site Home – TechNet Blogs.

You can control AD from remote PC or Server:

1.       Install .NET Framework 3.5 with Service Pack 1 on the domain controller.

2.       on the domain controller Download and install Active Directory Management Gateway Service Windows6.0-KB968934-x86.msu or Windows6.0-KB968934-x64.msu

3.       if you get this error “the update does not apply to your system”:

a.       There are two hotfixes that are required (and there are three options available—a .NET Framework update and an operating system–specific update):

                                                               i.      KB967574 hotfix which is already installed if the DC is running server 2008 SP 2.

                                                             ii.      969166 hotfix which is a .NET Framework 3.5 SP1 hotfix rollup – no need to reboot the DC after the installation.

                                                            iii.      For Windows Server 2003 and Windows Server 2003 R2, there is a specific hotfix that is described in KB 969429 – no need to install for 2008 DC.

                                        iv.    The third hotfix that is listed applies to Windows Server 2008. This hotfix, KB 967574, applies if you have not installed Service Pack 2 on the system.

4.     After the two updates are applied to the system and the Active Directory Management Gateway Service is installed, a reboot of the server is required.

5.     On the DC open the services.msc utility and verify that Active Directory Web Services service is created and running.

6.     Connect to the DC with Windows PowerShell from your Windows 7 desktop.

7.     Download and install the active directory powershell module on your Windows 7 desktop.

8.     Import the Active Directory module.

 

9.     end