back to top
Saturday, September 14, 2024
spot_img
InícioArtigosComo usar o PowerShell para automatizar instalações do Office 365

Como usar o PowerShell para automatizar instalações do Office 365

No mundo acelerado e exigente da TI, cada 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 da sua mesa. Esta postagem é para profissionais de TI e provedores de serviços gerenciados (MSPs) que estão procurando otimizar suas implantações do Office 365 usando o poder do PowerShell.

Por que automatizar com o PowerShell?

PowerShell é uma linguagem de script avançada e shell desenvolvida pela Microsoft. Ela é parte integrante do ecossistema do Windows desde o Windows 7, e seu poder e flexibilidade a tornaram uma ferramenta vital para muitos profissionais de TI e MSPs. Automatizar 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 certas configurações e até mesmo limpar após a instalação. Esse nível de personalização permite que profissionais de TI e MSPs garantam que o Office 365 seja implantado consistentemente em todas as máquinas, alinhando-se com as políticas e padrões de TI da empresa. 

Um mergulho profundo no script de instalação do PowerShell do Office 365

Vamos dar uma olhada mais de perto em um script PowerShell de exemplo para automatizar instalações do Office 365. Este script foi criado para instalar o Office 365 usando um arquivo de configuração personalizado ou um padrão. No caso de uma instalação falhar, o script fornecerá uma mensagem de erro, tornando a solução de problemas mais direta.

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, dando 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 uma reinicialização do sistema para funcionar corretamente. O script também é equipado com um mecanismo de limpeza que pode ser ativado para remover arquivos de instalação após o Office 365 ter sido instalado.

Microsoft Office 365 Installation PowerShell Script
#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.
.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.
By using this script, you indicate your acceptance of the following legal terms as well as our Terms of Use at https://www.mambosdeit.com/terms-of-use.
Ownership Rights: Mambosdeit owns and will continue to own all right, title, and interest in and to the script (including the copyright). Mambosdeit 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. Mambosdeit 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 Mambosdeit 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 Mambosdeit relating to your use of the script.
EULA: If you are a Mambosdeit customer, your use of the script is subject to the End User License Agreement applicable to you (EULA).
#>

[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 = [System.Convert]::ToBoolean($env:restartComputer)
)

begin {
if ($env:linkToConfigurationXml -and $env:linkToConfigurationXml -notlike "null") { $ConfigurationXMLFile = $env:linkToConfigurationXml }

$CleanUpInstallFiles = $True

# In case 'https://' is omitted from the URL.
if ($ConfigurationXMLFile -and $ConfigurationXMLFile -notmatch "^http(s)?://") {
Write-Warning "http(s):// is required to download the file. Adding https:// to your input...."
$ConfigurationXMLFile = "https://$ConfigurationXMLFile"
Write-Warning "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-Warning "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-Warning "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 {

[String]$MSWebPage = Invoke-RestMethod 'https://www.microsoft.com/en-us/download/confirmation.aspx?id=49117'

$MSWebPage | ForEach-Object {
if ($_ -match 'url=(https://.*officedeploymenttool.*\.exe)') {
$matches[1]
}
}

}
function Test-IsElevated {
$id = [System.Security.Principal.WindowsIdentity]::GetCurrent()
$p = New-Object System.Security.Principal.WindowsPrincipal($id)
if ($p.IsInRole([System.Security.Principal.WindowsBuiltInRole]::Administrator))
{ Write-Output $true }
else
{ Write-Output $false }
}

# Utility function for downloading files.
function Invoke-Download {
param(
[Parameter()]
[String]$URL,
[Parameter()]
[String]$Path,
[Parameter()]
[int]$Attempts = 3,
[Parameter()]
[Switch]$SkipSleep
)
Write-Host "URL given, Downloading the file..."

$i = 1
While ($i -le $Attempts) {
# Some cloud services have rate-limiting
if (-not ($SkipSleep)) {
$SleepTime = Get-Random -Minimum 3 -Maximum 15
Write-Host "Waiting for $SleepTime seconds."
Start-Sleep -Seconds $SleepTime
}

if ($i -ne 1) { Write-Host "" }
Write-Host "Download Attempt $i"

try {
# Invoke-WebRequest is preferred because it supports links that redirect, e.g., https://t.ly
if ($PSVersionTable.PSVersion.Major -lt 4) {
# Downloads the file
$WebClient = New-Object System.Net.WebClient
$WebClient.DownloadFile($URL, $Path)
}
else {
# Standard options
$WebRequestArgs = @{
Uri = $URL
OutFile = $Path
MaximumRedirection = 10
UseBasicParsing = $true
}

# Downloads the file
Invoke-WebRequest @WebRequestArgs
}

$File = Test-Path -Path $Path -ErrorAction SilentlyContinue
}
catch {
Write-Warning "An error has occurred while downloading!"
Write-Warning $_.Exception.Message

if (Test-Path -Path $Path -ErrorAction SilentlyContinue) {
Remove-Item $Path -Force -Confirm:$false -ErrorAction SilentlyContinue
}

$File = $False
}

if ($File) {
$i = $Attempts
}
else {
Write-Warning "File failed to download."
Write-Host ""
}

$i++
}

if (-not (Test-Path $Path)) {
Write-Error -Message "Failed to download file!" -Category InvalidResult -Exception (New-Object System.Deployment.Application.DeploymentDownloadException)
exit 1
}
}

# 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-Error -Message "Access Denied. Please run with Administrator privileges." -Category PermissionDenied -Exception (New-Object System.Security.SecurityException)
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"
}

