Создание профиля outlook powershell

Обновлено: 05.07.2024

In this post, App Dev Manager Edward Fry demonstrates how to use Microsoft Outlook Object Library from PowerShell.

Time is a precious commodity. For many professionals, there just aren’t enough hours to accomplish all the tasks in a day. Thankfully, today’s world thrives on automation. Computers can perform painstaking, mundane tasks in a matter of seconds, leaving you the extra time to work on a multitude of more mentally intensive jobs. Whether you have an advanced technical degree or just use the computer for day-to-day tasks, it isn’t too hard to make the computer your personal assistant.

For this article, let’s focus on a specific type of task that is common for many professionals: sending out reports. While the specifics will vary, this scenario typically involves generating reports on some area of business interest and then sending those reports to recipients of interest. Of course, one way to approach this task would be to have each interested party look at their own reports or dashboards.

However, this isn’t always feasible. For instance, your users may be executives who don’t have the time for managing their own reporting. Or you might be in sales or services and need to share reports with your customers. Sharing that information is just part of the service that you provide, so it wouldn’t be appropriate to offload such a task to your customers. These are only two possible scenarios where you need to push reports to others rather than (or in addition to) having them pull their own.

An additional constraint, though, is that your report recipients must all be separated from each other. One executive might not need to know or care about another’s area of focus. One customer should not see or even be aware of other customers’ reports for privacy reasons. This constraint adds some complexity and work to the process. Wouldn’t it be nice to have the computer be your personal assistant and take care of all that for you?

Our goal in this article is to automate the download of periodic reports, associated processing, and dissemination to recipients via discrete outgoing messages with relevant attachments. For this article, I am assuming that the reports come from a reporting tool that allows email subscriptions, like SQL Server Reporting Services (SSRS), that Outlook is the email client, and some basic PowerShell knowledge.

By the way, you don’t have to be a seasoned developer in order to pull this off; anyone with a little PowerShell experience can benefit. Every information professional will benefit from some basic scripting ability in a language like PowerShell, and I highly recommend setting aside some time to learn this useful practical skill. If you need the basics, check out some of the free resources that are available.

Before we get to the scripting, we need to set some things up. This will make the script easier to code, and it will enable easier management as things change over time.

Report Delivery

A key component of this solution is that the reports you need to send out are delivered to your inbox. Of course, it’s possible to run them manually and save them off, and there’s a solution for automating those, too (though that is outside the scope of this article), but it is much easier to have them come to you.

Oftentimes, people are not aware that you can automate report delivery in SSRS. It is quite simple and involves just pre-selecting the filters of interest and a delivery schedule – for instance, once a month or once a week, etc.

When you set up your subscription, be sure to select the type of report that you wish to distribute. Since PDF is the most common file type for this sort of scenario, we will assume the reports are delivered in PDF format for the rest of this article.

Recipients

Typing in a list of recipients each time you need to send out reports is tedious and error-prone. Instead of doing that, let’s add a layer of abstraction to the process. In our case, we will use Outlook groups to refer to recipients as a group rather than by name. As you can see in the image below, you create a group for each type of recipient for each destination. For instance, our example here assumes customer recipients. You would make an Outlook group for primary recipients, one for CC, etc. Check out how to make groups in Outlook HERE.


For each group, then, you simply add the actual people who will need to receive the reports. That could be one person or a lot of people. As contacts change, all you need to do is keep these groups up to date, and the automation script will implicitly pick those changes up without any need to modify the code.

Template Emails

We also need a template email. In the image above, you can see that our template includes the message that we want to send to our recipients along with some tags that will be replaced in our script. To create an email template, go HERE.




File System

In this optional but recommended step, organize your folder structure so that you can save a copy of each report automatically for your records. Setting up an organized filing system is key to keeping the files organized and easy to locate in the future.

