Search icon CANCEL
Subscription
0
Cart icon
Your Cart (0 item)
Close icon
You have no products in your basket yet
Arrow left icon
Explore Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Free Learning
Arrow right icon
Arrow up icon
GO TO TOP
PowerShell for Office 365

You're reading from   PowerShell for Office 365 Automate Office 365 administrative tasks

Arrow left icon
Product type Paperback
Published in Jul 2017
Publisher Packt
ISBN-13 9781787127999
Length 222 pages
Edition 1st Edition
Languages
Arrow right icon
Authors (2):
Arrow left icon
Prashant G Bhoyar Prashant G Bhoyar
Author Profile Icon Prashant G Bhoyar
Prashant G Bhoyar
Martin Machado Martin Machado
Author Profile Icon Martin Machado
Martin Machado
Arrow right icon
View More author details
Toc

Table of Contents (10) Chapters Close

Preface 1. PowerShell Fundamentals FREE CHAPTER 2. Managing Office 365 with PowerShell 3. Azure AD and Licensing Management 4. Managing SharePoint Online Using PowerShell 5. Managing Exchange Online Using PowerShell 6. Script Automation 7. Patterns and Practices PowerShell 8. OneDrive for Business 9. PowerShell Core

Creating your first script

To automate tasks, we need to create and run PowerShell scripts. To run a script, we need to follow these steps:

  1. Configure PowerShell to run scripts: Running a malicious script can harm the computer/server; the default setting for PowerShell is not to run them. We need to change the execution policy of the computer/server to be less restrictive. These steps need to be implemented once.
  2. Store the script: We need to store the script files with the .ps1 extension on the file system.
  3. Edit the script: Add the business logic using commands, cmdlets, variables, and so on.
  4. Run the script: Run the PowerShell script within the PowerShell Command Prompt or ISE.

Let's create our first PowerShell script. We will be creating a script to read the information from a CSV file and then process the information using the for loops and then print it on the screen.

A comma-separated file has information in the form of tables, as shown in the following screenshot. The file has the user's information: their first name, last name, location, and department. We will use this information and create the login names for the users using the format $firstName + "." + $lastName.

The CSV file is as follows:

The script is as follows:

Function generateUserName($firstName, $lastName){
$userName = $firstName + "." + $lastName
Return $userName;
}

$userInformation = import-csv 'C:\Demo\UsersInfo.csv'

foreach($user in $userInformation){
$firstName = $user.FirstName
$lastName=$user.LastName
$department =$user.Department
$office=$user.Office
$Location=$user.Location
$userName = generateUserName $firstName $lastName
Write-Host "The generated user name is " $userName
}

The following screenshot shows the preceding script:

Now let's review this script line by line. As mentioned before, if you are using functions inside a script, it is recommended that you write them at the top of the script. The reason is that when the script is executed, the functions are already loaded.

On line 1 we have declared the function with the name generateUserName, and it accepts two parameters of type string. We can pass complex datatypes as parameters as well.

On line 2, we are creating the value for the username using the following logic:

$firstname + "." + $lastName

On line 3, we are returning that value.

On line 6, we are reading the contents of the CSV file. The Import-CSV cmdlet is a cmdlet to read the contents of a file.

We will be covering this cmdlet in detail because to automate bulk user creation, we can use $userInformation stored in CSV files. We can also use information from other sources, such as plain text files or SharePoint lists. But as of now, CSV files are more common.

The Import-CSV cmdlet reads the information from the .csv file and stores them in the table-like custom objects. Each column header becomes the property and the subsequent rows become the values of the properties. You can find more information about this cmdlet here https://msdn.microsoft.com/en-us/powershell/reference/5.0/microsoft.powershell.utility/import-csv.

Here is the Import-CSV command:

This cmdlet accepts the following parameters.

  • [-Delimiter]: Specifies the delimiter that separates the property values in the CSV file. The default is a comma (,). Enter a character, such as a colon (:). To specify a semicolon (;), enclose it in quotation marks.
    If you specify a character other than the actual string delimiter in the file, Import-CSV cannot create objects from the CSV strings. Instead, it returns the strings.

  • [-Encoding]: Specifies the type of character encoding that was used in the CSV file. Acceptable values for this parameter are as follows:
    • Unicode
    • UTF7
    • UTF8
    • ASCII
    • UTF32
    • BigEndianUnicode
    • Default
    • OEM

The default is ASCII.

This parameter was introduced in Windows PowerShell 3.0.

  • [ -Header]: Specifies an alternate column header row for the imported file. The column header determines the names of the properties of the object that Import-CSV creates.
    Enter a comma-separated list of the column headers. Enclose each item in quotation marks (single or double). Do not enclose the header string in quotation marks. If you enter fewer column headers than there are columns, the remaining columns will have no header. If you enter more headers than there are columns, the extra headers are ignored.
    When using the Header parameter, delete the original header row from the CSV file. Otherwise, Import-CSV creates an extra object from the items in the header row.
  • [-LiteralPath]: Specifies the path to the CSV file to import. Unlike Path, the value of the LiteralPath parameter is used exactly as it is typed. No characters are interpreted as wildcards. If the path includes escape characters, enclose it in single quotation marks. Single quotation marks tell Windows PowerShell not to interpret any characters as escape sequences.
  • [-Path]: Specifies the path to the CSV file to import. You can also pipe a path to Import-CSV.
  • [-UseCulture]: Indicates that this cmdlet uses the list separator for the current culture as the item delimiter. The default is a comma (,).
  • [CommonParameters]: This cmdlet supports the common parameters: -Debug, -ErrorAction, -ErrorVariable, -InformationAction, -InformationVariable, -OutVariable, -OutBuffer, -PipelineVariable, -Verbose, -WarningAction, and -WarningVariable.

Inputs:

[System.String]: You can pipe a string that contains a path to Import-CSV.

Outputs:

[Object]: This cmdlet returns the objects described by the content in the CSV file.

Let's come back to the script. Once we get the contents of the CSV file in the $userInformation object, we process each row and assign the first name, last name, department, and office to the variables. On line 14, we call the generateUserName function and capture the return value in the variable and display the username on the script:

Using a similar script, we will cover how to create bulk users and assign them licenses in Chapter 3, Azure AD and Licensing Management.
You have been reading a chapter from
PowerShell for Office 365
Published in: Jul 2017
Publisher: Packt
ISBN-13: 9781787127999
Register for a free Packt account to unlock a world of extra content!
A free Packt account unlocks extra newsletters, articles, discounted offers, and much more. Start advancing your knowledge today.
Unlock this book and the full library FREE for 7 days
Get unlimited access to 7000+ expert-authored eBooks and videos courses covering every tech area you can think of
Renews at $19.99/month. Cancel anytime
Banner background image