$ConfigurationXMLFile = "$OfficeInstallDownloadPath\OfficeInstall.xml"
$ODTInstallLink = Get-ODTURL

#Download the Office Deployment Tool
Write-Host 'Downloading the Office Deployment Tool...'
Invoke-Download -URL $ODTInstallLink -Path "$OfficeInstallDownloadPath\ODTSetup.exe"

#Run the Office Deployment Tool setup
try {
Write-Host 'Running the Office Deployment Tool...'
Start-Process "$OfficeInstallDownloadPath\ODTSetup.exe" -ArgumentList "/quiet /extract:$OfficeInstallDownloadPath" -Wait -NoNewWindow
}
catch {
Write-Warning 'Error running the Office Deployment Tool. The error is below:'
Write-Warning $_
exit 1
}

#Run the O365 install
try {
Write-Host 'Downloading and installing Microsoft 365'
$Install = Start-Process "$OfficeInstallDownloadPath\Setup.exe" -ArgumentList "/configure $ConfigurationXMLFile" -Wait -PassThru -NoNewWindow

if ($Install.ExitCode -ne 0) {
Write-Error -Message "Exit Code does not indicate success!" -Category InvalidResult -Exception (New-Object System.Deployment.Application.DeploymentException)
exit 1
}
}
Catch {
Write-Warning 'Error running the Office install. The error is below:'
Write-Warning $_
}

$OfficeInstalled = Find-UninstallKey -DisplayName "Microsoft 365"

if ($CleanUpInstallFiles) {
Write-Host "Cleaning up install files..."
Remove-Item -Path $OfficeInstallDownloadPath -Force -Recurse
}

if ($OfficeInstalled) {
Write-Host "$($OfficeInstalled.DisplayName) installed successfully!"
if ($Restart) { Start-Process shutdown.exe -ArgumentList "-r -t 60" -Wait -NoNewWindow }
exit 0
}
else {
Write-Error -Message 'Microsoft 365 was not detected after the install ran!' -Category InvalidResult -Exception (New-Object System.Deployment.Application.DeploymentException)
exit 1
}
}
end {

}

Cenários de exemplo de script

Cenário 1: Implantação em larga escala

Suponha que você seja um administrador de TI em uma empresa que está prestes a contratar cem novos funcionários. Instalar manualmente o Office 365 em cada computador seria uma tarefa assustadora. 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 gerenciar efetivamente uma grande infraestrutura de TI.

Cenário 2: Força de trabalho remota 

Com o aumento do trabalho remoto, muitas empresas têm funcionários trabalhando de vários locais em seus próprios dispositivos. Garantir que cada trabalhador remoto tenha uma versão corretamente instalada e configurada do Office 365 pode ser um desafio. Ao distribuir este script do PowerShell para sua força de trabalho remota, eles podem executar a instalação eles mesmos. O script garante que o Office 365 seja instalado corretamente e configurado com base nos padrões da sua organização.

Cenário 3: Gerenciamento de clientes MSP

Como um Managed Service Provider (MSP) , você pode estar gerenciando TI para várias pequenas empresas, cada uma com suas próprias necessidades e configurações específicas. Com este script do PowerShell, você pode criar vários arquivos de configuração XML adaptados às necessidades de cada cliente. Quando for a hora de instalar ou atualizar o Office 365 para um cliente, basta executar o script com o arquivo de configuração apropriado . Isso garante uma configuração personalizada e consistente do Office 365 para cada um dos seus clientes. 

Cenário 4: Atualizações regulares  

O Office 365 é atualizado regularmente pela Microsoft, e manter as instalações da sua organização atualizadas pode ser uma tarefa demorada. Com este script, você pode agendar atualizações automatizadas para serem executadas em um horário adequado, garantindo interrupção mínima no fluxo de trabalho da sua equipe. O script usa a Ferramenta de Implantação do Office para baixar e instalar a versão mais recente do Office 365, garantindo que sua equipe sempre tenha acesso aos recursos e atualizações de segurança mais recentes. 

Em cada um desses cenários, este 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. 

Utilizando o script em seu fluxo de trabalho

Integrar este script do PowerShell ao seu fluxo de trabalho pode simplificar o processo de implantação do Office 365. Em vez de baixar e executar manualmente a Ferramenta de Implantação do Office em cada máquina, o script pode ser executado remotamente 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.

Pensamentos finais

A automação é a melhor amiga de um profissional de TI, e o PowerShell oferece uma maneira poderosa de automatizar instalações do Office 365. Este script útil não apenas simplifica o processo de implantação, mas também fornece opções de personalização e funcionalidade de limpeza.

Ao integrar este script ao seu fluxo de trabalho, você pode reduzir significativamente o tempo e o esforço envolvidos no gerenciamento de instalações do Office 365 em sua rede. Então, abrace o poder do PowerShell e torne as implantações do Office 365 uma moleza.

Domingos Massissa
Domingos Massissahttps://mambosdeit.com
IT professional with over eight years of experience in IT Consulting and Systems Administration. Specializes in developing and implementing secure and efficient solutions with expertise in configuring and maintaining Windows Server systems, information security policies, virtualization, and cloud migration. Proven track record in remote and in-person technical support with advanced Microsoft certifications. Passionate about optimizing processes and promoting organizational success through technological innovation and robust IT practices.MLSA Beta Microsoft
POSTAGEM RECENTES

DEIXE UMA RESPOSTA

Por favor digite seu comentário!
Por favor, digite seu nome aqui

- Advertisment -
Google search engine

ARTIGOS

POSTAGEM POPULAR

TUTORIAL

POSTAGENS

Recent Comments