Once the reports of interest show up in your inbox at the designated time from SSRS, our automation will follow these steps:

  1. Connect to Outlook
  2. Open the emails and save the PDF to the proper folder in your filing system for backup purposes. I like to rename each PDF with something meaningful to the recipient and report. For example: (CompanyName)(ReportTitle)(Date).pdf
  3. Process Reports
    1. Attach the PDF into the analogous email template.
    2. Expand the To and CC recipient groups.
    3. Customize the message as needed.

    Connect to Outlook

    Process Reports

    Now we can finally process those emails that were sent by SSRS automatically with the report PDFs.


    With our handy Outlook namespace object in hand, we can now get references to other objects and commands within Outlook. First, we’ll get a reference to the inbox and the emails that match our criteria within the inbox.

    Prepare Outgoing Emails

    Within the looping structure above (in place of the “Prepare outgoing emails” comment above), we can now get our emails ready. This will utilize the email template and groups that we prepared earlier. Here is some sample code to get you started:

    As you can see, we first use a template denoted by the constant $emailTemplatePattern for each recipient or customer to create a new email. Next, we expand the contact groups specified in the To and CC lines of the new email. Finally, we replace the tags that were denoted by “[tag]” in the template with appropriate data points meaningful to each recipient. This data is usually pulled directly off of the title or file name of the reports sent by SSRS. You could also parse information out of the attachments themselves, though such an activity is beyond the scope of this article.

    Note: You can also have the script automatically send out your emails. I prefer to double check before they go out to make sure that everything looks ok.

    Wrapping Up

    Once everything is ready, you can either review and manually send out the resulting emails, or you can just sit back since PowerShell did it for you, depending on your choice above to Save or Send.

    It is important to shut down any Outlook processes that were spawned during the script so as to maintain idempotency. Here is some code to do that:

    Вы можете использовать PowerShell для Microsoft 365 для эффективного создания учетных записей пользователей, в том числе нескольких учетных записей.

    При создании учетных записей пользователей в PowerShell всегда требуются определенные свойства учетных записей. Другие свойства не требуются, но важны. См. следующую таблицу.

    Имя свойства Обязательный? Описание
    DisplayName
    Да
    Это имя отображения, которое используется в Microsoft 365 службах. Например, Caleb Sills.
    UserPrincipalName
    Да
    Это имя учетной записи, используемой для регистрации Microsoft 365 служб. Например, CalebS @ contoso.onmicrosoft.com.
    FirstName
    Нет
    LastName
    Нет
    LicenseAssignment
    Нет
    Это план лицензирования (также известный как план лицензии или SKU), из которого доступная лицензия назначена учетной записи пользователя. Лицензия определяет Microsoft 365 службы, доступные для учетной записи. При создании учетной записи пользователю не нужно назначать лицензию, но у учетной записи должна быть лицензия на доступ к Microsoft 365 службам. Лицензию требуется добавить в течение 30 дней после создания учетной записи пользователя.
    Password
    Нет
    Если пароль не указан, случайный пароль назначен учетной записи пользователя, и пароль отображается в результатах команды. Если указать пароль, он должен быть от 8 до 16 текстовых символов ASCII следующих типов: буквы нижнего регистра, верхние буквы, цифры и символы.
    UsageLocation
    Нет
    Это допустимый код страны согласно ISO 3166-1 alpha-2 (например, US для США и FR для Франции). Например, США для США и FR для Франции. Важно предоставить это значение, так как некоторые Microsoft 365 службы недоступны в некоторых странах. Вы не можете назначить лицензию учетной записи пользователя, если эта учетная запись не настроена. Дополнительные сведения см. в дополнительных сведениях об ограничениях лицензии.

    Список дополнительных ресурсов см. в списке Управление пользователями и группами.

    Использование модуля PowerShell Azure Active Directory для Graph

    После подключения используйте следующий синтаксис для создания отдельной учетной записи:

    В этом примере создается учетная запись для американского пользователя Caleb Sills:

    Использование модуля Microsoft Azure Active Directory для Windows PowerShell

    Создание одной учетной записи пользователя

    Чтобы создать одну учетную запись, используйте следующий синтаксис:

    PowerShell Core не поддерживает модуль Microsoft Azure Active Directory для Windows PowerShell и командлетов с Msol в их имени. Эти командлеты требуется запускать из Windows PowerShell.

    Чтобы предоставить список доступных имен плана лицензирования, используйте следующую команду:

    В этом примере создается учетная запись для американского пользователя Caleb Sills и назначается лицензия из плана лицензирования contoso:ENTERPRISEPACK (Office 365 корпоративный E3).

    Создание нескольких учетных записей пользователей

    Создайте CSV-файл, который содержит обязательные сведения об учетных записях пользователей. Пример:

    Имена столбцов и их порядок в первом ряду CSV-файла являются произвольными. Но убедитесь, что порядок данных в остальном файле соответствует порядку имен столбцов. И используйте имена столбцов для значений параметров в PowerShell для Microsoft 365 команды.

    Используйте следующий синтаксис:

    В этом примере создаются учетные записи пользователей из файла C:\My Documents\NewAccounts.csv и журналы результатов в файле C:\My Documents\NewAccountResults.csv.

    Результаты можно просмотреть в выходном файле. Мы не указали пароли, поэтому случайные пароли, Microsoft 365 созданные, видны в файле вывода.

    I have made this script to reset outlook profile and configure a new profile. this script is deleting the old profile and creating a new one and launches outlook. I want that after launch of outlook the profile should also be configured automatically.. can anyone suggest how to do it further in this script.

    11 1 1 gold badge 1 1 silver badge 2 2 bronze badges

    3 Answers 3

    I'll make a short set by step guide

    Download the OCT files

    Place the Admin folder which u extract from that install into the directory with the installation of the Office Version and then run from the command line setup.exe /admin

    enter image description here

    After doing so You will get a office Setup and you can skip everything and go right away to Outlook Profile Enter the settings you desire in here

    After doing so head over to Export Settings and save the PRF file somewhere on the network.

    Now there are 2 ways of doing this

    1. Launching Outlook.exe with a parameterExecute Outlook.exe /importprf "\\path\to\your\prf\file.prf" You should only run this command once though. So as a login script which keep being fired of it could be a bad idea.
    2. Setting a Registry Key to import the file
      • Key: HKEY_CURRENT_USER\Software\Microsoft\Office\<version>\Outlook\Setup
      • Value name: ImportPRF
      • Value type: REG_SZ
      • Value: path to prf-file

    For this Registry value to work, the FirstRun and First-Run value may not exist in the Setup key.

    This way it will only import the file once when outlook is first started.

    This could be done rather easily with PowerMapi, a powershell module that let's you do advance stuff with mapi directly, including outlook profiles.

    I don't know the depth of the issue driving the question, but realize that this option would also require access to the module DLL on the users' hosts. If that's a blocker, disregard.

    The first thing to know is that a MAPI profile can only be mostly configured, not completely. Outlook completes the configuration on first launch. I'll assume the real request is to be able to do this change without requiring any prompting for an end user to deal with. if so, the example below will work well for that. Furthermore, the standard way a profile is setup is very similar as you see when you create one manually from the control panel. Essentially, given a servername and mailbox identifier, a mapi method exists to "configure" the profile. This causes some communication to occur between mapi and an exchange server to fill in all the other necessary details. Then when outlook runs the next time, it logs on to the mailbox straight away and fills in any other details that Outlook needs in the profile.

    There are also options with the cmdlet to add an Office365 mailbox in the new profile or to setup for Outlook Anywhere connections. Look at the details for new-MapiProfile.

    Be aware that the example above will still prompt for a username and password if the current user is not also the "owner" of the malibox. If the computer is not domain joined, or the user is logging in a a local user (not as a domain user), then there will be a prompt for credentials.

    The new-MapiProfile cmdlet does accept credentials as a parameter, and if the creds provided have sufficient rights to access exchange, the cmdlet will complete without prompts. However, this would also mean embedding credentials into the cmdlet/script. which is generally a no-no. Lastly, the -Credentials feature is showing not work work with Windows10 and Outlook 2013 and later because MS is changing the standard cred prompt to use the WinRT version, away from the older win32 calls. Be sure to test as always.

    And finally, PowerMapi provides complete access to all properties and attributes of profiles, profile services, and profile providers. With such it is possible to pre-fill all the properties for a profile instead of having mapi do the "configure" call that requires network communication. However, that should be left for those familar with mapi.

    Have you ever needed to find an e-mail message from one or two years ago that, if you couldn’t find it, might adversely affect your circumstances? Does your company automatically delete messages from your Inbox or Sent Items folders? Do you get tired of copying e-mails to multiple folders when they touch on multiple topics of interest—a particular project, manager, subject matter, company division or the like?

    Say an e-mail from Steve Masters comes in regarding the finances on Project X in Dubai. It would be useful to have an automated way to distribute copies of this message to folders for Project X, Steve Masters and Dubai, and ultimately to yet another folder for safekeeping. And all without you having to manually click around the Microsoft Outlook interface multiple times for each item of mail. (And if you receive a large volume of email, it’s all the more vital to automate some of the management tasks involved.)

    The rules facility in Outlook is often useful in addressing these kinds of situations, and code I’ll present in this article shows how to automate the creation of rules. For example, copying messages from Steve Masters to a related folder in Outlook is a relatively straightforward matter. And that goes for other standard rules operations.

    What’s more difficult to do, and generally outside the capacity of Outlook rules, is to get a single e-mail into multiple folders based on more amorphous criteria than standard rules contemplate. While Steve Masters's e-mail can easily be copied to a related folder, the other relevant factors in his message—that it concerns finance, Dubai and Project X, among other possible criteria—are much more difficult to translate into actions. The subject line might cover one or two of the criteria and be susceptible to formal manipulation by an Outlook rule, but that often places too much trust in any given sender's subject lines. What we need is a quick, automated method to assign values to e-mails in both your Inbox and Sent Items such that a PowerShell script can be run to allocate them to the correct folders.

    Programming Outlook Rules

    This section takes a stab at demonstrating programmatic creation of two Outlook rules. One rule reads a message’s subject line for the specific string “Notification” and then copies relevant messages to a specified folder (named Notifications).

    With the namespace in hand, we specify the originating folder (the Inbox), create a new rule and specify the folder to copy to (Notifications).

    Navigating Folders

    It’s an interesting exercise to run some lines of code to see how folders are enumerated in the MAPI namespace. The following lines illustrate how to navigate to various levels of depth in the folder tree:

    Having created a new rule instance, we can define its parameters and properties like this:

    The first line relates the rule to the subject line of an incoming e-mail. The string to look for (“Completed Notification”) is specified, and the action to take is CopyToFolder (as opposed, for example, MoveToFolder). The invocation recites the action and the destination folder.

    Figure 1 shows the second example of programmatically creating a rule, where we look at recipients rather than the subject line.

    Figure 1. Creating a Rule for Recipients

    Managing Messages with a Script

    Clearly, one can do a lot in Outlook with the built-in rule facility, but what if you want to divide messages into categories like Project, Finance, Human Resources, Recipient Name, Sending Division, Month of Receipt, City, State, Country or any other of a virtually limitless number of categories, where any given e-mail could apply to multiple categories that are not identifiable from the subject or even the body of the message? In cases like these, a custom script can function like a special rule.

    In the following example, we manage the Sent Items folder by manually marking the subject line of each message with acronyms ("\\\Admin,FOR", for example), where each acronym relates the message to a target folder (Administrative,Foreign in the example) to which the e-mail should be copied. The process calls for manual action only to mark the subject lines of sent items with your designated acronyms.

    When the script runs, it finds the acronyms and copies the e-mail to as many folders as the acronyms listed in the subject line refer to. In addition, sent items are “aged” out of those folders by code that tests the respective received and sent dates for a given period and moves relevant messages to their respective resting places once the age criteria is met.

    The function I wrote is called CopyMove-Email. It has three parameters: a list of acronyms or symbols, the corresponding list of folders and an integer representing the maximum number of days to retain a message under Sent Items before moving it to safekeeping. (For use with Inbox items—the code is not shown—a fourth parameter should be added to indicate the number of days to maintain an Inbox item.)

    Then, as with the case of creating a rule, the messaging API is invoked:

    If you look in Task Manager, you’ll see two instances of Outlook. One is the original, displayed version that you are working in, and the other is a background Outlook process being used by this script.

    Next, we construct a timespan to mark the absolute limit for keeping sent items in that folder, whether the item is marked for copying or not.

    Using the timespan, we create the dates against which to test each e-mail item in the Sent Items folder.

    We also need a string-formatted date to use in naming text files that will store a specific day's run of this application. The text files will store, respectively, mail that was copied and mail that was moved.

    Then we need to accumulate data about moves and copies in temporary holding arrays:

    Experience shows that merely looping through all the messages in the Sent Items folder once isn’t enough; on a first loop, some items are handled but others aren’t touched. It may take three or four such loops to handle all the items that need handling. The number of loops probably depends on how many mail items are ready for copy-move operations and other factors in how Outlook interoperates with your computer. In any event, the solution is to use a Do-While structure to keep running the loop until all marked items have been properly managed.

    The application is now ready to begin parsing through Sent Items:

    The first If test is against the established maximum-days window and for the existence of either the \\\ tag or the /// tag:

    With a matching e-mail in hand, test it for each acronym in the $acronyms parameter:

    For each matching acronym, the script makes a copy of the subject e-mail and moves the copy to the folder that matches the acronym. This part of the code is shown in Figure 2. Essentially, this copies the message to the new folder while also leaving it in the original Sent Items folder.

    Figure 2. Copying Code Based on Acronyms

    The next action for these kinds of mail items (shown in Figure 3) is to move them to Sent Items OLD for more permanent storage and also for later transfer to a text file documenting the move-copy actions.

    Figure 3. Moving Items to Sent Items OLD

    Then messages in Sent Items that are past the maximum retention period should be moved to Sent Items OLD. Their data is also stored for moving into the related text file. (See Figure 4.)

    Figure 4. Managing Message Retention Limits

    The last action to take is moving data about moved and copied items into the text files set up to hold that data:

    You can call the CopyMove function with parameters, including the list of acronyms and the list of related folder names, plus the maximum number of days to keep sent items in that folder before saving them to Sent Items OLD:

    Wrapping Up

    As an afterword, I’d note that scheduled tasks can be configured to include the code I’ve shown, but a certain number of gotchas will manifest themselves in the process, not least of which is that the task will not run if the machine is not connected to the network. So, remote users relying on a VPN, for example, might be out of luck if, as is usually the case, the connection automatically shuts down after a certain period of nonuse (like when you go to bed at night). Thus, the app can be scheduled to run only during times when you know the network connection is active.

    Joe Leibowitz is an infrastructure consultant who specializes in Microsoft’s identity management products.

    Читайте также: