No mundo acelerado e exigente da TI, toda ferramenta que economiza tempo e simplifica tarefas vale seu peso em ouro. Hoje, vamos explorar como os scripts do PowerShell podem ser utilizados para automatizar a instalação do Office 365, uma operação crítica que pode economizar inúmeras horas a longo prazo. Na verdade, com um script bem escrito, você pode gerenciar instalações em uma rede inteira a partir de sua mesa. Esta postagem é para profissionais de TI e provedores de serviços gerenciados (MSPs) que desejam simplificar suas implantações do Office 365 usando o poder do PowerShell.
Por que automatizar com o PowerShell?
O PowerShell é uma linguagem de script avançada e um shell desenvolvido pela Microsoft. Ele tem sido parte integrante do ecossistema do Windows desde o Windows 7, e seu poder e flexibilidade o tornaram uma ferramenta vital para muitos profissionais de TI e MSPs. A automação das instalações do Office 365 usando o PowerShell pode reduzir drasticamente o tempo e o esforço necessários para implantar o Office 365 em várias máquinas.
Além disso, os scripts do PowerShell podem ser personalizados para atender às suas necessidades. Por exemplo, o script pode ser configurado para instalar componentes específicos do Office 365, aplicar determinadas configurações e até mesmo limpar após a instalação. Esse nível de personalização permite que os profissionais de TI e os MSPs garantam que o Office 365 seja implantado de forma consistente em todas as máquinas, alinhando-se às políticas e aos padrões de TI da empresa.
Um mergulho profundo no script do PowerShell Install Office 365
Vamos dar uma olhada mais de perto em um exemplo de script do PowerShell para automatizar as instalações do Office 365. Esse script foi projetado para instalar o Office 365 usando um arquivo de configuração personalizado ou padrão. Se a instalação falhar, o script fornecerá uma mensagem de erro, tornando a solução de problemas mais simples.
O que torna esse script particularmente útil é sua capacidade de baixar e usar a Office Deployment Tool dos servidores da Microsoft. Esse recurso garante que a versão mais recente do Office 365 seja sempre usada para a instalação. Além disso, o script verifica se o pacote Office 365 foi instalado corretamente, oferecendo uma camada extra de garantia.
Após uma instalação bem-sucedida, o script aciona uma reinicialização do sistema. Isso é particularmente útil, pois alguns componentes do Office 365 exigem a reinicialização do sistema para funcionar corretamente. O script também é equipado com um mecanismo de limpeza que pode ser ativado para remover os arquivos de instalação após a instalação do Office 365.
Script do PowerShell para instalação do Microsoft Office 365
#Requires -Version 5.1
<#
.SYNOPSIS
Installs Office 365 from a config file or creates a generic config file and installs.
.DESCRIPTION
Installs Office 365 from a config file or creates a generic config file and installs.
By using this script, you indicate your acceptance of the following legal terms as well as our Terms of Use at https://www.ninjaone.com/terms-of-use.
Ownership Rights: NinjaOne owns and will continue to own all right, title, and interest in and to the script (including the copyright). NinjaOne is giving you a limited license to use the script in accordance with these legal terms.
Use Limitation: You may only use the script for your legitimate personal or internal business purposes, and you may not share the script with another party.
Republication Prohibition: Under no circumstances are you permitted to re-publish the script in any script library or website belonging to or under the control of any other software provider.
Warranty Disclaimer: The script is provided “as is” and “as available”, without warranty of any kind. NinjaOne makes no promise or guarantee that the script will be free from defects or that it will meet your specific needs or expectations.
Assumption of Risk: Your use of the script is at your own risk. You acknowledge that there are certain inherent risks in using the script, and you understand and assume each of those risks.
Waiver and Release: You will not hold NinjaOne responsible for any adverse or unintended consequences resulting from your use of the script, and you waive any legal or equitable rights or remedies you may have against NinjaOne relating to your use of the script.
EULA: If you are a NinjaOne customer, your use of the script is subject to the End User License Agreement applicable to you (EULA).
.EXAMPLE
No parameters need if you want to use the default config file OR change the $OfficeXML variable to use your XML config file's content.
.EXAMPLE
-ConfigurationXMLFile https://replace.me/configuration.xml
Install Office 365 and use a local config file.
You can use https://config.office.com/deploymentsettings to help build the config file.
.OUTPUTS
None
.NOTES
This will reboot after a successful install.
Minimum OS Architecture Supported: Windows 10, Windows Server 2016
Release Notes: Renamed script and added Script Variable support, made restarts optional, changed default download path to %TEMP%\Office365Install, switched to downloading an xml instead of using a local path.
#>
[CmdletBinding()]
param(
# Use a existing config file
[Parameter()]
[String]$ConfigurationXMLFile,
# Path where we will store our install files and our XML file
[Parameter()]
[String]$OfficeInstallDownloadPath = "$env:TEMP\Office365Install",
[Parameter()]
[Switch]$Restart
)
begin {
if ($env:linkToConfigurationXml -and $env:linkToConfigurationXml -notlike "null") { $ConfigurationXMLFile = $env:linkToConfigurationXml }
if ($env:restartComputer -like "true") { $Restart = $True }
$CleanUpInstallFiles = $True
# In case 'https://' is omitted from the URL.
if ($ConfigurationXMLFile -and $ConfigurationXMLFile -notmatch "^http(s)?://") {
Write-Host "[Warn] http(s):// is required to download the file. Adding https:// to your input...."
$ConfigurationXMLFile = "https://$ConfigurationXMLFile"
Write-Host "[Warn] New Url $ConfigurationXMLFile."
}
# Set TLS Version
$SupportedTLSversions = [enum]::GetValues('Net.SecurityProtocolType')
if ( ($SupportedTLSversions -contains 'Tls13') -and ($SupportedTLSversions -contains 'Tls12') ) {
[System.Net.ServicePointManager]::SecurityProtocol = [System.Net.ServicePointManager]::SecurityProtocol::Tls13 -bor [System.Net.SecurityProtocolType]::Tls12
}
elseif ( $SupportedTLSversions -contains 'Tls12' ) {
[System.Net.ServicePointManager]::SecurityProtocol = [System.Net.SecurityProtocolType]::Tls12
}
else {
# Not everything requires TLS 1.2, but we'll try anyway.
Write-Host "[Warn] TLS 1.2 and or TLS 1.3 are not supported on this system. This script may fail!"
if ($PSVersionTable.PSVersion.Major -lt 3) {
Write-Host "[Warn] PowerShell 2 / .NET 2.0 doesn't support TLS 1.2."
}
}
function Set-XMLFile {
# XML data that will be used for the download/install
# Example config below generated from https://config.office.com/
# To use your own config, just replace <Configuration> to </Configuration> with your xml config file content.
# Notes:
# "@ can not have any character after it
# @" can not have any spaces or character before it.
$OfficeXML = [XML]@"
<Configuration ID="76b3b530-54a8-44d8-9689-278ec2547592">
<Info Description="Example O365 install" />
<Add OfficeClientEdition="64" Channel="MonthlyEnterprise" MigrateArch="TRUE">
<Product ID="O365BusinessRetail">
<Language ID="MatchOS" />
<Language ID="MatchPreviousMSI" />
<ExcludeApp ID="Access" />
<ExcludeApp ID="Groove" />
<ExcludeApp ID="Lync" />
<ExcludeApp ID="Publisher" />
</Product>
</Add>
<Property Name="SharedComputerLicensing" Value="0" />
<Property Name="FORCEAPPSHUTDOWN" Value="TRUE" />
<Property Name="DeviceBasedLicensing" Value="0" />
<Property Name="SCLCacheOverride" Value="0" />
<Updates Enabled="TRUE" />
<RemoveMSI />
<AppSettings>
<Setup Name="Company" Value="Ninja Example" />
<User Key="software\microsoft\office\16.0\excel\options" Name="defaultformat" Value="51" Type="REG_DWORD" App="excel16" Id="L_SaveExcelfilesas" />
<User Key="software\microsoft\office\16.0\powerpoint\options" Name="defaultformat" Value="27" Type="REG_DWORD" App="ppt16" Id="L_SavePowerPointfilesas" />
<User Key="software\microsoft\office\16.0\word\options" Name="defaultformat" Value="" Type="REG_SZ" App="word16" Id="L_SaveWordfilesas" />
</AppSettings>
<Display Level="None" AcceptEULA="TRUE" />
<Setting Id="SETUP_REBOOT" Value="Never" />
<Setting Id="REBOOT" Value="ReallySuppress"/>
</Configuration>
"@
#Save the XML file
$OfficeXML.Save("$OfficeInstallDownloadPath\OfficeInstall.xml")
}
function Get-ODTURL {
$Uri = 'https://www.microsoft.com/en-us/download/details.aspx?id=49117'
$DownloadURL = ""
for ($i = 1; $i -le 3; $i++) {
try {
$MSWebPage = Invoke-WebRequest -Uri $Uri -UseBasicParsing -MaximumRedirection 10
$DownloadURL = $MSWebPage.Links | Where-Object { $_.href -like "*officedeploymenttool*.exe" } | Select-Object -ExpandProperty href -First 1
if ($DownloadURL) {
break
}
Write-Host "[Warn] Unable to find the download link for the Office Deployment Tool at: $Uri. Attempt $i of 3."
Start-Sleep -Seconds $($i * 30)
}
catch {
Write-Host "[Warn] Unable to connect to the Microsoft website. Attempt $i of 3."
}
}
if (-not $DownloadURL) {
Write-Host "[Error] Unable to find the download link for the Office Deployment Tool at: $Uri"
exit 1
}
return $DownloadURL
}
function Test-IsElevated {
# Get the current Windows identity of the user running the script
$id = [System.Security.Principal.WindowsIdentity]::GetCurrent()
# Create a WindowsPrincipal object based on the current identity
$p = New-Object System.Security.Principal.WindowsPrincipal($id)
# Check if the current user is in the Administrator role
# The function returns $True if the user has administrative privileges, $False otherwise
$p.IsInRole([System.Security.Principal.WindowsBuiltInRole]::Administrator)
}
# Utility function for downloading files.
function Invoke-Download {
param(
[Parameter()]
[String]$URL,
[Parameter()]
[String]$Path,
[Parameter()]
[int]$Attempts = 3,
[Parameter()]
[Switch]$SkipSleep
)
# Display the URL being used for the download
Write-Host "[Info] URL '$URL' was given."
Write-Host "[Info] Downloading the file..."
# Determine the supported TLS versions and set the appropriate security protocol
$SupportedTLSversions = [enum]::GetValues('Net.SecurityProtocolType')
if ( ($SupportedTLSversions -contains 'Tls13') -and ($SupportedTLSversions -contains 'Tls12') ) {
[System.Net.ServicePointManager]::SecurityProtocol = [System.Net.ServicePointManager]::SecurityProtocol::Tls13 -bor [System.Net.SecurityProtocolType]::Tls12
}
elseif ( $SupportedTLSversions -contains 'Tls12' ) {
[System.Net.ServicePointManager]::SecurityProtocol = [System.Net.SecurityProtocolType]::Tls12
}
else {
# Warn the user if TLS 1.2 and 1.3 are not supported, which may cause the download to fail
Write-Host "[Warn] TLS 1.2 and/or TLS 1.3 are not supported on this system. This download may fail!"
if ($PSVersionTable.PSVersion.Major -lt 3) {
Write-Host "[Warn] PowerShell 2 / .NET 2.0 doesn't support TLS 1.2."
}
}
# Initialize the attempt counter
$i = 1
While ($i -le $Attempts) {
# If SkipSleep is not set, wait for a random time between 3 and 15 seconds before each attempt
if (!($SkipSleep)) {
$SleepTime = Get-Random -Minimum 3 -Maximum 15
Write-Host "[Info] Waiting for $SleepTime seconds."
Start-Sleep -Seconds $SleepTime
}
# Provide a visual break between attempts
if ($i -ne 1) { Write-Host "" }
Write-Host "[Info] Download Attempt $i"
# Temporarily disable progress reporting to speed up script performance
$PreviousProgressPreference = $ProgressPreference
$ProgressPreference = 'SilentlyContinue'
try {
if ($PSVersionTable.PSVersion.Major -lt 4) {
# For older versions of PowerShell, use WebClient to download the file
$WebClient = New-Object System.Net.WebClient
$WebClient.DownloadFile($URL, $Path)
}
else {
# For PowerShell 4.0 and above, use Invoke-WebRequest with specified arguments
$WebRequestArgs = @{
Uri = $URL
OutFile = $Path
MaximumRedirection = 10
UseBasicParsing = $true
}
Invoke-WebRequest @WebRequestArgs
}
# Verify if the file was successfully downloaded
$File = Test-Path -Path $Path -ErrorAction SilentlyContinue
}
catch {
# Handle any errors that occur during the download attempt
Write-Host "[Warn] An error has occurred while downloading!"
Write-Host $_.Exception.Message
# If the file partially downloaded, delete it to avoid corruption
if (Test-Path -Path $Path -ErrorAction SilentlyContinue) {
Remove-Item $Path -Force -Confirm:$false -ErrorAction SilentlyContinue
}
$File = $False
}
# Restore the original progress preference setting
$ProgressPreference = $PreviousProgressPreference
# If the file was successfully downloaded, exit the loop
if ($File) {
$i = $Attempts
}
else {
# Warn the user if the download attempt failed
Write-Host "[Warn] File failed to download."
Write-Host ""
}
# Increment the attempt counter
$i++
}
# Final check: if the file still doesn't exist, report an error and exit
if (!(Test-Path $Path)) {
Write-Host "[Error] Failed to download file."
Write-Host "Please verify the URL of '$URL'."
exit 1
}
else {
# If the download succeeded, return the path to the downloaded file
return $Path
}
}
# Check's the two Uninstall registry keys to see if the app is installed. Needs the name as it would appear in Control Panel.
function Find-UninstallKey {
[CmdletBinding()]
param (
[Parameter(ValueFromPipeline)]
[String]$DisplayName,
[Parameter()]
[Switch]$UninstallString
)
process {
$UninstallList = New-Object System.Collections.Generic.List[Object]
$Result = Get-ChildItem HKLM:\Software\Wow6432Node\Microsoft\Windows\CurrentVersion\Uninstall\* | Get-ItemProperty |
Where-Object { $_.DisplayName -like "*$DisplayName*" }
if ($Result) { $UninstallList.Add($Result) }
$Result = Get-ChildItem HKLM:\Software\Microsoft\Windows\CurrentVersion\Uninstall\* | Get-ItemProperty |
Where-Object { $_.DisplayName -like "*$DisplayName*" }
if ($Result) { $UninstallList.Add($Result) }
# Programs don't always have an uninstall string listed here so to account for that I made this optional.
if ($UninstallString) {
# 64 Bit
$UninstallList | Select-Object -ExpandProperty UninstallString -ErrorAction Ignore
}
else {
$UninstallList
}
}
}
}
process {
$VerbosePreference = 'Continue'
$ErrorActionPreference = 'Stop'
if (-not (Test-IsElevated)) {
Write-Host "[Error] Access Denied. Please run with Administrator privileges."
exit 1
}
if (-not (Test-Path $OfficeInstallDownloadPath )) {
New-Item -Path $OfficeInstallDownloadPath -ItemType Directory | Out-Null
}
if (-not ($ConfigurationXMLFile)) {
Set-XMLFile
}
else {
Invoke-Download -URL $ConfigurationXMLFile -Path "$OfficeInstallDownloadPath\OfficeInstall.xml"
try {
[xml]::new().Load("$OfficeInstallDownloadPath\OfficeInstall.xml")
}
catch {
Write-Host "[Error] The XML file is not valid. Please check the file and try again."
exit 1
}
}
$ConfigurationXMLPath = "$OfficeInstallDownloadPath\OfficeInstall.xml"
$ODTInstallLink = Get-ODTURL
#Download the Office Deployment Tool
Write-Host "[Info] Downloading the Office Deployment Tool..."
Invoke-Download -URL $ODTInstallLink -Path "$OfficeInstallDownloadPath\ODTSetup.exe"
#Run the Office Deployment Tool setup
try {
Write-Host "[Info] Running the Office Deployment Tool..."
Start-Process "$OfficeInstallDownloadPath\ODTSetup.exe" -ArgumentList "/quiet /extract:$OfficeInstallDownloadPath" -Wait -NoNewWindow
}
catch {
Write-Host "[Warn] Error running the Office Deployment Tool. The error is below:"
Write-Host "$_"
exit 1
}
#Run the O365 install
try {
Write-Host "[Info] Downloading and installing Microsoft 365"
$Install = Start-Process "$OfficeInstallDownloadPath\Setup.exe" -ArgumentList "/configure $ConfigurationXMLPath" -Wait -PassThru -NoNewWindow
if ($Install.ExitCode -ne 0) {
Write-Host "[Error] Exit Code does not indicate success!"
exit 1
}
}
Catch {
Write-Host "[Warn] Error running the Office install. The error is below:"
Write-Host "$_"
}
$OfficeInstalled = Find-UninstallKey -DisplayName "Microsoft 365"
if ($CleanUpInstallFiles) {
Write-Host "[Info] Cleaning up install files..."
Remove-Item -Path $OfficeInstallDownloadPath -Force -Recurse
}
if ($OfficeInstalled) {
Write-Host "[Info] $($OfficeInstalled.DisplayName) installed successfully!"
if ($Restart) {
Write-Host "[Info] Restarting the computer in 60 seconds..."
Start-Process shutdown.exe -ArgumentList "-r -t 60" -Wait -NoNewWindow
}
exit 0
}
else {
Write-Host "[Error] Microsoft 365 was not detected after the install ran!"
exit 1
}
}
end {
}
Acesse mais de 700 scripts no NinjaOne Dojo
Cenários de exemplo de script
Cenário 1: Implementação em larga escala
Suponha que você seja um administrador de TI em uma empresa que está prestes a integrar cem novos funcionários. Instalar manualmente o Office 365 em cada computador seria uma tarefa difícil. Em vez disso, você pode usar este script do PowerShell para automatizar o processo. Usando o NinjaOne para executar o script remotamente em cada dispositivo, você pode padronizar suas instalações do Office 365 em toda a rede. Essa abordagem simplificada não apenas economiza tempo valioso, mas também garante uniformidade, um recurso essencial para o gerenciamento eficaz de uma grande infraestrutura de TI.
Saiba mais sobre como o NinjaOne pode melhorar a eficiência de sua infraestrutura de TI.
Link: https://www.ninjaone.com/efficiency/
Cenário 2: Força de trabalho remota
Com o aumento do trabalho remoto, muitas empresas têm funcionários trabalhando em vários locais com seus próprios dispositivos. Garantir que cada funcionário remoto tenha uma versão do Office 365 corretamente instalada e configurada pode ser um desafio. Ao distribuir esse script do PowerShell para sua força de trabalho remota, eles podem realizar a instalação por conta própria. O script garante que o Office 365 seja instalado corretamente e configurado com base nos padrões de sua organização.
Cenário 3: Gerenciamento de clientes MSP
Como um Provedor de serviços gerenciados (MSP) você pode estar gerenciando a TI de várias pequenas empresas, cada uma com suas próprias necessidades e configurações específicas. Com esse script do PowerShell, você pode criar vários arquivos de configuração XML adaptados às necessidades de cada cliente. Quando for o momento de instalar ou atualizar o Office 365 para um cliente, basta executar o script com o arquivode configuração apropriado. Isso garante uma configuração personalizada e consistente do Office 365 para cada um de seus clientes.
Cenário 4: Atualizações regulares
O Office 365 é atualizado regularmente pela Microsoft, e manter as instalações de sua organização atualizadas pode ser uma tarefa demorada. Com esse script, você pode programar atualizações automatizadas para serem executadas em um horário adequado, garantindo o mínimo de interrupção do fluxo de trabalho da sua equipe. O script usa a Office Deployment Tool para baixar e instalar a versão mais recente do Office 365, garantindo que sua equipe sempre tenha acesso aos recursos e às atualizações de segurança mais recentes.
Em cada um desses cenários, esse script do PowerShell pode simplificar significativamente o processo de instalação e gerenciamento do Office 365. Ao automatizar essas tarefas, você pode economizar tempo, reduzir o risco de erros e garantir uma experiência consistente e confiável do Office 365 para seus usuários.
Utilização do script em seu fluxo de trabalho
A integração desse script do PowerShell em seu fluxo de trabalho pode simplificar o processo de implantação do Office 365. Em vez de baixar e executar manualmente a Office Deployment Tool em cada máquina, o script pode ser executado remotamente a partir de um local central. Isso reduz as chances de erro humano e garante uma configuração padrão em todas as instalações.
Além disso, ao personalizar o arquivo de configuração XML, você pode adaptar a instalação do Office 365 às necessidades da sua organização. Isso inclui especificar a versão do Office 365, o canal de atualização e até mesmo os componentes individuais do Office a serem instalados.
Considerações finais
A automação é a melhor amiga de um profissional de TI, e o PowerShell oferece uma maneira eficiente de automatizar as instalações do Office 365. Esse prático script não apenas simplifica o processo de implementação, mas também oferece opções de personalização e funcionalidade de limpeza.
Ao integrar esse script ao seu fluxo de trabalho, você pode reduzir significativamente o tempo e o esforço envolvidos no gerenciamento das instalações do Office 365 em sua rede. Portanto, aproveite o poder do PowerShell e facilite as implantações do Office 365.
O NinjaOne pode otimizar suas operações automatizando tarefas repetitivas e demoradas. Sua interface amigável permite que técnicos de todos os níveis apliquem facilmente a automação em endpoints, incluindo scripts personalizados de uma extensa biblioteca, tornando a correção simples e intuitiva. Como Chris Hesler, da Crossroads Church, observou: “A NinjaOne nos ajudou… a reduzir as horas de trabalho… conseguimos trazer mais automação com a biblioteca de scripts para resolver nossos problemas recorrentes” Descubra o poder transformador da automação em suas operações de TI com o NinjaOne, uma ferramenta projetada com flexibilidade e intuitividade em seu núcleo.