Search is not available for this dataset
filename
stringlengths
5
114
module_name
stringlengths
8
67
content
stringlengths
0
282M
0install.psd1
0install-2.25.12
@{ ModuleVersion = '2.25.12' GUID = '89e16ee9-f9dd-4efd-b7a2-e0374958f6c0' Author = 'Bastian Eicher' CompanyName = '0install.net' Copyright = 'Copyright Bastian Eicher et al.' Description = 'Zero Install is a decentralized cross-platform software-installation system.' PowerShellVersion = '3.0' FunctionsToExport = @() #RequiredModules = @('PackageManagement') FileList = @('0install.dll') PrivateData = @{ PackageManagementProviders = '0install.dll' PSData = @{ Tags = @("PackageManagement","Provider") ProjectUri = 'https://0install.net' } } } # SIG # Begin signature block # MIIu0QYJKoZIhvcNAQcCoIIuwjCCLr4CAQExDzANBglghkgBZQMEAgEFADB5Bgor # BgEEAYI3AgEEoGswaTA0BgorBgEEAYI3AgEeMCYCAwEAAAQQH8w7YFlLCE63JNLG # KX7zUQIBAAIBAAIBAAIBAAIBADAxMA0GCWCGSAFlAwQCAQUABCAVK8gom5h25HPM # QayOMf6Xo9RkTuMgm6H2joZ62Jtu+aCCEzswggVyMIIDWqADAgECAhB2U/6sdUZI # k/Xl10pIOk74MA0GCSqGSIb3DQEBDAUAMFMxCzAJBgNVBAYTAkJFMRkwFwYDVQQK # ExBHbG9iYWxTaWduIG52LXNhMSkwJwYDVQQDEyBHbG9iYWxTaWduIENvZGUgU2ln # bmluZyBSb290IFI0NTAeFw0yMDAzMTgwMDAwMDBaFw00NTAzMTgwMDAwMDBaMFMx # CzAJBgNVBAYTAkJFMRkwFwYDVQQKExBHbG9iYWxTaWduIG52LXNhMSkwJwYDVQQD # EyBHbG9iYWxTaWduIENvZGUgU2lnbmluZyBSb290IFI0NTCCAiIwDQYJKoZIhvcN # AQEBBQADggIPADCCAgoCggIBALYtxTDdeuirkD0DcrA6S5kWYbLl/6VnHTcc5X7s # k4OqhPWjQ5uYRYq4Y1ddmwCIBCXp+GiSS4LYS8lKA/Oof2qPimEnvaFE0P31PyLC # o0+RjbMFsiiCkV37W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+dR0wX7PhRP2xn0wVA26nGeU9g8BsuY3 # IdOWwgeWkbJ+ZMN2taTGnftlKcSEykRa7xCJfljYkAzqgw/Lm+VBFb8cmQ3HiUPr # V8eqmy11VAfl5g5lYPCVsSlbmXCG1AoZpQzULuC9Ae91sVxeg1puo+HSx5gwrjAl # SmN6rM1VYGY/pp4t2YZb3cCPWZNfzVN5h1Gtq0nBSlehN8VHCqpgJ4rGdEifIXrW # Yg5H0oayzlPtIAorcfow42CCw0mHAUQLqp/ai3ZtqcVLrwm+WM7TNpQIIXk6XXVk # QwJF0bwkhEspr/WkwTh+xaSSSautDra6r6PEMFfWOODi4A/TE3mWMKfIfswv6yNg # RRm6PXNkETgff9x+xXVy1iXEnd4l24WfXsuQwrIxUFrH0o9/qb3+XC+IrRPisMoI # mtGMKfu7464VBENVYMu3TDOGIeYQhLoOtNde0WDtmP6twh2Y7oevfRrxoiEkPJif # UZ9qBzmvJvdL9KbUBrsL5RbLL7q0ThkqaA2VcBkdH8kGwo4yJtFC3wtPytvH5M9F # /4ULuqwGI90pekPwDq/Rat0tSDk6R0A7jJyRDJptHwZudPthCA== # SIG # End signature block
1C.ParserLST.psd1
1C.ParserLST-1.0.22.1
# # Module manifest for module '1C.ParserLST' # # Generated by: Pavel Aivazov # # Generated on: 14.05.2024 # @{ # Script module or binary module file associated with this manifest. RootModule = '1C.ParserLST.dll' # Version number of this module. ModuleVersion = '1.0.22.1' # Supported PSEditions CompatiblePSEditions = 'Core' # ID used to uniquely identify this module GUID = '474a382e-9fd8-4c12-95e0-20287afcdbab' # Author of this module Author = 'Pavel Aivazov' # Company or vendor of this module CompanyName = 'Unknown' # Copyright statement for this module Copyright = '(c) 2024 Pavel Aivazov. All rights reserved.' # Description of the functionality provided by this module Description = 'Parse .lst 1c cluster files' # Minimum version of the PowerShell engine required by this module PowerShellVersion = '7.4.0.0' # Name of the PowerShell host required by this module # PowerShellHostName = '' # Minimum version of the PowerShell host required by this module # PowerShellHostVersion = '' # Minimum version of Microsoft .NET Framework required by this module. This prerequisite is valid for the PowerShell Desktop edition only. DotNetFrameworkVersion = '8.0' # Minimum version of the common language runtime (CLR) required by this module. This prerequisite is valid for the PowerShell Desktop edition only. # ClrVersion = '' # Processor architecture (None, X86, Amd64) required by this module # ProcessorArchitecture = '' # Modules that must be imported into the global environment prior to importing this module # RequiredModules = @() # Assemblies that must be loaded prior to importing this module # RequiredAssemblies = @() # Script files (.ps1) that are run in the caller's environment prior to importing this module. # ScriptsToProcess = @() # Type files (.ps1xml) to be loaded when importing this module # TypesToProcess = @() # Format files (.ps1xml) to be loaded when importing this module # FormatsToProcess = @() # Modules to import as nested modules of the module specified in RootModule/ModuleToProcess # NestedModules = @() # Functions to export from this module, for best performance, do not use wildcards and do not delete the entry, use an empty array if there are no functions to export. FunctionsToExport = '*' # Cmdlets to export from this module, for best performance, do not use wildcards and do not delete the entry, use an empty array if there are no cmdlets to export. CmdletsToExport = 'Get-InfobasesPropertyList' # Variables to export from this module VariablesToExport = '*' # Aliases to export from this module, for best performance, do not use wildcards and do not delete the entry, use an empty array if there are no aliases to export. AliasesToExport = '*' # DSC resources to export from this module # DscResourcesToExport = @() # List of all modules packaged with this module # ModuleList = @() # List of all files packaged with this module # FileList = @() # Private data to pass to the module specified in RootModule/ModuleToProcess. This may also contain a PSData hashtable with additional module metadata used by PowerShell. PrivateData = @{ PSData = @{ # Tags applied to this module. These help with module discovery in online galleries. # Tags = @() # A URL to the license for this module. # LicenseUri = '' # A URL to the main website for this project. # ProjectUri = '' # A URL to an icon representing this module. # IconUri = '' # ReleaseNotes of this module # ReleaseNotes = '' # Prerelease string of this module # Prerelease = '' # Flag to indicate whether the module requires explicit user acceptance for install/update/save # RequireLicenseAcceptance = $false # External dependent modules of this module # ExternalModuleDependencies = @() } # End of PSData hashtable # ReleaseNotes ReleaseNotes = '' } # End of PrivateData hashtable # HelpInfo URI of this module # HelpInfoURI = '' # Default prefix for commands exported from this module. Override the default prefix using Import-Module -Prefix. # DefaultCommandPrefix = '' }
Load-ToBase1C.ps1
1C.Utils-0.4.0
. $PSScriptRoot\CommonUtils\CommonUtils.ps1 function Load-ToBase1C { <# .SYNOPSIS Загружает dt-файл в базу 1С. .DESCRIPTION Загружает dt-файл в базу 1С. dt-файл может быть задан как параметр или помещен в буфер обмена перед запуском скрипта. В случае если dt-файл расположен в локальной сети (начинается на \\), то перед загрузкой в базу он будет скопирован на локальный компьютер. Если указаная локальная база и имеются запущенные клиенты или конфигуратор к этой базе, то перед загрузкой будет предпринята попытка завершить все рабочие процессы. .PARAMETER FilePath Путь к dt-файлу. Псевдоним: dt .PARAMETER IBName Имя базы как оно задано в окне запуска предприятия. Псевдоним: ib .PARAMETER UserName Имя пользователя базы. Если не указан, то Администратор. Псевдоним: u .PARAMETER Password Пароль пользователя базы. Псевдоним: p .PARAMETER DirTemp Каталог приемник куда будут копироваться файлы из сети. Если не задан то файл копируется во временный каталог пользователя и после загрузки в базу удаляется. Если каталог указан, то файл после загрузки не удаляется. Псевдоним: tmp .PARAMETER OpenEnterprise После загрузки dt-файла запустить базу в режиме предприятия. Если параметр не задан, то база открывается в режиме конфигуратора. Псевдоним: ent .PARAMETER Wait После выполнения дождаться нажатия любой клавиши. Псевдоним: w #> [CmdletBinding()] param( [Alias("dt")][string]$FilePath, # Путь к Dt файлу [Alias("ib")][string]$IBName, # имя базы как оно указано в окне запуска предприятия [Alias("u")][string]$UserName='Администратор', # имя пользователя базы [Alias("p")][string]$Password, # пароль пользователя базы [Alias("tmp")][string]$DirTemp, # Каталог приемник куда копировать файлы из сети [Alias("ent")][switch]$OpenEnterprise, # после загрузки запустить в режиме предприятия (по умолчанию открывается конфигуратор) [Alias("w")][switch]$Wait # Ожидать нажатия любой клавиши (параметр переключатель) ) $TotalWatch = [System.Diagnostics.Stopwatch]::StartNew() # глобальный секундомер $Watch = [System.Diagnostics.Stopwatch]::StartNew() # секундомер операции if ('' -eq $FilePath){ $FileSource = Get-Clipboard }else{ $FileSource = $FilePath } $FileSource = $FileSource.Trim().Trim('`"') if ($null -eq $FileSource -or '' -eq $FileSource -or !(Test-Path $FileSource)){ Write-Warning "В буфере обмена не обнаружен путь к DT-файлу" return } if ('' -eq $DirTemp){ $DirTemp = $Env:TMP } $DirTemp = $DirTemp.TrimEnd('\') $FileFromNetwork = $false if ($FileSource[1] -eq '\') { $FileSource = $FileSource.Replace('/', '\') Write-Host ('Файл источник: {0}' -f $FileSource) $PartPath = $FileSource -split "\\" $NewFile = "$DirTemp\{0}" -f ($PartPath[-1]) Write-Host ('Файл получатель: {0}' -f $NewFile) Copy-Item $FileSource $NewFile $FileFromNetwork = $true $Watch.Stop() #Остановка секундомера операции Write-Host ("Затрачено на копирование: {0:hh}:{0:mm}:{0:ss}" -f $Watch.Elapsed) -ForegroundColor White '' } else { $NewFile = $FileSource } Stop-1C $IBName -Force '' $Designer1C = New-Designer1C -IBName $IBName -User $UserName -PasswordUser $Password $Designer1C.RestoreIB($NewFile) if ($OpenEnterprise) { $Designer1C.RunEnterprise() } else { $Designer1C.Open() } if ($FileFromNetwork -and $DirTemp -eq $Env:TMP){ Remove-Item $NewFile } $TotalWatch.Stop() #Остановка глобального секундомера Write-Host("`nВсего затрачено: {0:hh}:{0:mm}:{0:ss}" -f $TotalWatch.Elapsed) -ForegroundColor White if ($Wait) { Wait-PressAnyKey } } # end of Load-ToBase1C
Stop-1C.ps1
1C.Utils-0.4.0
. $PSScriptRoot\CommonUtils\CommonUtils.ps1 New-Alias -Name 'Kill-1C' -Value 'Stop-1C' #---------------------------------------------------------------------------------------- # Завершает процессы платформы 1С function Stop-1C { <# .SYNOPSIS Завершает процессы платформы 1С. .DESCRIPTION Выводит список всех запущенных процессов платформы 1С и ожидает подтверждения пользователя для завершения. Если передана строка поиска, то будут найдены все процессы платформы 1С содержащие в своей командной строке запуска переданную строку. Псевдоним: Kill-1C .PARAMETER Search Фрагмент строки запуска (или фрагменты через запятую) содержание которого будет определяться в командной строке запуска платформы 1С. Псевдонимы: s, filter, f .PARAMETER IncludeServer1C Включить процессы сервера 1С в список к удалению. По умолчанию процессы сервера 1С в список к удалению не включаются. .PARAMETER Force Завершить все найденные процессы без вопросов. .EXAMPLE #Завершить все запущенные процессы в режиме предприятия: Stop-1C ENTERPRISE .EXAMPLE #Завершить все процессы к конкретной базе: Stop-1C '/IBName"ИмяБазы"' #> [CmdletBinding()] param( [Alias("s", "filter", "f")][string]$Search, # строка поиска в командной строке запуска процесса [Parameter(HelpMessage="IncludeServer1C = false")][switch]$IncludeServer1C, # По умолчанию процессы сервера 1С исключены из удаления [switch]$Force # True = завершить процессы не спрашивая ) if ($IncludeServer1C){ $Process1C = Get-Process -Name 1cv8*,ragent,rmngr,rphost,dbda }else{ $Process1C = Get-Process -Name '1cv8*' } $LinesSearch = $Search.Split(",") foreach ($LineFind in $LinesSearch) { $Filter = "*$LineFind*" if ($IncludeServer1C){ $Process = $Process1C | Where-Object {$_.CommandLine -Like $Filter -or $_.CommandLine -Like ""} }else{ $Process = $Process1C | Where-Object {$_.CommandLine -Like $Filter} } Write-Verbose "Process = $Process" if($Process){ '' if ($Force) { $Result = Terminate-Process $Process -Force } else { $Result = Terminate-Process $Process if (Get-Permission "Завершить"){ '' $Result = Terminate-Process $Process -Force } } } } # foreach $LinesSearch }# end of Stop-1C #---------------------------------------------------------------------------------------- # Завершает переданные процессы function Terminate-Process { [CmdletBinding()] param( $Process, # массив процессов [switch]$Force ) $Result = $false $Force = $Force -and $DebugPreference -eq 'SilentlyContinue' $Text="Будет завершен процесс:"; $Color='White' if($Force){$Text="Завершен процесс:"; $Color='Yellow'} foreach($Proc in $Process) { Write-Host $Text -ForegroundColor DarkGray Write-Host ("{0} PID = {1}; CommandLine = {2}" -f $Proc.Name, $Proc.Id, $Proc.CommandLine) -ForegroundColor $Color if ($Force){ Get-Process -Id $Proc.Id | ForEach-Object{$_.Kill()} } } Return $Result }# end Terminate-Process
Common1C.ps1
1C.Utils-0.4.0
. $PSScriptRoot\CommonUtils\CommonUtils.ps1 #---------------------------------------------------------------------------------------- # Выделяет из переданной строки каталог установки, номер весрии платформы и путь к exe файлу function Get-VersionCatalogExe { <# .SYNOPSIS Из переданной строки выделяет каталог установки и(или) номер версии платформы и(или) путь к exe файлу. .DESCRIPTION Входной строкой может быть пустая строка, каталог установки 1С, номер версии платформы, полный путь к exe файлу. Если передан полный путь к exe файлу, то из него будут выделены каталог установки и версия платформы, если это возможно. Возвращается словарь с тремя ключами InstalledLocation1C, VersionPlatform1C, FileExe .PARAMETER InputString Входная строка для разбора. #> [CmdletBinding()] param( [string]$InputString ) $Result = @{'InstalledLocation1C' = ''; 'VersionPlatform1C' = ''; 'FileExe' = ''} if ($InputString -match '^\d+\.\d+\.\d+\.\d+$') { $Result['VersionPlatform1C'] = $InputString } elseif ('' -ne $InputString -and (Test-Path $InputString)) { $DirFile = Get-Item $InputString if ($DirFile.PSIsContainer) { $InstalledLocation1C = $DirFile.FullName if ($InstalledLocation1C[-1] -ne '\' -or $InstalledLocation1C[-1] -ne '/') { $InstalledLocation1C += '\' } $Result['InstalledLocation1C'] = $InstalledLocation1C } elseif ($DirFile.Extension -eq '.exe') { $FileExe = $InputString if ($FileExe -match '\\\d+\.\d+\.\d+\.\d+\\' -or $FileExe -match '\/\d+\.\d+\.\d+\.\d+\/'){ $Result['VersionPlatform1C'] = $Matches[0].Trim('\').Trim('/') $Result['InstalledLocation1C'] = $FileExe.Substring(0, $FileExe.IndexOf($Result['VersionPlatform1C'])) } $Result['FileExe'] = $FileExe } } Write-Verbose ('FileExe = {0}' -f $FileExe) Write-Verbose ('InstalledLocation1C = {0}' -f $InstalledLocation1C) Write-Verbose ('VersionPlatform1C = {0}' -f $VersionPlatform1C) $Result }# end of Get-VersionCatalogExe #---------------------------------------------------------------------------------------- # Получает исполняемый файл платформы function Get-Exe1C { <# .SYNOPSIS Получает исполняемый файл платформы. .DESCRIPTION По переданной строке поиска пытается определить исполняемый файл платформы. Входной строкой поиска может быть: - пустая строка - будет произведен поиск исполняемого файла в стандартном каталоге последней установленной версии платформы - каталог установки 1С - в указанном каталоге будет произведен поиск исполняемого файла последней установленной версии - номер версии платформы в формате 8.3.XX.XXXX - в стандартном каталоге установки, в подкаталоге с заданным номером версии будет произведен поиск исполняемого файла - можно передать сам exe файл, тогда без поиска вернется он же Если переданный каталог установки или файл не существуют или не установлена переденная версия, то возвращается исполняемый файл последней установленной версии найденный в стандартном каталоге установки. Дополнительно можно передать имя исполняемого файла (по умолчанию 1cv8). .PARAMETER SearchString Входная строка поиска. .PARAMETER FileName Имя исполняемого файла (по умолчанию 1cv8). #> [CmdletBinding()] param( [string]$Search, [string]$FileName='1cv8' ) $ResultFileExe = '' $InstalledLocation1C = Get-InstalledLocation1C $Name = Get-VersionCatalogExe $Search if ('' -ne $Name.InstalledLocation1C) { $InstalledLocation1C = $Name.InstalledLocation1C } #region GetExe if ('' -ne $Name.FileExe -and (Test-Path $Name.FileExe)) { $ResultFileExe = $Name.FileExe } elseif ('' -ne $Name.VersionPlatform1C) { $CatalogInstalled1C = $InstalledLocation1C + $Name.VersionPlatform1C if (Test-Path $CatalogInstalled1C) { $FileExe = Get-ChildItem $CatalogInstalled1C -Name "$FileName.exe" -Recurse | Sort-Object -Descending if ($FileExe -is 'System.Array' -and 0 -ne $FileExe.Length) { $FileExe = $FileExe[0] } if ($CatalogInstalled1C[-1] -ne '\' -or $CatalogInstalled1C[-1] -ne '/') { $CatalogInstalled1C += '\' } if ($null -ne $FileExe) { $ResultFileExe = $CatalogInstalled1C + $FileExe } } } #endregion GetExe if ('' -eq $ResultFileExe) { # Найдем последнюю установленную версию в стандартном (или переданном) каталоге установки $FileExe = Get-ChildItem $InstalledLocation1C -Name "$FileName.exe" -Recurse | Sort-Object -Descending if ($FileExe -is 'System.Array' -and 0 -ne $FileExe.Length) { $FileExe = $FileExe[0] } if ($null -ne $FileExe) { $ResultFileExe = $InstalledLocation1C + $FileExe } } $ResultFileExe }# end Get-Exe1C #---------------------------------------------------------------------------------------- # Определяет каталог установки 1С function Get-InstalledLocation1C { <# .SYNOPSIS Определяет каталог установки 1С. .DESCRIPTION По файлам 1cestart.cfg пытается определить каталог установки платформы. .PARAMETER v82 Возвращает только каталог версии платформы 8.2. #> [CmdletBinding()] param( [switch]$v82 ) $Path1cv8 = @() $FileName = '\1c\1CEStart\1CEStart.cfg' $FilePath = $Env:ALLUSERSPROFILE + $FileName Get-Content $FilePath | Where-Object {$_ -match "InstalledLocation="} | ForEach-Object { $Path1cv8 += ($_ -split '=')[1] } $FilePath = $Env:APPDATA + $FileName Get-Content $FilePath | Where-Object {$_ -match "InstalledLocation="} | ForEach-Object { $Path1cv8 += ($_ -split '=')[1] } $Filter = "1cv8$" if ($v82){ $Filter = "1cv82" } $Path1cv8 = $Path1cv8 | Sort-Object -Descending | Where-Object {$_ -match $Filter} $Path1cv8 | ForEach-Object{ Write-Verbose $_ } $Result = $Path1cv8 if ($Path1cv8 -is [System.Array]){ $Result = $Path1cv8[0] } if (($null -eq $Path1cv8) -or !(Test-path $Result)) { $Result = 'C:\Program Files\1cv8' if (!(Test-path $Result)){ $Result = 'C:\Program Files (x86)\1cv8' if (!(Test-Path $Result)){ Write-Warning 'Не найдена платформа 1С.' } } } $Result+'\' }# end of Get-InstalledLocation1C()
Designer1C.ps1
1C.Utils-0.4.0
. $PSScriptRoot\CommonUtils\classLog.ps1 . $PSScriptRoot\CommonUtils\CommonUtils.ps1 . $PSScriptRoot\Common1C.ps1 function New-Designer1C { <# .SYNOPSIS Возвращает экземпляр класса Designer1c. .DESCRIPTION Создает объект класса Designer1C позволяющий работать с командной строкой 1С в объектной технике. .NOTES В методе класса CreateInfoBaseSrvr для задания типа СУБД используется перечисление: enum TypeDBMS { MSSQLServer, PostgreSQL, IBMDB2, OracleDatabase } Перечисление добавляется в текущую сессию методом AddType при первом вызове New-Designer1C. После после чего оно будет доступно как обычный тип. Например: [TypeDBMS]::MSSQLServer .PARAMETER PathBase Задается адрес расположения базы (можно установить методом SetBase): - для файловой базы c:\CatalogBases1C\NameBase - для клиент-серверной базы NameServer[:NumberPort]\NameBase - для базы на веб-сервере http://NameWebServer/NameBase Псевдонимы: b .PARAMETER UserName Имя пользователя базы (можно установить методом SetUserBase). Псевдонимы: u .PARAMETER PasswordUser Пароль пользователя базы (можно установить методом SetUserBase). Псевдонимы: p .PARAMETER IBName Имя базы как оно задано в окне запуске 1С. Псевдонимы: ib .PARAMETER Platform Номер версии платформы 8.3.XX.XXXX. Если не задан, то будет произведен поиск в стандартном каталоге установки последней установленной версии платформы. Игнорируется если задан параметр IBName. .PARAMETER LogFile Полный путь к лог-файлу. Псевдонимы: l, log .PARAMETER Settings Путь к файлу значений полей класса выгруженных методом ExportToYAML или ExportToJSON (можно загрузить методом ImportFrom) Псевдонимы: set, import .EXAMPLE #Создать объект для работы с командной строкой платформы $Designer = New-Designer1C 'c:\Namebase' 'Администратор' .EXAMPLE #Создать базу на сервере 1С при этом сервер СУБД имеет такое же имя как и имя сервера 1С. #По умолчанию тип СУБД имеет значение перечисления [TypeDBMS]::MSSQLServer #Тип перечисления добавляется в текущую сессию методом AddType при первом вызове New-Designer1C. $Designer = New-Designer1C 'ИмяСервера1С\ИмяБазы' 'Администратор' $Designer.CreateInfoBaseSrvr('ИмяАдминистратораСУБД', 'ПарольАдминистратораСУБД') .EXAMPLE #Создать базу на сервере 1С при этом имя сервера СУБД отличается от имени сервера 1С. #Для задания типа СУБД используется явное указание значения перечисления. #Тип перечисления добавляется в текущую сессию методом AddType при первом вызове New-Designer1C. $Designer = New-Designer1C 'ИмяСервера1С\ИмяБазы' 'Администратор' $Designer.CreateInfoBaseSrvr([TypeDBMS]::PostgreSQL, 'ИмяСервераСУБД', 'ИмяАдминистратораСУБД', 'ПарольАдминистратораСУБД') .EXAMPLE #Посмотреть все свойства и методы класса (со всеми перегрузками методов) New-Designer1C | Get-Member | Format-List #> [CmdletBinding()] param( [Alias("b")][string]$PathBase='', [Alias("u")][string]$UserName='', [Alias("p")][string]$PasswordUser='', [Alias("ib")][string]$IBName='', [string]$Platform='', [Alias("l", "log")][string]$LogFile='', [Alias("set", "import")][string]$Settings='' ) Add-Type -TypeDefinition " public enum TypeDBMS { MSSQLServer, PostgreSQL, IBMDB2, OracleDatabase }" $Designer = New-Object Designer1C($PathBase, $UserName, $PasswordUser, $IBName, $Platform, $LogFile) if ('' -ne $Settings) { $Designer.ImportFrom($Settings) } $Designer }# end New-Designer1C # Перечисление типы серверов баз данных для создания базы данных на сервере enum TypeDBMS { MSSQLServer PostgreSQL IBMDB2 OracleDatabase } # описание класса class Designer1C { #region Properties hidden [string]$PathBase='' hidden [string]$ConnectionString='' hidden [hashtable]$UserBase=$null [String]$Storage='' hidden [hashtable]$UserStorage=$null hidden [string]$IBName='' hidden [string]$Platform='' hidden [string]$Exe1cv8='' $Log = $null hidden [string]$NameBase='' [bool]$Debug=$false hidden [bool]$Done=$false hidden [string]$DumpResult='' #endregion Properties #region Constructor Designer1C() { $this.SetBase('', '', '', '', '','') } Designer1C([String]$PathBase, [String]$UserName, [String]$PasswordUser, [String]$IBName, [String]$Platform, [string]$LogFile) { $this.SetBase($PathBase, $UserName, $PasswordUser, $IBName, $Platform, $LogFile) } #endregion Constructor #region Methods [bool] CommandIsDone() { return $this.Done } #region SetBase [void] SetBase() { $this.SetBase('', '', '', '', '','') } [void] SetBase([String]$PathBase) { $this.SetBase($PathBase, '', '', '', '','') } [void] SetBase([String]$PathBase, [String]$UserName, [String]$PasswordUser) { $this.SetBase($PathBase, $UserName, $PasswordUser, '', '','') } [void] SetBase([String]$PathBase, [String]$UserName, [String]$PasswordUser, [String]$LogFile) { $this.SetBase($PathBase, $UserName, $PasswordUser, '', '', $LogFile) } [void] SetBase([String]$PathBase, [String]$UserName, [String]$PasswordUser,` [String]$IBName, [String]$Platform, [string]$LogFile) { $this.PathBase = $PathBase $this.SetLog($LogFile) $this.IBName = $IBName $this.Platform = $Platform $this.SetNameBase() $this.SetConnectionString() if ('' -ne $UserName){ $this.SetUserBase($UserName, $PasswordUser) } $this.SetExe1cv8() }# end SetBase #endregion SetBase [void] SetLog() { $this.SetLog('', $false)} [void] SetLog([string]$FullName) { $this.SetLog($FullName, $true)} [void] SetLog([string]$FullName, [bool]$Append) { if ($null -eq $this.Log) { $this.Log = New-Log $FullName -Append:$Append } elseif ('' -ne $FullName) { $this.Log.SetFullName($FullName, $Append) } }# end SetLog [string] GetNameBase() { if ('' -eq $this.NameBase) { $this.SetNameBase() } return $this.NameBase } hidden [void] SetNameBase() { $this.NameBase = $this.IBName if ('' -ne $this.PathBase) { if ($this.PathBase.ToLower().IndexOf('http://') -ge 0 ` -or $this.PathBase.ToLower().IndexOf('https://') -ge 0 ` -or (Test-Path $this.PathBase) ` -or $this.PathBase.split('\').Length -eq 2) { $Path = $this.PathBase.TrimEnd('\').TrimEnd('/') $Index = $Path.LastIndexOf('\') if($Index -lt 0) {$Index = $Path.LastIndexOf('/')} $this.NameBase = $Path.Substring($Index+1) } } }# end SetNameBase hidden SetConnectionString() { if ('' -ne $this.IBName) { $this.ConnectionString = '/IBName "{0}"' -f $this.IBName.Replace('"','""') } elseif ('' -ne $this.PathBase) { if ($this.PathBase.ToLower().IndexOf('http://') -ge 0 ` -or $this.PathBase.ToLower().IndexOf('https://') -ge 0) { $this.ConnectionString = '/WS"{0}"' -f $this.PathBase } elseif (Test-Path $this.PathBase) { $this.ConnectionString = '/F"{0}"' -f $this.PathBase } elseif ($this.PathBase.split('\').Length -eq 2) { $this.ConnectionString = '/S"{0}"' -f $this.PathBase } } }# end SetConnectionString hidden [string] GetConnectionString() { return $this.ConnectionString } [string] GetIBName(){ return $this.IBName } [void] SetIBName([string]$IBName){ $this.SetIBName($IBName, '', '', '') } [void] SetIBName([string]$IBName, [String]$UserName, [String]$PasswordUser, [string]$LogFile){ $this.IBName = $IBName $this.SetLog($LogFile) $this.PathBase = '' $this.Platform = '' if ('' -ne $UserName){ $this.SetUserBase($UserName, $PasswordUser) } $this.SetNameBase() $this.SetConnectionString() $this.SetExe1cv8() } [string] GetExe1cv8() { return $this.Exe1cv8 } #region SetExe1cv8 <# В SetExe1cv8 можно передать: - пустую строку - будет произведен поиск в стандартном каталоге последней установленной версии платформы - каталог установки 1С - будет произведен поиск последней установленной версии - номер версии платформы в формате 8.3.XX.XXXX - в стандартном каталоге установки, в подкаталоге с заданным номером версии будет произведен поиск 1cv8.exe - непосредственно сам exe файл платформы - если не задан IBName, то установит его, если задан IBName устанавливает '\common\1cestart.exe' из стандартного каталога #> [void] SetExe1cv8() { $this.SetExe1cv8('') } [void] SetExe1cv8([string]$VersionCatalogExe) { $this.Exe1cv8 = Get-Exe1C $VersionCatalogExe $Name = Get-VersionCatalogExe $this.Exe1cv8 $this.Platform = $Name.VersionPlatform1C $InstalledLocation1C = Get-InstalledLocation1C if ('' -ne $Name.InstalledLocation1C) { $InstalledLocation1C = $Name.InstalledLocation1C } if ('' -ne $this.IBName){ $this.Platform = '' $this.Exe1cv8 = $InstalledLocation1C + 'common\1cestart.exe' } }# end SetExe1cv8 #endregion SetExe1cv8 [string] GetPlatform(){ return $this.Platform } [hashtable] GetUserBase() { if ($null -eq $this.UserBase){ $this.UserBase = @{Name=''; Password=''} } return $this.UserBase }# end GetUserBase [void] SetUserBase([string]$UserName) { $this.SetUserBase($UserName, '') }# end SetUserBase [void] SetUserBase([string]$UserName, [string]$UserPassword) { $this.UserBase = @{Name=$UserName; Password=$UserPassword} }# end SetUserBase hidden [string] GetLoginBase() { $Login = @() if ($null -ne $this.UserBase){ if ('' -ne $this.UserBase.Name){ $Login += '/N"{0}"' -f $this.UserBase.Name.Trim('"') if ('' -ne $this.UserBase.Password){ $Login += '/P"{0}"' -f $this.UserBase.Password } } } return ([string]$Login).Trim() }# end GetLoginBase [void] SetStorage([string]$Storage, [string]$UserName) { $this.SetStorage($Storage, $UserName, '') } [void] SetStorage([string]$Storage, [string]$UserName, [string]$UserPassword) { $this.Storage = $Storage $this.UserStorage = @{Name=$UserName; Password=$UserPassword} }# end SetStorage [hashtable] GetUserStorage() { if ($null -eq $this.UserStorage){ $this.UserStorage = @{Name=''; Password=''} } return $this.UserStorage }# end GetUserStorage hidden [string] GetLoginStorage() { $Login = @() if ('' -ne $this.Storage) { $Login += '/ConfigurationRepositoryF"{0}"' -f $this.Storage.Trim('"') if ($null -ne $this.UserStorage){ if ('' -ne $this.UserStorage.Name){ $Login += '/ConfigurationRepositoryN"{0}"' -f $this.UserStorage.Name.Trim('"') if ('' -ne $this.UserStorage.Password) { $Login += '/ConfigurationRepositoryP"{0}"' -f $this.UserStorage.Password } } } } return ([string]$Login).Trim() }# end GetLoginStorage #region ExportTo [string] ExportToYAML(){ return $this.ExportTo('', 'YAML') } [string] ExportToYAML([string]$PathFile){ return $this.ExportTo($PathFile, 'YAML') } [string] ExportToJSON(){ return $this.ExportTo('', 'JSON') } [string] ExportToJSON([string]$PathFile){ return $this.ExportTo($PathFile, 'JSON') } hidden [string] ExportTo([string]$PathFile, [string]$Format){ $Result = '' if ('' -eq $PathFile) { if ('JSON' -eq $Format) { $Result = ConvertTo-Json $this } elseif ('YAML' -eq $Format){ $Result = ConvertTo-Yaml -Data $this } } else { if ('JSON' -eq $Format) { ConvertTo-Json $this | Out-File $PathFile } elseif ('YAML' -eq $Format) { ConvertTo-Yaml -Data $this | Out-File $PathFile } } return $Result } #endregion ExportTo #region ImportFrom [void] ImportFrom([string]$PathFile){ if ($null -eq $PathFile -or '' -eq $PathFile -or !(Test-Path $PathFile)){ return } $string_cfg = Get-Content $PathFile -Raw $FormatConfig = "YAML" if ($string_cfg.Trim()[0] -eq "{") { $FormatConfig = "JSON" } $DataClass = $null if("YAML" -eq $FormatConfig) { $DataClass = ConvertFrom-Yaml -Yaml $string_cfg } elseif("JSON" -eq $FormatConfig) { $DataClass = ConvertFrom-Json $string_cfg | Convert-PSObjectToHashtable } if ($null -eq $DataClass) { Write-Warning 'Не удалось распознать формат данных. На текущий момент поддерживаются форматы YAML и JSON.' return } $this.PathBase = $DataClass.PathBase $this.SetLog($DataClass.Log.FullName) $this.Log.Silent = $DataClass.Log.Silent $this.Log.TemplateMessage = $DataClass.Log.TemplateMessage $this.Log.Symbol = $DataClass.Log.Symbol $this.Log.AmountSymbol = $DataClass.Log.AmountSymbol $this.IBName = $DataClass.IBName $this.Platform = $DataClass.Platform $this.NameBase = $DataClass.NameBase $this.SetConnectionString() $this.UserBase = $DataClass.UserBase $this.Storage = $DataClass.Storage $this.UserStorage = $DataClass.UserStorage if ('' -eq $this.IBName) { $this.Platform = $DataClass.Platform $this.Exe1cv8 = $DataClass.Exe1cv8 } else { $this.SetExe1cv8() } if ($null -ne $DataClass.Debug) { $this.Debug = $DataClass.Debug } if ($null -ne $DataClass.Done) { $this.Done = $DataClass.Done } } #endregion ImportFrom #region RunEnterprise [void] RunEnterprise(){ $Wait = $false $Enterprise = $true $this.Run('', @(), $Wait, $Enterprise) } [void] RunEnterprise([string]$Command){ $Wait = $false $Enterprise = $true $this.Run($Command, @(), $Wait, $Enterprise) } [void] RunEnterprise([string]$Command, [bool]$Wait){ $Enterprise = $true $this.Run($Command, @(), $Wait, $Enterprise) } [void] RunEnterprise([string]$Command, [System.Array]$Parametrs){ $Wait = $false $Enterprise = $true $this.Run($Command, $Parametrs, $Wait, $Enterprise) } [void] RunEnterprise([string]$Command, [System.Array]$Parametrs, [bool]$Wait){ $Enterprise = $true $this.Run($Command, $Parametrs, $Wait, $Enterprise) } #endregion RunEnterprise [void] Open(){ $Wait = $false $Enterprise = $false $this.Run('', @(), $Wait, $Enterprise) } #region Run [void] Run([string]$Command){ $Wait = $true $Enterprise = $false $this.Run($Command, @(), $Wait, $Enterprise) } [void] Run([string]$Command, [bool]$Wait){ $Enterprise = $false $this.Run($Command, @(), $Wait, $Enterprise) } [void] Run([string]$Command, [System.Array]$Parametrs){ $Wait = $true $Enterprise = $false $this.Run($Command, $Parametrs, $Wait, $Enterprise) } [void] Run([string]$Command, [System.Array]$Parametrs, [bool]$Wait){ $Enterprise = $false $this.Run($Command, $Parametrs, $Wait, $Enterprise) } [void] Run([string]$Command, [System.Array]$Parametrs, [bool]$Wait, [bool]$Enterprise){ $WatchKey = [System.Diagnostics.Stopwatch]::StartNew() # секундомер команды $WatchKey.Start() $Command = $Command.Replace("<NameBase>", $this.GetNameBase()) $Command = $Command.Replace("<Date>", (Get-Date -Format yyyyMMdd)) $Command = $Command.Replace("<Time>", (Get-Date -Format hhmm)) $Arguments = $this.GetArguments($Command, $Parametrs) if ($Enterprise){ $Arguments[0] = 'ENTERPRISE' } if ($Wait -and '' -ne $this.log.GetFullName()){ $Arguments += ("/Out {0} -NoTruncate" -f $this.log.GetFullName()) } #/DumpResult <имя файла> #Записать результат работы конфигуратора в файл. Результат ‑ число (0 ‑ в случае успеха). $tmpFile = New-TemporaryFile if ('' -ne $this.DumpResult) { $tmpFile = $this.DumpResult } $Arguments += ("/DumpResult {0}" -f $tmpFile) $Indent = 12 if ('' -eq $Command){ $this.Log.Write("Запуск".PadRight($Indent) + $Arguments[0]) } else { $this.Log.Write("Выполняется".PadRight($Indent) + $Command) } #$Silent = ('' -ne $this.Log.FullName) $Silent = $true $RealCommand = '"{0}" {1}' -f $this.exe1cv8, [string]$Arguments $this.Log.Write(("Команда".PadRight($Indent) + $RealCommand), $Silent) $this.Done = $false if(!$this.Debug) { $process1cv8 = Start-Process -FilePath $this.exe1cv8 -ArgumentList $Arguments -Wait:$Wait -PassThru $buffer = (Get-Content $tmpFile) if ($buffer.Length -gt 0) { Write-Verbose ('process1cv8.ExitCode = {0}' -f $process1cv8.ExitCode) Write-Verbose ('DumpResult = {0} (0 = успех, 1 = ошибка)' -f $buffer[0]) $this.Done = ($buffer[0] -eq '0') } } $WatchKey.Stop() #Запись в лог замера времени для ключа if ($Wait){ $this.Log.Write("Затрачено".PadRight($Indent) + ("{0:hh}:{0:mm}:{0:ss}" -f $WatchKey.Elapsed)) } Remove-Item -Path $tmpFile }# end Run [System.Array] GetArguments(){ return GetArguments('', @()) } [System.Array] GetArguments([String]$Command){ return GetArguments($Command, @()) } hidden [System.Array] GetArguments([string]$Command, [System.Array]$Parametrs){ $Arguments = @('DESIGNER') if ($Command.ToUpper().Contains("CREATEINFOBASE")){ $Arguments = @('CREATEINFOBASE') } else { $Arguments += $this.GetConnectionString() $Arguments += $this.GetLoginBase() $Arguments += $this.GetLoginStorage() $Arguments += $Command } $Arguments += [string]$Parametrs $Arguments = $Arguments | Where-Object{$_ -ne ''} return $Arguments } #endregion Run #endregion Methods #region CreateInfoBase #region File [void] CreateInfoBaseFile() { $this.CreateInfoBaseFile('') } [void] CreateInfoBaseFile([string]$NameToList) { $Param = @(("File={0};" -f $this.PathBase)) if ('' -ne $NameToList){ $Param += "/AddList $NameToList" } $this.Run("CREATEINFOBASE", $Param) } #endregion File #region Srvr <# Параметры подключения: Srvr - ИмяСервера[:НомерПорта] <- $this.PathBase <- NameServer:Port\NameBase Ref - Имя базы на сервере 1С <- $this.PathBase <- NameServer:Port\NameBase DBMS - Тип сервера СУБД может быть: - MSSQLServer - PostgreSQL - IBMDB2 - OracleDatabase DBSrvr - Имя сервера СУБД DB - имя базы на сервере СУБД = Ref DBUID - логин пользователя СУБД с правами на создание баз DBPwd - пароль пользователя СУБД SQLYOffs - смещение дат = 2000 Locale - Если параметр не задан, то будут использованы региональные установки текущей информационной базы. Допустимые значения такие же, как у параметра <Форматная строка> метода Формат(). Необязательный. CrSQLDB - создать базу в случае ее отсутствия. Может быть Y или N без учета регистра. Если не задан, то N. SchJobDn - В созданной базе запретить выполнение регламентных созданий. Может быть Y или N без учета регистра. Если не задан, то N. SUsr - Имя администратора кластера, в котором должен быть создан начальный образ. Параметр необходимо задавать, если в кластере определены администраторы и для них аутентификация операционной системы не установлена или не подходит. SPwd - Пароль администратора кластера. #> hidden [void] TestTypeDBMS([TypeDBMS]$DBMS){ $this.Log.OutValue("$DBMS = [TypeDBMS]::MSSQLServer", $DBMS -eq [TypeDBMS]::MSSQLServer) $this.Log.OutValue("$DBMS = [TypeDBMS]::PostgreSQL", $DBMS -eq [TypeDBMS]::PostgreSQL) $this.Log.OutValue("$DBMS = [TypeDBMS]::IBMDB2", $DBMS -eq [TypeDBMS]::IBMDB2) $this.Log.OutValue("$DBMS = [TypeDBMS]::OracleDatabase", $DBMS -eq [TypeDBMS]::OracleDatabase) } [void] CreateInfoBaseSrvr([string]$UserDBSrvr, [string]$PwdUserDBSrvr) { $this.CreateInfoBaseSrvr([TypeDBMS]::MSSQLServer,'', '', $UserDBSrvr, $PwdUserDBSrvr, 'Y', 'N', '', '', '') } [void] CreateInfoBaseSrvr([string]$UserDBSrvr, [string]$PwdUserDBSrvr, [string]$NameToList) { $this.CreateInfoBaseSrvr([TypeDBMS]::MSSQLServer,'', '', $UserDBSrvr, $PwdUserDBSrvr, 'Y', 'N', $NameToList, '', '') } [void] CreateInfoBaseSrvr([TypeDBMS]$DataBaseManagmentSystem, [string]$NameDBSrvr,` [string]$UserDBSrvr, [string]$PwdUserDBSrvr) { $this.CreateInfoBaseSrvr($DataBaseManagmentSystem, $NameDBSrvr, '', $UserDBSrvr, $PwdUserDBSrvr,` 'Y', 'N', '', '', '') } [void] CreateInfoBaseSrvr([TypeDBMS]$DataBaseManagmentSystem, [string]$NameDBSrvr,` [string]$UserDBSrvr, [string]$PwdUserDBSrvr, [string]$NameToList) { $this.CreateInfoBaseSrvr($DataBaseManagmentSystem, $NameDBSrvr, '', $UserDBSrvr, $PwdUserDBSrvr,` 'Y', 'N', $NameToList, '', '') } [void] CreateInfoBaseSrvr([TypeDBMS]$DataBaseManagmentSystem, [string]$NameDBSrvr, [string]$NameDB,` [string]$UserDBSrvr, [string]$PwdUserDBSrvr,` [string]$CreateDBifNull, [string]$ScheduleJobOff, [string]$NameToList,` [string]$AdminCluster, [string]$PwdAdminCluster) { $Names = $this.PathBase.Split('\') $Srvr = $Names[0] $Ref = $Names[1] $Srvr1C = "Srvr=$Srvr;Ref=$Ref;" if ('' -eq $NameDBSrvr){ $NameDBSrvr = $Srvr} if ('' -eq $NameDB){ $NameDB = $Ref} if ($null -eq $DataBaseManagmentSystem){ $DataBaseManagmentSystem = [TypeDBMS]::MSSQLServer } $DBMS = "DBMS=$DataBaseManagmentSystem;DBSrvr=$NameDBSrvr;DB=$NameDB;DBUID=$UserDBSrvr;" if ('' -ne $PwdUserDBSrvr){ $DBMS += "DBPwd=$PwdUserDBSrvr;" } $AddSettings = "SQLYOffs=2000;" if ('' -ne $CreateDBifNull){ $AddSettings += "CrSQLDB=$CreateDBifNull;" } if ('' -ne $ScheduleJobOff){ $AddSettings += "SchJobDn=$ScheduleJobOff;" } if ('' -ne $AdminCluster){ $AddSettings += "SUsr=$AdminCluster;" } if ('' -ne $PwdAdminCluster){ $AddSettings += "SPwd=$PwdAdminCluster;" } # $LocaleSettings = "Locale=$Locale;" $Param = @("$Srvr1C$DBMS$AddSettings") if ('' -ne $NameToList){ $Param += "/AddList $NameToList" } $this.Run("CREATEINFOBASE", $Param) } #endregion Srvr #endregion CreateInfoBase #region Unloading_and_loading_of_information_base [void] DumpIB([string]$FileDT){ $this.Run(('/DumpIB "{0}"' -f $FileDT)) }# end DumpIB [void] RestoreIB([string]$FileDT){ $this.Run(('/RestoreIB "{0}"' -f $FileDT)) }# end RestoreIB #endregion Unloading_and_loading_of_information_base #region Configuration_and_extensions #region DumpCfg [void] DumpCfg([string]$FileCF){ $this.Run(('/DumpCfg "{0}"' -f $FileCF)) } [void] DumpCfg([string]$FileCF, [string]$NameExtension){ $this.Run(('/DumpCfg "{0}" -Extension "{1}"' -f $FileCF, $NameExtension)) } #endregion DumpCfg #region LoadCfg [void] LoadCfg([string]$FileCF){ $this.LoadCfg($FileCF, $false) } [void] LoadCfg([string]$FileCF, [bool]$UpdDBCfg){ $Param = @() if ($UpdDBCfg){ $Param += $this.GetCommandUpdateDBCfg() } $this.Run(('/LoadCfg "{0}"' -f $FileCF), $Param) } [void] LoadCfg([string]$FileCF, [string]$NameExtension){ $this.LoadCfg($FileCF, $NameExtension, $false) } [void] LoadCfg([string]$FileCF, [string]$NameExtension, [bool]$UpdDBCfg){ $Param = @() if ($UpdDBCfg){ $Param += $this.GetCommandUpdateDBCfg() } $this.Run(('/LoadCfg "{0}" -Extension "{1}"' -f $FileCF, $NameExtension), $Param) } #endregion LoadCfg #region UpdateDBCfg [void] UpdateDBCfg(){ $this.UpdateDBCfg($false) } [void] UpdateDBCfg([bool]$Dynamic){ $this.Run($this.GetCommandUpdateDBCfg($Dynamic)) }# end UpdateDBCfg hidden [string] GetCommandUpdateDBCfg(){ return $this.GetCommandUpdateDBCfg($false) } hidden [string] GetCommandUpdateDBCfg([bool]$Dynamic){ $ModeDynamic = '-Dynamic–' if ($Dynamic){ $ModeDynamic = '-Dynamic+' } return "/UpdateDBCfg $ModeDynamic" }# end GetCommandUpdateDBCfg #endregion UpdateDBCfg #region DumpConfigToFiles [void] DumpConfigToFiles([string]$UploadDirectory){ $this.DumpConfigToFiles($UploadDirectory, '') } [void] DumpConfigToFiles([string]$UploadDirectory, [string]$ListFiles){ $Param = @() if ('' -ne $ListFiles){ $Param += $this.GetListFiles($ListFiles) } $this.Run(('/DumpConfigToFiles "{0}"' -f $UploadDirectory), $Param) } #endregion DumpConfigToFiles hidden [string] GetListFiles($ListFiles){ $i = 0 $Key = '-listFiles' foreach($line in [System.IO.File]::ReadLines($ListFiles)){ if($line -match ','){ $Key = '-Files' break } if ($i -eq 3) { break } $i += 1 } return ('{0} "{1}"' -f $Key, $ListFiles) } #region LoadConfigFromFiles [void] LoadConfigFromFiles([string]$LoadDirectory){ $this.LoadConfigFromFiles($LoadDirectory, '', $false) } [void] LoadConfigFromFiles([string]$LoadDirectory, [bool]$UpdDBCfg){ $this.LoadConfigFromFiles($LoadDirectory, '', $UpdDBCfg) } [void] LoadConfigFromFiles([string]$LoadDirectory, [string]$ListFiles, [bool]$UpdDBCfg){ $Param = @() if ('' -ne $ListFiles){ $Param += $this.GetListFiles($ListFiles) } if ($UpdDBCfg){ $Param = @($this.GetCommandUpdateDBCfg()) } $this.Run(('/LoadConfigFromFiles "{0}"' -f $LoadDirectory), $Param) } #endregion LoadConfigFromFiles #endregion Configuration_and_extensions #region Configuration_storage_commands #region RepositoryBindCfg [void] RepositoryBindCfg(){ $this.RepositoryBindCfg($true, $true, '') } [void] RepositoryBindCfg([bool]$forceBindAlreadyBindedUser){ $this.RepositoryBindCfg($forceBindAlreadyBindedUser, $true, '') } [void] RepositoryBindCfg([bool]$forceBindAlreadyBindedUser, [bool]$forceReplaceCfg, [string]$Extension){ $Param = @() if ($forceBindAlreadyBindedUser){ $Param += '-forceBindAlreadyBindedUser' } if ($forceReplaceCfg){ $Param += '-forceReplaceCfg' } if ('' -ne $Extension){ $Param += ('-Extension "{0}"' -f $Extension) } $this.Run('/ConfigurationRepositoryBindCfg', $Param) } #endregion RepositoryBindCfg #region RepositoryDumpCfg [void] RepositoryDumpCfg([string]$FileCF){ $this.RepositoryDumpCfg($FileCF, '', '') } [void] RepositoryDumpCfg([string]$FileCF, [string]$Version, [string]$Extension) { $Param = @($FileCF) if ('' -ne $Version){ $Param += ('-v {0}' -f $Version) } if ('' -ne $Extension){ $Param += ('-Extension "{0}"' -f $Extension) } $this.Run('/ConfigurationRepositoryDumpCfg', $Param) } #endregion RepositoryDumpCfg #region RepositoryLock [void] RepositoryLock([string]$Objects){ $this.RepositoryLock($Objects, $true, '') } [void] RepositoryLock([string]$Objects, [bool]$Revised){ $this.RepositoryLock($Objects, $Revised, '') } [void] RepositoryLock([string]$Objects, [bool]$Revised, [string]$Extension){ $Param = @() if ('' -ne $Objects){ $Param += ('-Objects "{0}"' -f $Objects) } if ($Revised){ $Param += '-revised' } if ('' -ne $Extension){ $Param += ('-Extension "{0}"' -f $Extension) } $this.Run('/ConfigurationRepositoryLock', $Param) } #endregion RepositoryLock #region RepositoryCommit [void] RepositoryCommit([string]$Objects){ $this.RepositoryCommit($Objects, '', $false, $false, '') } [void] RepositoryCommit([string]$Objects, [string]$Comment){ $this.RepositoryCommit($Objects, $Comment, $false, $false, '') } [void] RepositoryCommit([string]$Objects, [string]$Comment, [bool]$keepLocked){ $this.RepositoryCommit($Objects, $Comment, $keepLocked, $false, '') } [void] RepositoryCommit([string]$Objects, [string]$Comment, [bool]$keepLocked, [bool]$Force){ $this.RepositoryCommit($Objects, $Comment, $keepLocked, $Force, '') } [void] RepositoryCommit([string]$Objects, [string]$Comment, [bool]$keepLocked, [bool]$Force, [string]$Extension){ $Param = @() if ('' -ne $Objects){ $Param += ('-Objects "{0}"' -f $Objects) } if ('' -ne $Comment){ $Comment -split "`n" | foreach{$Param += ('-Comment "{0}"' -f $_)} } if ($keepLocked){ $Param += '-keepLocked' } if ($Force){ $Param += '-force' } if ('' -ne $Extension){ $Param += ('-Extension "{0}"' -f $Extension) } $this.Run('/ConfigurationRepositoryCommit', $Param) } #endregion RepositoryCommit #region RepositoryUnLock [void] RepositoryUnLock([string]$Objects){ $this.RepositoryUnLock($Objects, $false, '') } [void] RepositoryUnLock([string]$Objects, [bool]$Force){ $this.RepositoryUnLock($Objects, $Force, '') } [void] RepositoryUnLock([string]$Objects, [bool]$Force, [string]$Extension){ $Param = @() if ('' -ne $Objects){ $Param += ('-Objects "{0}"' -f $Objects) } if ($Force){ $Param += '-force' } if ('' -ne $Extension){ $Param += ('-Extension "{0}"' -f $Extension) } $this.Run('/ConfigurationRepositoryUnLock', $Param) } #endregion RepositoryUnLock #region RepositoryUpdateCfg [void] RepositoryUpdateCfg([string]$Version){ $this.RepositoryUpdateCfg($Version, $false, $true, '', '') } [void] RepositoryUpdateCfg([bool]$Revised){ $this.RepositoryUpdateCfg('', $Revised, $true, '', '') } [void] RepositoryUpdateCfg([string]$Version, [bool]$Revised, [bool]$Force, [string]$Objects, [string]$Extension){ $Param = @() if ('' -ne $Version){ $Param += ('-v {0}' -f $Version) } if ($Revised){ $Param += '-revised' } if ($Force){ $Param += '-force' } if ('' -ne $Objects){ $Param += ('-Objects "{0}"' -f $Objects) } if ('' -ne $Extension){ $Param += ('-Extension "{0}"' -f $Extension) } $this.Run('/ConfigurationRepositoryUpdateCfg', $Param) } #endregion RepositoryUpdateCfg #endregion Configuration_storage_commands #region The command to create a file delivery and update #region CreateDistributionFiles [void] CreateDistributionFiles([string]$cffile){ $this.CreateDistributionFiles($cffile, '', '', '', $false) } [void] CreateDistributionFiles([string]$cfufile, [string]$NameCF_VersionCF){ $this.CreateDistributionFiles('', $cfufile, $NameCF_VersionCF, $false) } [void] CreateDistributionFiles([string]$cffile, [string]$cfufile, [string]$NameCF_VersionCF,` [string]$digisign, [bool]$WarningAsError){ $Param = @() if ('' -ne $cfufile){ $Param += ('-cfufile "{0}"' -f $cfufile) } if ('' -ne $NameCF_VersionCF){ $template = '-v "{0}"' if (Test-Path $NameCF_VersionCF) { $template = '-f "{0}"' } $Param += ($template -f $NameCF_VersionCF) } if ('' -ne $digisign){ $Param += ('-digisign "{0}"' -f $digisign) } if ($WarningAsError){ $Param += '-WarningAsError' } $this.Run(('/CreateDistributionFiles -cffile "{0}"' -f $cffile), $Param) } #endregion CreateDistributionFiles #endregion The command to create a file delivery and update }# end class Designer1C #Export-ModuleMember -Function New-Designer1C
Uninstall-1C.ps1
1C.Utils-0.4.0
#09.2017©willynilly . $PSScriptRoot\CommonUtils\CommonUtils.ps1 #---------------------------------------------------------------------------------------- # Запускает деинсталяцию установленных экземпляров 1С function Uninstall-1C { <# .SYNOPSIS Деинсталирует не используемые версии платформы 1С. .DESCRIPTION Деинсталирует все установленые стандартным установщиком версии платформы 1С кроме: - заданных по умолчанию в файле iBases.v8i из профиля текущего пользователя - запущенных на момент выполнения скрипта После запуска команды выводится список всех установленных платформ для удаления (список исключений выделен цветом) и ожидается подтверждение пользователя на удаление. .PARAMETER Force Выполнить деинсталяцию без вопросов пользователю. .PARAMETER Wait Для завершения работы ждать подтверждения от пользователя. #> [CmdletBinding()] param( [switch]$Wait, # Ожидать нажатия любой клавиши (параметр переключатель) [switch]$Force # молча выполнить без вопросов пользователю (параметр переключатель) ) $DickUsedBefore = (Get-PSDrive -Name C).Used # занято на диске до начала деинсталяции $TotalWatch = [System.Diagnostics.Stopwatch]::StartNew() # глобальный секундомер $Watch = [System.Diagnostics.Stopwatch]::StartNew() # секундомер для операции $TotalWatch.Start() #Запуск глобального секундомера # получим список ислючений из удаления $Watch.Reset() $Watch.Start() $ExceptPlatform = Get-ExceptPlatform $Watch.Stop() $TimeGetExcept = $Watch.Elapsed # Получим все приложения вендора $Watch.Reset() $Watch.Start() $InstalledPlatform = Get-InstalledPlatform $Watch.Stop() $TimeGetting = $Watch.Elapsed # Покажем что получили $HasRemove = Show-ListToUninstall $InstalledPlatform $ExceptPlatform # Запрос на продолжение if (-not($Force)) { $TotalWatch.Stop() #Тормознем глобальный секундомер (пропустим раздумья пользователя) $CanContinue = Get-Permission $TotalWatch.Start() } #Запустить деинсталяцию $DickFree = 0 $Watch.Reset() if ($HasRemove -and $CanContinue) { $Watch.Start() Run-Uninstall $InstalledPlatform $ExceptPlatform $Watch.Stop() $DickFree = $DickUsedBefore - (Get-PSDrive -Name C).Used # высвобождено после деинсталяции } $TimeUninstall = $Watch.Elapsed #Подведем итоги работы '' $TotalWatch.Stop() #Остановка глобального секундомера $MaxRight = 50 $MaxLeft = 12 $Sym = '.' $TimeFormat = '{0:hh}:{0:mm}:{0:ss}.{0:fff}' ("Затрачено на получение списка установленных").PadRight($MaxRight,$Sym) + $TimeFormat -f $TimeGetting ("Затрачено на получение списка исключений").PadRight($MaxRight,$Sym) + $TimeFormat -f $TimeGetExcept ("Количество установленных экземпляров").PadRight($MaxRight,$Sym) + ('{0}' -f $InstalledPlatform.Count).PadLeft($MaxLeft, $Sym) ("Количество исключений").PadRight($MaxRight,$Sym) + ('{0}' -f $ExceptPlatform.Count).PadLeft($MaxLeft, $Sym) ("Затрачено на деинсталяцию").PadRight($MaxRight,$Sym) + $TimeFormat -f $TimeUninstall ("Всего высвобождено на диске").PadRight($MaxRight,$Sym) + ('{0:n3} Gb' -f ($DickFree/1Gb)).PadLeft($MaxLeft, $Sym) ("Всего затрачено:").PadRight($MaxRight,$Sym) + $TimeFormat -f $TotalWatch.Elapsed if ($Wait) { Wait-PressAnyKey } }# end Uninstall-1C #---------------------------------------------------------------------------------------- # Удаляет платформы из переданного списка установленных кроме списка исключений если задан function Run-Uninstall($InstalledPlatform, $ExceptPlatform = $null) { Write-Host "`nУдаленные:" foreach($Platform in $InstalledPlatform) { if (Can-UninstallVersion $Platform.Version $ExceptPlatform) { Write-Host (" {0} {1}" -f $Platform.Name, $Platform.IdentifyingNumber) -ForegroundColor Green Start-Process -FilePath 'MsiExec.exe' -ArgumentList ("/x{0} /qn" -f $Platform.IdentifyingNumber) -Wait -PassThru | Out-Null } } }# end Run-Uninstall #---------------------------------------------------------------------------------------- # Показывает список к удалению но не удаляет function Show-ListToUninstall($InstalledPlatform, $ExceptPlatform = $null) { Write-Host "`nСписок к удалению:" $HasRemove = $false foreach($Platform in $InstalledPlatform) { if (Can-UninstallVersion $Platform.Version $ExceptPlatform) { Write-Host (" {0}" -f $Platform.Name) -ForegroundColor Green $HasRemove = $true } else {Write-Host (" {0}" -f $Platform.Name) -ForegroundColor Yellow} } return $HasRemove }# end Show-ListToUninstall #---------------------------------------------------------------------------------------- # Проверяет возможность удаления function Can-UninstallVersion($Version, $ExceptPlatform = $null) { $Results = $True if ($ExceptPlatform) { $Results = -not($ExceptPlatform.ContainsKey($Version)) } return $Results }# end Can-UninstallVersion #---------------------------------------------------------------------------------------- # получает версии установленных платформ function Get-InstalledPlatform { $test = Test-WSMan -ErrorAction SilentlyContinue $StopWinRM = $false if (-not $test) { # Write-Warning 'Запуск "Служба удаленного управления Windows (WS-Management)"' Start-Service -Name 'WinRM' $StopWinRM = $true } $VendorEN = "1C" $VendorRU = "1С" $FilterVendor = "(Vendor like '{0}%' or Vendor like '{1}%')" -f $VendorEN, $VendorRU $FilterName = "(Name like '{0}%' or Name like '{1}%')" -f ($VendorEN + ":Предприятие"), ($VendorRU + ":Предприятие") $Filter = "{0} and {1}" -f $FilterVendor, $FilterName $InstalledPlatform = Get-CimInstance -ClassName Win32_Product -Filter $Filter -ComputerName "." | Sort-Object Version, Name if ($StopWinRM) { # Write-Warning 'Остановка "Служба удаленного управления Windows (WS-Management)"' Stop-Service -Name 'WinRM' } return $InstalledPlatform }# end Get-InstalledPlatform #---------------------------------------------------------------------------------------- # получает версии платформ запрещенных для удаления function Get-ExceptPlatform { # соберем все что удалять не надо Write-Host "`nСписок исключений для удаления получен:" $ExceptPlatform = @{} Add-1CEStart_cfg $ExceptPlatform Add-StartedProcess1C $ExceptPlatform Write-Host '' $ExceptPlatform.Keys | sort | foreach{Write-Host(' {0}' -f $_) -ForegroundColor Yellow} return $ExceptPlatform }# end Get-ExceptPlatform #---------------------------------------------------------------------------------------- # добавляет версии платформ перечисленные в файле 1CEStart.cfg из профиля пользователя function Add-1CEStart_cfg($ExceptPlatform) { $Ok = $false $fpathEStartCfg = $env:appdata + "\1C\1CEStart\1CEStart.cfg" if(Test-Path $fpathEStartCfg) { Get-Content $fpathEStartCfg | where {$_ -match 'DefaultVersion'} | foreach { $Platform = ($_ -split '-')[1] $Platform = ($Platform -split ';')[0] $ExceptPlatform[$Platform]=""; $Ok = $true } if ($Ok){Write-Host (" - из файла {0}" -f $fpathEStartCfg)} } }# end Add-1CEStart_cfg #---------------------------------------------------------------------------------------- # добавляет версии платформ всех запущенных в текущий момент процессов function Add-StartedProcess1C($ExceptPlatform) { $Ok = $false Get-Process "1cv8*" -FileVersionInfo | foreach{$ExceptPlatform[$_.FileVersion]=""; $Ok = $true} Get-Process "ragent*" -FileVersionInfo | foreach{$ExceptPlatform[$_.FileVersion]=""; $Ok = $true} if ($Ok){Write-Host " - из списка запущеных процессов"} }# end Add-StartedProcess1C
classLog.ps1
1C.Utils-0.4.0
function New-Log { <# .SYNOPSIS Возвращает экземпляр класса Log. .DESCRIPTION Создает объект класса Log позволяющий вести журнал действий. .PARAMETER FullName Полное имя файла журнала. .PARAMETER Append Если указан, то существующий файл журнала не будет очищаться. .EXAMPLE #Создать объект для ведения файла журнала $Log = New-Log 'c:\.log' #> [CmdletBinding()] param( [Alias("f")][string]$FullName='', [Alias("a")][switch]$Append ) New-Object Log($FullName, $Append) }# end New-Log class Log { #region Properties hidden [String]$FullName='' [bool]$Silent=$false [string]$TemplateMessage='%Time% %Message%' [string]$Symbol='.' [int16]$AmountSymbol=45 #endregion Properties #region Constructor Log() { $this.SetFullName() } Log([String]$FullName, [bool]$Append) { $this.SetFullName($FullName, $Append) } #endregion Constructor #region Methods [string] GetFullName(){ return $this.FullName } [string] GetPossibleSubstitutions(){ return @( '%Time%', '%Data%', '%Message%', '%TypeMessage%' ) } [void] SetFullName() { $this.SetFullName('', $false) } [void] SetFullName([string]$FullName, [bool]$Append) { $this.FullName = $FullName if ('' -ne $this.FullName -and (!$Append -or !(Test-Path $this.FullName))){ New-Item $this.FullName -ItemType file -Force | Out-Null # создадим лог-файл } } [void] Write() { $this.WriteLog('', '', $false) } [void] Write([string]$Message) { $this.WriteLog($Message, '', $false) } [void] Write([string]$Message, [bool]$Silent) { $this.WriteLog($Message, '', $Silent) } [void] WriteColor([string]$Message, [string]$Color) { $this.WriteLog($Message, $Color, $false) } [void] WriteError([string]$Message) { $this.WriteLog($Message, 'Red', $false) } [void] WriteError([string]$Message, [bool]$Silent) { $this.WriteLog($Message, 'Red', $Silent) } [void] WriteWarning([string]$Message) { $this.WriteLog($Message, 'Yellow', $false) } [void] WriteWarning([string]$Message, [bool]$Silent) { $this.WriteLog($Message, 'Yellow', $Silent) } hidden [void]WriteLog([string]$Message, [string]$Color, [bool]$Silent){ $TypeMessage = 'inf' switch ($Color) { 'Red' { $TypeMessage = 'err' } 'Yellow' { $TypeMessage = 'wrn' } } $msg = "{0}" -f $Message if ('' -ne $Message){ $msg = $this.TemplateMessage $msg = $msg.Replace('%Time%', (Get-Date -Format "HH:mm:ss")) $msg = $msg.Replace('%Data%', (Get-Date -Format "dd.MM.yyyy")) $msg = $msg.Replace('%TypeMessage%', $TypeMessage) $msg = $msg.Replace('%Message%', $Message) } if(-not ($Silent -or $this.Silent)){ if('' -eq $Color){ Write-Host $msg } else { Write-Host $msg -ForegroundColor $Color } } if ('' -ne $this.FullName){ $msg | Out-File $this.FullName -append -encoding unicode } }#end WriteLog [void] OutValue([string]$Name, $Value) { $msg = $Name.PadRight($this.AmountSymbol, $this.Symbol) + $Value Write-Host $msg if ('' -ne $this.FullName){ $msg | Out-File $this.FullName -append -encoding unicode } } #endregion Methods }#end class Log #Export-ModuleMember -Function New-Log
1C.Utils.psd1
1C.Utils-0.4.0
# # Module manifest for module '1C.Utils' # # Generated by: agur # # Generated on: 31.10.2017 # @{ # Script module or binary module file associated with this manifest. RootModule = '1C.Utils.psm1' # Version number of this module. ModuleVersion = '0.4.0' # Supported PSEditions # CompatiblePSEditions = @() # ID used to uniquely identify this module GUID = 'ff36bb51-e8f7-4ed8-8b63-57a4109c68a2' # Author of this module Author = 'willynilly' # Company or vendor of this module CompanyName = 'willynilly' # Copyright statement for this module Copyright = '(c) 2017-2024 willynilly. All rights reserved.' # Description of the functionality provided by this module Description = 'A set of utilities and tools to work in Powershell 1C.' # Minimum version of the Windows PowerShell engine required by this module # PowerShellVersion = '' # Name of the Windows PowerShell host required by this module # PowerShellHostName = '' # Minimum version of the Windows PowerShell host required by this module # PowerShellHostVersion = '' # Minimum version of Microsoft .NET Framework required by this module. This prerequisite is valid for the PowerShell Desktop edition only. # DotNetFrameworkVersion = '' # Minimum version of the common language runtime (CLR) required by this module. This prerequisite is valid for the PowerShell Desktop edition only. # CLRVersion = '' # Processor architecture (None, X86, Amd64) required by this module # ProcessorArchitecture = '' # Modules that must be imported into the global environment prior to importing this module RequiredModules = @( @{ModuleName = 'powershell-yaml'; ModuleVersion = '0.3.1'} ) # Assemblies that must be loaded prior to importing this module # RequiredAssemblies = @() # Script files (.ps1) that are run in the caller's environment prior to importing this module. # ScriptsToProcess = @() # Type files (.ps1xml) to be loaded when importing this module # TypesToProcess = @() # Format files (.ps1xml) to be loaded when importing this module # FormatsToProcess = @() # Modules to import as nested modules of the module specified in RootModule/ModuleToProcess # NestedModules = @() # Functions to export from this module, for best performance, do not use wildcards and do not delete the entry, use an empty array if there are no functions to export. FunctionsToExport = @( 'Clear-Cache1C', 'Get-DirectoryCache1C', 'Get-Exe1C', 'Get-iBasesFullName', 'Get-InstalledLocation1C', 'Get-ObjectsXML', 'Get-RolesXML', 'Load-ToBase1C', 'New-Designer1C', 'Read-iBases', 'Set-DebugServer1C', 'Start-1C', 'Stop-1C', 'Uninstall-1C') # Cmdlets to export from this module, for best performance, do not use wildcards and do not delete the entry, use an empty array if there are no cmdlets to export. CmdletsToExport = '*' # Variables to export from this module VariablesToExport = '*' # Aliases to export from this module, for best performance, do not use wildcards and do not delete the entry, use an empty array if there are no aliases to export. AliasesToExport = @('Dbg-Srv1C', 'Kill-1C', 'RUN-1C') # DSC resources to export from this module # DscResourcesToExport = @() # List of all modules packaged with this module # ModuleList = @() # List of all files packaged with this module # FileList = @() # Private data to pass to the module specified in RootModule/ModuleToProcess. This may also contain a PSData hashtable with additional module metadata used by PowerShell. PrivateData = @{ PSData = @{ # Tags applied to this module. These help with module discovery in online galleries. # Tags = @() # A URL to the license for this module. # LicenseUri = '' # A URL to the main website for this project. ProjectUri = 'https://bitbucket.org/willynilly74/1c.utils/wiki/Home' # A URL to an icon representing this module. # IconUri = '' # ReleaseNotes of this module ReleaseNotes = ' add new cmdlet: Load-ToBase1C refactoring: Stop-1C - The call to the winRM service has been replaced with the standard Get-Process cmdlet. ' } # End of PSData hashtable } # End of PrivateData hashtable # HelpInfo URI of this module HelpInfoURI = 'https://bitbucket.org/willynilly74/1c.utils/wiki/Home' # Default prefix for commands exported from this module. Override the default prefix using Import-Module -Prefix. # DefaultCommandPrefix = '' }
Clear-Cache1C.ps1
1C.Utils-0.4.0
. $PSScriptRoot\CommonUtils\CommonUtils.ps1 . $PSScriptRoot\Read-iBases.ps1 $global:MaxSizeCache = 1MB*100 # выделять цветом папки с кэшом превышающий MaxSizeCache $global:MaxLengthName = 45 $global:MaxLengthSize = 13 $global:TotalCacheSize = 0 #---------------------------------------------------------------------------------------- # Очищает кэш 1С function Clear-Cache1C { <# .SYNOPSIS Очищает кэш платформы 1С. .DESCRIPTION Выводит пронумерованный список баз с размером кэша для каждой базы и дожидается выбора баз для очистки кэша. По умолчанию очищается только каталог кэша метаданных. Для ОС Windows C:\Users\NameUser\AppData\Local\1C\1Cv8. Параметр UserSettings позволяет очистить каталог кэша настроек пользователя. Для ОС Windows C:\Users\NameUser\AppData\Roaming\1C\1Cv8. .PARAMETER UserSettings Очистить кэш настроек пользователя. Псевдоним: us .PARAMETER Force Очистить кэш у всех баз не спрашивая. .PARAMETER Wait После выполнения дождаться нажатия любой клавиши. #> [CmdletBinding()] param( [Alias("us")][switch]$UserSettings, # работать с каталогом пользовательских настроек [switch]$Force, # True = очистить кэш метаданных у всех баз не спрашивая [switch]$Wait ) $DirCache1C = Get-DirectoryCache1C -UserSettings:$UserSettings $iBases = Get-ListBase $DirCache1C -UserSettings:$UserSettings -Force:$Force if ($Force){ # удалить кэш баз Remove-Cache1C $DirCache1C $UserSettings $iBases } else { # показать меню и дождаться выбора пользователя $Menu = "`n[1,2,3] - для очистки кэша укажите номера баз (Пустая строка = Все номера) `n"+ "[любой символ не цифра] - завершить работу`n"+ "Ваш выбор" [System.String]$InputUser = Read-Host $Menu if ($InputUser -eq '') { Remove-Cache1C $DirCache1C $UserSettings $iBases } elseif($InputUser -match '\d+') { $Indexes = Get-Indexes $InputUser if ($Indexes.Length -gt 0) { Remove-Cache1C $DirCache1C $UserSettings $iBases $Indexes } } }# if ($Force) if ($Wait) { Wait-PressAnyKey } }# end of Clear-Cache1C #---------------------------------------------------------------------------------------- # Функция каталог кэша 1С function Get-DirectoryCache1C { <# .SYNOPSIS Возвращает каталог хранения кэша платформы 1С. .DESCRIPTION По умолчанию возвращает каталог хранения кэша метаданных. Если задан параметр UserSettings, то возвращает каталог хранения кэша настроек пользователя. Если в каталоге кэша обнаружен файл location.cfg, то каталог хранения будет прочитан из файла (параметр location). По умолчанию для ОС Windows платформы 1С версии 8.3 кэш хранится в каталогах: - кэш метаданных в C:\Users\NameUser\AppData\Local\1C\1Cv8 - кэш настроек пользователя в C:\Users\NameUser\AppData\Roaming\1C\1Cv8 .PARAMETER UserSettings Вернуть каталог кэша настроек пользователя. Псевдоним: us #> [CmdletBinding()] param( [Alias("us")][switch]$UserSettings # работать с каталогом пользовательских настроек ) $ChacheDir = $env:LOCALAPPDATA + '\1C\1cv8' if ($UserSettings){$ChacheDir = $env:APPDATA + '\1C\1cv8'} if (Test-Path "$ChacheDir\location.cfg"){ switch -Regex -File "$ChacheDir\location.cfg" { "^location=(.*)$" { Write-Verbose ("location = '{0}'" -f $matches[1]) $ChacheDir = $matches[1] } } } $ChacheDir }# end Get-DirectoryCache1C #---------------------------------------------------------------------------------------- # Функция получает и выводит список баз и размер кэша каждой базы function Get-ListBase { [CmdletBinding()] param( [string]$DirCache1C, # каталог хранения кэша [Alias("us")][switch]$UserSettings, # работать с каталогом пользовательских настроек [switch]$Force # True = очистить кэш метаданных у всех баз не спрашивая ) $NameDirCache1C = "`nОчистка кэша метаданных: $DirCache1C`n" $NameTotalSize = "Суммарный размер кэша метаданных" if ($UserSettings){ $NameDirCache1C = "`nОчистка кэша настроек пользователя: $DirCache1C`n" $NameTotalSize = "Суммарный размер кэша настроек пользователя" } Write-Host $NameDirCache1C $global:TotalCacheSize = 0 $iBases = @() $i = 0 Read-iBases | foreach{ $DirCacheBase = "{0}\{1}" -f $DirCache1C, $_.ID $CacheSize = 0 if(Test-Path -path $DirCacheBase) { $CacheSize = (dir $DirCacheBase -recurse -Force | measure -Property Length -Sum).Sum } if ([Math]::Floor($CacheSize/1mb) -gt 0){ $global:TotalCacheSize +=$CacheSize $_['Cache'] = $DirCacheBase $_['CacheSize'] = $CacheSize $iBases += $_ if (!$Force){ $msg = Get-Message $_['Name'] $CacheSize ($i+=1) if($CacheSize -ge $global:MaxSizeCache){ Write-Host $msg -ForegroundColor Yellow # покрасить строку базы } else { Write-Host $msg # вывести без окраски } }# end if (!$Force) }# if ($CacheSize -gt 0) } if (!$Force){ Write-Host (Get-Message $NameTotalSize $global:TotalCacheSize " ") -ForegroundColor White } $iBases }# end Get-ListBase #---------------------------------------------------------------------------------------- # Получает массив индексов из строки заданной пользователем function Get-Indexes($TextNumbers) { $Indexes = @() $Numbers = $TextNumbers -Replace "[\D]","," -split "," foreach($Number in $Numbers) { if ($Number.Trim() -ne '') { $Indexes += [Convert]::ToInt32($Number.Trim())-1 } } $Indexes }# end Get-Indexes #---------------------------------------------------------------------------------------- # Удаляет каталоги кэша баз данных function Remove-Cache1C($DirCache1C, $UserSettings, $Bases, $Indexes = $null) { Write-Verbose "DebugPreference = $DebugPreference" $msg = "`nОчистка кэша метаданных: $DirCache1C" if ($UserSettings){$msg = "`nОчистка кэша настроек пользователя: $DirCache1C"} Write-Host $msg -ForegroundColor White $TotalDelete = 0 if ($Indexes -eq $null){ foreach($Base in $Bases){ $TotalDelete = $TotalDelete + (Remove-CacheBase $Base) } } else { foreach($Index in $Indexes){ if ($Index -lt $Bases.Length){ $TotalDelete = $TotalDelete + (Remove-CacheBase $Bases[$Index]) } } } Write-Host (Get-Message "Всего удалено:" $TotalDelete) -ForegroundColor White if ($Indexes -ne $null){ Write-Host (Get-Message "Осталось:" ($global:TotalCacheSize - $TotalDelete)) -ForegroundColor White } }# end Remove-Cache1C #---------------------------------------------------------------------------------------- # Удаляет каталоги кэша переданной базы данных function Remove-CacheBase($iBase) { $CachseSize = 0 try{ If ($DebugPreference -eq 'SilentlyContinue') { Remove-Item $iBase['Cache'] -Recurse $CachseSize = $iBase['CacheSize'] } Write-Host (Get-Message $iBase['Name'] $CachseSize) -ForegroundColor Yellow } catch [System.Exception] { # НЕ РАБОТАЕТ если файл заблокирован другим процессом!!! Write-Warning 'При удалении возникла ошибка. Возможно кэш заблокирован другим процессом или не существует.' } $CachseSize # вернем размер удаленного }# end Remove-CacheBase #---------------------------------------------------------------------------------------- # Получает строку сообщения с заданными параметрами function Get-Message($Name, $Size, $Number = $null) { if ($Number -eq $null) { $msg = "{0}.{1} MB" -f $Name.PadRight($global:MaxLengthName + 1,'.'), ("{0:n0}" -f ($Size/1mb)).PadLeft($global:MaxLengthSize,'.') } else { $msg = "{0} {1}.{2} MB" -f $Number.ToString().PadRight(2,' '), $Name.PadRight($global:MaxLengthName + 1,'.'), ("{0:n0}" -f ($Size/1mb)).PadLeft($global:MaxLengthSize,'.') } $msg }# end Get-Message
Start-1C.ps1
1C.Utils-0.4.0
. $PSScriptRoot\CommonUtils\CommonUtils.ps1 . $PSScriptRoot\Common1C.ps1 New-Alias -Name 'RUN-1C' -Value 'Start-1C' #region Start-1C #---------------------------------------------------------------------------------------- # запускает платформу 1С с переданными ключами командной строки function Start-1C { <# .SYNOPSIS Запускает платформу 1С в пакетном режиме. .DESCRIPTION Выполняет в пакетном режиме переданные в файле настроек командные ключи платформы 1С для заданного набора баз. Позволяет для разных баз выполнить один набор команд. При этом общий набор команд для каждой базы можно переопределить индивидуальным набором команд. Файл настроек задается в формате YAML или JSON. Для получения пустого шаблона файла настроек небходимо запустить командлет с ключами: -CFG C:\ПолныйПутьКФайлу\ВКоторыйБудетЗаписан\ШаблонНастроек.YAML -TemplateCFG -CFG C:\ПолныйПутьКФайлу\ВКоторыйБудетЗаписан\ШаблонНастроек.JSON -TemplateCFG -JSON В сформированном шаблоне настроек представлена инструкция по его наполнению. Псевдоним: RUN-1C .PARAMETER CFG Полный путь к файлу настроек. Если указан параметр TemlateCFG, то в указанный файл будет записан пустой шаблон настроек. Вместо файла настроек может быть передана хэш-таблица сформированная по заданному в файле настроек формату. .PARAMETER TemplateCFG Записать в файл CFG шаблон настроек в формате YAML. Псевдонимы: t, templ .PARAMETER JSON Формировать шаблон настроек в формате JSON (без указания TemplateCFG игнорирутеся). Псевдонимы: j, js .PARAMETER OpenLog По окончании работы открыть лог файл. Лог файл формируется в каталоге размещения файла настроек с именем сформированным по шаблону <ИмяФайлаНастроек>.log. .PARAMETER Wait Для завершения работы ждать подтверждения от пользователя. #> [CmdletBinding(SupportsShouldProcess = $true)] param( [Parameter(Mandatory=$True,HelpMessage="Укажите настройки (путь к файлу или HashTable с настройками)")]$CFG, # файл настроек или HasTable настроек [Alias("t", "templ")][switch]$TemplateCFG, # Записать в файл cfg шаблон настроек в формате YAML [Alias("j", "js")][switch]$JSON, # Записать в файл cfg шаблон настроек в формате JSON [switch]$OpenLog, # После выполнения открыть лог файл [switch]$Wait ) if ($null -eq $CFG -or $CFG -eq ""` -or ($CFG -is "System.String" -and -not(Test-Path $CFG)` -and -not($TemplateCFG))) { Return } Write-Verbose "PSScriptRoot = $PSScriptRoot" Write-Verbose "CFG = $CFG" Write-Verbose "TemplateCFG = $TemplateCFG" Write-Verbose "JSON = $JSON" if ($TemplateCFG) { if ($JSON) { Get-TextJSON | Out-File $CFG } else { Get-TextYAML | Out-File $CFG } Return } $TotalWatch = [System.Diagnostics.Stopwatch]::StartNew() # глобальный секундомер $Files = @{} if (Test-Path $CFG) { $Config = Read-Config $CFG $FileCfg = Get-Item $CFG $Files["log"] = "{0}\{1}.log" -f $FileCfg.Directory, $FileCfg.BaseName New-Item $Files.log -ItemType file -Force | Out-Null # создадим лог-файл } if ($cfg -is "System.Collections.Hashtable") { $Config = $CFG $Files["log"] = $Config["log"] if ($null -eq $Files["log"]){ $Files["log"] = New-TemporaryFile $Config["log"] = $Files.log } else { New-Item $Files.log -ItemType file -Force | Out-Null # создадим лог-файл } } $Debug = $PSBoundParameters.Debug -eq $true $WhatIf = $PSBoundParameters.WhatIf -eq $true if ($null -ne $Config) { $Files["exe"] = "{0}{1}/bin/1cv8.exe" -f $Config.Dir1C, $Config.Platform1C if ($null -eq $Config.Dir1C -or $null -eq $Config.Platform1C) { $Files["exe"] = (Get-InstalledLocation1C) + 'common\1cestart.exe' } if ($null -ne $Config.exe1cv8) { $Files["exe"] = $Config.exe1cv8 } Write-Verbose ("Dir1C = {0}" -f $Config.Dir1C) Write-Verbose ("Platform1C = {0}" -f $Config.Platform1C) Write-Log ("`nCFG = {0}" -f $CFG) $Files.log -Color Green -NoTime:$Debug Write-Log ("LOG = {0}" -f $Files.log) $Files.log -NoTime Write-Log ("1cv8.exe = {0}" -f $Files.exe) $Files.log -NoTime $Modes = @('COMMANDS', 'DESIGNER', 'ENTERPRISE') $WatchBase = [System.Diagnostics.Stopwatch]::StartNew() # секундомер базы foreach($Base in $Config.Bases1C) { #Hачало обработки базы $NameBase = Get-ValueByKey $Base "NameBase" Write-Log ("`nОбрабатывается база: {0}" -f $NameBase) $Files.Log -Color Green -NoTime:$Debug #Старт секундомер базы $WatchBase.Reset() $WatchBase.Start() #Переопределить платформу для базы $Dir1C = Get-ValueByKey $Base "Dir1C" $Config.Dir1C $Platform1C = Get-ValueByKey $Base "Platform1C" $Config.Platform1C $Files["exe"] = "{0}{1}/bin/1cv8.exe" -f $Dir1C, $Platform1C if ($null -ne $Base.exe1cv8) { $Files["exe"] = Get-ValueByKey $Base "exe1cv8" } if ($Dir1C -ne $Config.Dir1C` -or $Platform1C -ne $Config.Platform1C` -or $null -ne $Base.exe1cv8) { Write-Log ("1cv8.exe = {0}" -f $Files.exe) $Files.log -NoTime } #Выполним заданные команды над базой foreach($Mode in $Modes) { $COMMANDS = Get-ValueByKey $Config $Mode @() # список команд для всех баз $COMMANDS = Get-Commands $Base $Mode $COMMANDS # список команд для текущей базы Run-CommandLines $Base $Mode $COMMANDS $Files -Debug:$Debug -WhatIf:$WhatIf } #Запись в лог замера времени для базы $WatchBase.Stop() Write-Log ("Затрачено на обработку базы {0}: {1:hh}:{1:mm}:{1:ss}" -f $NameBase, $WatchBase.Elapsed) $Files.Log -NoTime } } $TotalWatch.Stop() #Остановка глобального секундомера Write-Log ("`nВсего затрачено на обработку: {0:hh}:{0:mm}:{0:ss} " -f $TotalWatch.Elapsed) $Files.Log -Color Green -NoTime:$Debug if ($Wait) { Wait-PressAnyKey } if($OpenLog) {& $Files.Log} }# end of Start-1C #---------------------------------------------------------------------------------------- # Формирует командную строку и запускает на выполнение для каждого ключа командной строки # из переданного массива ключей $CommandKeys function Run-CommandLines #($Base, $NameMode, $CommandKeys, $Files) { [CmdletBinding(SupportsShouldProcess = $true)] param( $Base, $NameMode, $CommandKeys, $Files ) if ($null -eq $CommandKeys){Return} $LoginBase = $Base.Connection | foreach{$_.Trim()} $LineCommandKeys = $CommandKeys | foreach{$_.Trim()} Write-Verbose "Connection = $Connection" Write-Verbose "RUN -> $NameMode = $LineCommandKeys" $exe1cv8 = $Files.exe $exe1cestart = (Get-InstalledLocation1C) + 'common\1cestart.exe' if ("$LoginBase".Contains("IBName") -or "$CommandKeys".Contains("/IBName")){ $exe1cv8 = $exe1cestart } $WatchKey = [System.Diagnostics.Stopwatch]::StartNew() # секундомер ключа foreach($CommandKey in $CommandKeys) { #Старт секундомер ключа $WatchKey.Reset() $WatchKey.Start() # заменим тэги автозамены $CommandKey = $CommandKey.Replace("<Date>", (Get-Date -Format yyyyMMdd)) $CommandKey = $CommandKey.Replace("<Time>", (Get-Date -Format hhmm)) foreach($KeyBase in $Base.Keys) { $CommandKey = $CommandKey.Replace("<$KeyBase>", $Base[$KeyBase]) if ($KeyBase -eq 'IBName'){ $exe1cv8 = $exe1cestart } } #Начало выполнения ключа Write-Log ("`nВыполняется: {0}" -f $CommandKey) $Files.Log -NoTime # определимся с режимом запуска $Mode = $NameMode # проверить наличие режима в команде if($CommandKey.Contains("DESIGNER")) { $Mode = "DESIGNER" $CommandKey = $CommandKey.Replace("DESIGNER", "").Trim() } if($CommandKey.Contains("ENTERPRISE")) { $Mode = "ENTERPRISE" $CommandKey = $CommandKey.Replace("ENTERPRISE", "").Trim() } $LoginBase = $Base.Connection | foreach{$_.Trim()} if ($Mode -eq "ENTERPRISE"){ $LoginBase = $LoginBase | where { !$_.Contains("ConfigurationRepository") } } # определимся с режимом ожидания $Wait = ($Mode -eq "DESIGNER" -and $CommandKey -ne "") # ждем только конфигуратор с не пустыми ключами if($CommandKey.Contains("/Wait")){$Wait = $true} # прямое указание ждать if($CommandKey.Contains("/NoWait")){$Wait = $false} # прямое указание НЕ ждать $CommandKey = $CommandKey.Replace("/Wait", "") $CommandKey = $CommandKey.Replace("/NoWait", "") # Запуск команды на выполнение #$PSCmdlet.ShouldProcess("Запуск команды", $NameMode) $CanRun = -not($DebugPreference -eq 'Inquire' -or $WhatIfPreference) if ($Wait) { $Arguments = "$Mode $LoginBase $CommandKey /Out {0} -NoTruncate" -f $Files.log Write-Verbose ("CommandKeys = $Arguments") #Запишем в лог исполняемую командную строку Write-Log ("Команда: {0} {1}" -f $exe1cv8, $Arguments) $Files.Log -NoTime -Silent if($CanRun) { $process = Start-Process -FilePath $exe1cv8 -ArgumentList $Arguments -Wait -PassThru } #Запись в лог замера времени для ключа $WatchKey.Stop() Write-Log ("Затрачено: {0:hh}:{0:mm}:{0:ss} " -f $WatchKey.Elapsed) $Files.Log -NoTime:$Debug } else { $Arguments = "$Mode $LoginBase $CommandKey" Write-Verbose ("CommandKeys = $Arguments") #Запишем в лог исполняемую командную строку Write-Log ("Команда: {0} {1}" -f $exe1cv8, $Arguments) $Files.Log -NoTime -Silent #if($DebugPreference -eq 'SilentlyContinue') { if($CanRun) { $process = Start-Process -FilePath $exe1cv8 -ArgumentList $Arguments -PassThru } }# end of if($Wait) }# end of foreach($CommandKey in $CommandKeys) }# end of Run-CommandLines #---------------------------------------------------------------------------------------- # читает настройки из файла в переменную function Read-Config($FileConfig) { #region КОСТЫЛЬ #Изредка (эпизодически) по не выясненным причинам при импорте powershell-yaml не подгружаются его билиотеки Try { "---" | ConvertFrom-Yaml | Out-Null } Catch [System.Management.Automation.PSArgumentException] { &(Get-Module powershell-yaml).Scripts[0] } #endregion КОСТЫЛЬ $string_cfg = Get-Content $FileConfig -Raw $FormatConfig = "YAML" if ($string_cfg.Trim()[0] -eq "{") {$FormatConfig = "JSON"} if($FormatConfig -eq "YAML") { $Config = ConvertFrom-Yaml $string_cfg } elseif($FormatConfig -eq "JSON") { $Config = ConvertFrom-Json $string_cfg | Convert-PSObjectToHashtable } else { Return } if ($DebugPreference -eq 'Inquire'){$DebugPreference = 'Continue'} Write-Debug ("`nФайл настроек: {0}`nФормат настроек: {1}`n`nСтрока настроек: {2}`n`nНастройки: {3}`n" ` -f $FileConfig, $FormatConfig, $string_cfg, $Config) $Config }# end of Read-Config #---------------------------------------------------------------------------------------- # Получить команды для выполнения над базой function Get-Commands($Base, $KeyCommand, $COMMANDS) { if($null -ne $Base[$KeyCommand]) { $COMMANDS = Get-ValueByKey $Base $KeyCommand $COMMANDS } if($null -ne $Base["$KeyCommand+"]) { $ADD = Get-ValueByKey $Base "$KeyCommand+" @() if($COMMANDS -is "System.String") {$COMMANDS = @($COMMANDS)} $COMMANDS += $ADD } if($null -ne $Base["$KeyCommand-"]) { $SUBSTRACT = Get-ValueByKey $Base "$KeyCommand-" @() $COMMANDS = $COMMANDS | ?{$SUBSTRACT -notcontains $_} } Return $COMMANDS }# end of Get-Commands #---------------------------------------------------------------------------------------- # читает настройки ключа. Если ключ не найден, то возвращает значение по умолчанию. function Get-ValueByKey($HashTable, $NameKey, $DefultValue = "") { $OFS = "`r`n" $Value = $HashTable[$NameKey] if ($null -eq $Value) {$Value = $DefultValue} Write-Verbose "$NameKey = $Value" Remove-Variable OFS Return $Value }# end of Get-ValueByKey #---------------------------------------------------------------------------------------- # пишет сообщение в лог и выводит на экран function Write-Log { [CmdletBinding()] param( [string]$Message, # текст сообщения [string]$log, # Полный путь к лог файлу [switch]$Silent, # молчаливая запись в файл - без вывода на экран [switch]$NoTime, # не показывать время [string]$Color="" # цвет сообщения ) $msg = "{0} <{1}>" -f $Message, (Get-Date -Format "HH:mm:ss dd.MM.yyyy") if($NoTime){$msg = $Message} if(-not $Silent) { if($Color -eq "") {Write-Host $msg} else {Write-Host $msg -ForegroundColor $Color} } if($log -ne ""){$msg | Out-File $log -append -encoding unicode} }# end of Write-Log #endregion Start-1C #region Get-Text #---------------------------------------------------------------------------------------- # текст шаблона настроек в Формате JSON function Get-TextJSON { <# !!!ВНИМАНИЕ!!! ОСОБЕННОСТЬ POWERSHELL !!!ВНИМАНИЕ!!! строка передается в переменную как записано здесь - вместе со всеми отступлениями лишних оступов не делать - они будут переданы в файл #> Return '{ "Dir1C": "C:/Program Files (x86)/1cv8/", "Platform1C": "8.3.XX.XXXX", "exe1cv8": "C:/Program Files (x86)/1cv8/8.3.XX.XXXX/bin/1cv8.exe (если задан предыдущие два игнорируются)", "COMMANDS": [ "Команды в режиме конфигуратора или предприятия которые будут выполнены для всех баз из массива Bases1C", "Представляет из себя массив ключей командной строки 1C", "как указано в справке вместе с прямым слэшем и указание режима запуска", "Пример:", "DESIGNER /DumpIB C:/Каталог выгрузок/<NameBase>_<Date>-<Time>.dt", "/NoWait", "если надо просто открыть окно конфигуратора или предприятия", "ENTERPRISE /Execute C:/RenameCF.epf", "где:", "Тэги автозамены будут заменены на соотвествующие им значения", "Теги автозамены (могут быть указаны в параметрах и заменяются на соответствующие им значения):", "<Date> - заменяется на текущую дату в формате YYYYMMDD", "<Time> - заменяется на текущее время в формате HHMM", "<ИмяКлючаПараметраБазы> - заменяется на значение ключа указанного для базы"], "DESIGNER": [ "Команды в режиме конфигуратора которые будут выполнены для всех баз из массива Bases1C" "Представляет из себя массив ключей командной строки 1C без указания режима запуска", "как указано в справке вместе с прямым слэшем", "Пример:", "/DumpIB C:/Каталог выгрузок/<NameBase>_<Date>.dt", "Тэги автозамены будут заменены на соотвествующие им значения.", "/NoWait" ], "ENTERPRISE": [ "Команды в режиме предприятия которые будут выполнены для всех баз из массива Bases1C" "Представляет из себя массив ключей командной строки 1C без указания режима запуска", "как указано в справке вместе с прямым слэшем", "Ожидание завершения команды:", "- все команды в режиме конфигуратора (DESIGNER) запускаются с ожиданием завершения команды", "- все команды в режиме предприятия (ENTERPRISE) запускаются без ожиданием завершения команды", "но это можно изменить указав соответствующие ключи:", "- /Wait явное указание ждать завершения команды", "- /NoWait явное указание НЕ ждать завершения команды (просто открыть окно 1С в режиме конфигуратора или предприятия)" ], "Bases1C": [ { "NameBase": "Произвольное имя базы <Обязательный> Будет использоваться в именах создаваемых фалов и сообщениях пользователю", "Platform1C": "8.3.XX.XXXX (можно переопределить платформу для конкретной базы)", "exe1cv8": "C:/Program Files (x86)/1cv8/8.3.XX.XXXX/bin/1cv8.exe (можно переопределить платформу для конкретной базы)", "IBName": "Имя базы как в окне запуска (если задан все предыдущие параметры платформы игнорируются)", "Connection": [ "<Обязательный>", "Строка подключения к базе", "Представляет из себя массив ключей командной строки 1C", "как указано в справке вместе с прямым слэшем", "Здесь же указывается параметры подключения к хранилищу если необходимо" "/IBName \"Имя базы как в окне запуска (если задан все предыдущие параметры платформы игнорируются)\"" ], "COMMANDS": [ "<Необязательный>", "Массив ключей командной строки которые будут применены только к этой базе", "Подменяет массив ключей заданный для всех баз", "Если задан пустой массив, то общие команды в этой базе не будут выполнены" ], "COMMANDS+": [ "<Необязательный>", "Массив ключей командной строки которые будут применены только к этой базе", "Дополняет массив ключей заданный для всех баз", "Если команды для всех баз не заданы, то будет применен только этот массив параметров" ], "COMMANDS-": [ "<Необязательный>", "Команды в режиме конфигуратора которые НЕ будут выполнены только для этой базы", "Удаляет перечисленные ключи из массива ключей командной строки заданного для всех баз" ], "DESIGNER": [ "<Необязательный>", "Массив ключей командной строки которые будут применены только к этой базе", "Подменяет массив ключей заданный для всех баз", "Если задан пустой массив, то общие команды в этой базе не будут выполнены" ], "DESIGNER+": [ "<Необязательный>", "Массив ключей командной строки которые будут применены только к этой базе", "Дополняет массив ключей заданный для всех баз", "Если команды для всех баз не заданы, то будет применен только этот массив параметров" ], "DESIGNER-": [ "<Необязательный>", "Команды в режиме конфигуратора которые НЕ будут выполнены только для этой базы", "Удаляет перечисленные ключи из массива ключей командной строки заданного для всех баз" ], "ENTERPRISE": [ "<Необязательный>", "Команды в режиме предприятия которые будут выполнены только для этой базы", "Подменяет массив ключей заданный для всех баз" ], "ENTERPRISE+": [ "<Необязательный>", "Команды в режиме предприятия которые будут выполнены только для этой базы", "Дополняет массив ключей заданный для всех баз" ], "ENTERPRISE-": [ "<Необязательный>", "Команды в режиме предприятия которые НЕ будут выполнены только для этой базы", "Удаляет перечисленные ключи из массива ключей заданного для всех баз" ] }, { "NameBase": "ПроизвольноеИмяБазы", "Connection": [ "/FПуть/К/Базе/Разделенный/ПРЯМЫМИ/слэшами(/SСервер:НомерПорта\\ИмяБазы)", "/NПользовательБазы", "/PПарольПользователяБазы", "/ConfigurationRepositoryF tcp://ИмяСервера:НомерПорта/ИмяХранилища", "/ConfigurationRepositoryN ПользовательХранилища", "/ConfigurationRepositoryP ПарольПользователяХранилища" ], "DESIGNER": [ "/ConfigurationRepositoryUpdateCfg -force /UpdateDBCfg", "/ConfigurationRepositoryLock -objects c:/objects.xml" ], "DESIGNER+": [ "/CreateDistributionFiles [-cffile \"c:/ПроизвольноеИмяБазы.cf\"]" ] } ] } ' }# end of Get-TextJSON() #---------------------------------------------------------------------------------------- # текст шаблона настроек в Формате YAML function Get-TextYAML { <# !!!ВНИМАНИЕ!!! ОСОБЕННОСТЬ POWERSHELL !!!ВНИМАНИЕ!!! строка передается в переменную как записано здесь - вместе со всеми отступлениями лишних оступов не делать - они будут переданы в файл #> Return '# Строка начинающаяся с # является комментарием и в параметры не передается # #Теги автозамены (могут быть указаны в параметрах и заменяются на соответствующие им значения): #<Date> - заменяется на текущую дату в формате YYYYMMDD #<Time> - заменяется на текущее время в формате HHMM #<ИмяКлючаПараметраБазы> - заменяется на значение ключа указанного для базы # #Путь к каталогу установки версии платформы 1С Dir1C: C:/Program Files (x86)/1cv8/ #Версия платформы 1С Platform1C: 8.3.XX.XXXX #Непосредственно сам файл запуска платформы 1С exe1cv8: C:/Program Files (x86)/1cv8/8.3.XX.XXXX/bin/1cv8.exe (если задан предыдущие параметры платформы игнорируются) COMMANDS: #- Команды в режиме конфигуратора или предприятия которые будут выполнены для всех баз из массива Bases1C #- Представляет из себя массив ключей командной строки 1C #- как указано в справке вместе с прямым слэшем и указание режима запуска #- Пример: - DESIGNER /DumpIB C:/Каталог выгрузок/<NameBase>_<Date>-<Time>.dt #тэги автозамены будут заменены на соотвествующие им значения - ENTERPRISE /Execute C:/RenameCF.epf DESIGNER: #- Команды в режиме конфигуратора которые будут выполнены для всех баз из массива Bases1C #- Представляет из себя массив ключей командной строки 1C #- как указано в справке вместе с прямым слэшем #- Пример: - /DumpIB C:/Каталог выгрузок/<NameBase>_<Date>-<Time>.dt #тэги автозамены будут заменены на соотвествующие им значения - /NoWait #если надо просто открыть окно конфигуратора или предприятия ENTERPRISE: #- Команды в режиме предприятия которые будут выполнены для всех баз из массива Bases1C #Представляет из себя массив ключей командной строки 1C без указания режима запуска #как указано в справке вместе с прямым слэшем #Ожидание завершения команды: # - все команды в режиме конфигуратора (DESIGNER) запускаются с ожиданием завершения команды # - все команды в режиме предприятия (ENTERPRISE) запускаются без ожиданием завершения команды #но это можно изменить указав соответствующие ключи: # - /Wait явное указание ждать завершения команды # - /NoWait явное указание НЕ ждать завершения команды (просто открыть окно 1С в режиме конфигуратора или предприятия) Bases1C: #- NameBase: Произвольное имя базы. Будет использоваться в именах создаваемых фалов и сообщениях пользователю <Обязательный> # Platform1C: 8.3.XX.XXXX (переопределяет версию платформы для конкретной базы)<Необязательный> # exe1cv8: C:/Program Files (x86)/1cv8/8.3.XX.XXXX/bin/1cv8.exe (можно переопределить файл запуска платформы для конкретной базы)<Необязательный> # IBName: Имя базы как в окне запуска (если задан все предыдущие параметры платформы игнорируются)<Необязательный> # Connection: # <ОБЯЗАТЕЛЬНЫЙ> # - Строка подключения к базе # - Представляет из себя массив ключей командной строки 1C # - как указано в справке вместе с прямым слэшем # - Здесь же указывается параметры подключения к хранилищу если необходимо # - /IBName "Имя базы как в окне запуска (если задан все предыдущие параметры платформы игнорируются)" #Команды в режиме конфигуратора или предприятия которые будут выполнены только для этой базы # COMMANDS: # <Необязательный> # - Подменяет одноименный массив ключей заданный для всех баз # - Если задан пустой массив, то общие команды в этой базе не будут выполнены # COMMANDS+: # <Необязательный> # - Дополняет одноименный массив ключей заданный для всех баз # - Если команды для всех баз не заданы, то будет применен только этот массив параметров # COMMANDS-: # <Необязательный> # - Удаляет перечисленные здесь ключи из одноименного массива ключей заданного для всех баз #Команды в режиме конфигуратора которые будут выполнены только для этой базы # DESIGNER: # <Необязательный> # - Подменяет одноименный массив ключей заданный для всех баз # - Если задан пустой массив, то общие команды в этой базе не будут выполнены # DESIGNER+: # <Необязательный> # - Дополняет одноименный массив ключей заданный для всех баз # - Если команды для всех баз не заданы, то будет применен только этот массив параметров # DESIGNER-: # <Необязательный> # - Удаляет перечисленные здесь ключи из одноименного массива ключей заданного для всех баз #Команды в режиме предприятия которые будут выполнены только для этой базы # ENTERPRISE: # <Необязательный> # - Подменяет одноименный массив ключей заданный для всех баз # - Если задан пустой массив, то общие команды в этой базе не будут выполнены # ENTERPRISE+: # - <Необязательный> # - Дополняет одноименный массив ключей заданный для всех баз # - Если команды для всех баз не заданы, то будет применен только этот массив параметров # ENTERPRISE-: # <Необязательный> # - Удаляет перечисленные здесь ключи из одноименного массива ключей заданного для всех баз # ANY_KEY: любой произвольный ключ с произвольным текстовым значением для замены тегов автозамены #Пример: - NameBase: ПроизвольноеИмяБазы Connection: - /FПуть/К/Базе/Разделенный/ПРЯМЫМИ/слэшами(/SСервер:НомерПорта\\ИмяБазы) - /NПользовательБазы - /PПарольПользователяБазы - /ConfigurationRepositoryF tcp://ИмяСервера:НомерПорта/ИмяХранилища - /ConfigurationRepositoryN ПользовательХранилища - /ConfigurationRepositoryP ПарольПользователяХранилища DESIGNER: - /ConfigurationRepositoryUpdateCfg -force /UpdateDBCfg - /ConfigurationRepositoryLock -objects c:/objects.xml DESIGNER+: - /CreateDistributionFiles [-cffile "c:/<NameBase>.cf"] ' }# end of Get-TextYAML #endregion Get-Text
Read-iBases.ps1
1C.Utils-0.4.0
. $PSScriptRoot\CommonUtils\CommonUtils.ps1 New-Alias -Name 'Parse-iBases' -Value 'Read-iBases' #---------------------------------------------------------------------------------------- # возвращает путь к файлу iBases.v8i function Get-iBasesFullName { <# .SYNOPSIS Возвращает полный путь по умолчанию к файлу iBases.v8i. .DESCRIPTION Проверяет наличие и возвращает полный путь к файлу iBases.v8i. Если файл не существует, то возвращается $null. Расположение файла iBases.v8i по умолчанию: - Для ОС Windows: %APPDATA%\1C\1CEStart\ #> $Result = $null if (Test-Path("$env:APPDATA\1C\1CEStart\iBases.v8i")){$Result = "$env:APPDATA\1C\1CEStart\iBases.v8i"} $Result }# end of Get-iBasesFullName #---------------------------------------------------------------------------------------- # получает файл списка объектов для захвата из отчета сравнения function Read-iBases { <# .SYNOPSIS Преобразует содержимое файла iBases.v8i в массив хэш-таблиц. .DESCRIPTION Преобразует текстовый файл настроек запуска баз iBases.v8i в массив хэш-таблиц, где в каждой хэш-таблице перечисленны все указаные для одной базы параметры. .PARAMETER FilePath Полный путь к файлу iBases.v8i, если не указан будет взят из профиля текущего пользователя. Для ОС Windows: %APPDATA%\1C\1CEStart\iBases.v8i. .EXAMPLE #Получить список файловых баз запускаемых на платформе 8.3: $FileBases = Read-iBases | where {$_.Connect -macth 'File*' -and $_.Version -match '8.3*'} .EXAMPLE #Показать идентификаторы и имена баз запускаемых на платформе 8.3: Read-iBases | where {$_.Version -match '8.3*'} | foreach{Write-Host ("{0} {1}" -f $_.ID, $_.Name)} .EXAMPLE #Сформировать файл Descript.ion (для любителей Far): #в каталог ...\APPDATA\Local\... (кэш метаданых) Read-iBases | foreach{"{0} {1}" -f $_.ID, $_.Name} > $env:LOCALAPPDATA\1C\1cv8\Descript.ion #в каталог ...\APPDATA\Roaming\... (настройки пользователя) Read-iBases | foreach{"{0} {1}" -f $_.ID, $_.Name} > $env:APPDATA\1C\1cv8\Descript.ion #> [CmdletBinding()] param( [string]$FilePath # полный путь к файлу iBases.v8i ) if ($FilePath -eq '') {$FilePath = Get-iBasesFullName} Write-Verbose "FilePath = $FilePath" $BufferBases = @{} switch -Regex -File $Filepath { "^\[(.+)\]$" { Write-Verbose ("`n`t Секция '{0}'" -f $matches[1]) $NameBase = $matches[1] $Section = @{Name = $NameBase} $BufferBases[$NameBase] = $Section } "^([^=]+)=(.*)$" { Write-Verbose ("Ключ '{0}' = '{1}'" -f $matches[1], $matches[2]) $Section[$matches[1]] = $matches[2] } } $iBases = @() $BufferBases.Keys | Sort-Object | foreach{ if ($null -ne $BufferBases[$_]['Connect']){$iBases += $BufferBases[$_]} } $iBases }# end of Read-iBases
CommonUtils.ps1
1C.Utils-0.4.0
#01.2018©willynilly #---------------------------------------------------------------------------------------- # Получает согласие пользователя на продолжение function Get-Permission { <# .Synopsis Получить разрешение от пользователя. .Description Задает вопрос пользователю и ожидает ответа Да/Нет клавишами Enter/Esc. .Parameter TextQuestion Текст однозначного вопроса (без знака вопроса) на который можно ответить Да/Нет. По умолчанию: "Продолжить?" Псевдонимы: t, q .Example if (Get-Permision "Очистить экран") {Clear-Host} #> [CmdletBinding()] param( [Alias("t", "q", "Question")][string]$TextQuestion="Продолжить" # текст вопроса ) # в ISE есть глобальная переменная psISE, а в VS Code есть psEditor # в ISE параметр $host.ui.RawUi.KeyAvailable равен NULL $ispsISE = (Test-path variable:psISE) $ispsEditor = (Test-path variable:psEditor) $isNullKeyAvailable = ($host.ui.RawUi.KeyAvailable -eq $null) Write-Verbose "psISE = $ispsISE" Write-Verbose "psEditor = $ispsEditor" Write-Verbose "isNullKeyAvailable = $isNullKeyAvailable" Write-Verbose ('host.ui.RawUi.KeyAvailable = {0}' -f $host.ui.RawUi.KeyAvailable) $Result = $true Write-Host ("`n{0}? (Enter\Esc)" -f $TextQuestion) -ForegroundColor White while($True) { try { $Key = $host.UI.RawUI.ReadKey("NoEcho,IncludeKeyDown") # !!!НЕ РАБОТАЕТ в ISE и VS CODE!!! if ($key.VirtualKeyCode -eq 27) {$Result = $false; Break} # нажали Esc - выходим из скрипта if ($key.VirtualKeyCode -eq 13) {Break} # нажали Enter - выходим из цикла и идем удалять } catch { $InputUser = Read-Host ('Да <Enter>\Нет <любой символ>') if($InputUser.Length -gt 0) {$Result = $false} Break } } if (-not $Result){Write-Host "Отказ" -ForegroundColor Red} $Result }# end Get-Permission #---------------------------------------------------------------------------------------- # проверяет параметр скрипта WaitPressAnyKey и ждет нажатия любой клавиши если надо function Wait-PressAnyKey { <# .Synopsis Ждет нажатия любой клавиши. .Description Выводит сообщение "Для выхода нажмите любую клавишу..." и ждет. .Example if ($Wait) {Wait-PressAnyKey} #> [CmdletBinding()] param() # в ISE есть глобальная переменная psISE, а в VS Code есть psEditor # в ISE параметр $host.ui.RawUi.KeyAvailable равен NULL $ispsISE = (Test-path variable:psISE) $ispsEditor = (Test-path variable:psEditor) $isNullKeyAvailable = ($host.ui.RawUi.KeyAvailable -eq $null) Write-Verbose "psISE = $ispsISE" Write-Verbose "psEditor = $ispsEditor" Write-Verbose "isNullKeyAvailable = $isNullKeyAvailable" Write-Verbose ('host.ui.RawUi.KeyAvailable = {0}' -f $host.ui.RawUi.KeyAvailable) if (-not($ispsISE -or $ispsEditor -or $isNullKeyAvailable)) { #Остановка скрипта БЕЗ возможности отмены !!!НЕ РАБОТАЕТ В ISE и VS Code!!! Write-host "`nДля выхода нажмите любую клавишу..." -ForegroundColor White $host.UI.RawUI.ReadKey("NoEcho,IncludeKeyDown,AllowCtrlC") | Out-Null } }# end Wait-PressAnyKey #---------------------------------------------------------------------------------------- # получает кодировку файла function Get-Encoding { <# .Synopsis Получает кодировку текстового файла. .Description Определяет кодировку переданного текстового файла. .Parameter filePath Полный путь к текстовому файлу. .Outputs [System.Text.Encoding] .Example Get-Encoding C:\Names.txt #> [CmdletBinding()] param( [Parameter(Mandatory=$True)][string]$filePath ) Try { $sr = New-Object System.IO.StreamReader($filePath, $true) [char[]] $buffer = new-object char[] 3 $sr.Read($buffer, 0, 3) | Out-Null # задавим вывод, иначе попадет в результат функции $encoding = $sr.CurrentEncoding $sr.Close() } catch { #ничего делать не надо } #вернем полученную кодировку $encoding }# end Get-Encoding #---------------------------------------------------------------------------------------- #Открывает диалог выбора файла function Select-FileDialog { <# .Synopsis Выбор файла в диалоговом окне. .Description Открывает стандартное диалоговое окно выбора файла и возвращает полный путь выбранного файла. .Parameter Title Заголовок окна выбора файла. .Parameter Directory Начальный каталог выбора файла. .Parameter Filter Фильтр расширений файлов. По умолчанию все файлы. .Outputs [System.String] .Example $FileConfig = Select-FileDialog "Укажите файл настроек" "C:\Settings" "Файлы настроек (*.cfg)|*.cfg|Все файлы (*.*)|*.*" #> param( [string]$Title, [string]$Directory, [string]$Filter="Все файлы (*.*)|*.*" ) [System.Reflection.Assembly]::LoadWithPartialName("System.Windows.Forms") | Out-Null $objForm = New-Object System.Windows.Forms.OpenFileDialog $objForm.InitialDirectory = $Directory $objForm.Filter = $Filter $objForm.Title = $Title $objForm.ShowDialog() | Out-Null $objForm.FileName } #---------------------------------------------------------------------------------------- # Показывает диалоговое окно вопроса или предупреждения function Show-Dialog { <# .Synopsis Показывает диалоговое окно вопроса или предупреждения. .Description Показывает диалоговое окно вопроса или предупреждения. .Parameter Text Текст сообщения. .Parameter SecondsToWait Количество секунд, по истечении которого окно будет автоматически закрыто. .Parameter Title Текст заголовка окна сообщения. .Parameter Type Комбинация флагов, определяет тип кнопок и значка. Возможные значения флагов: 0 — кнопка ОК. 1 — кнопки ОК и Отмена. 2 — кнопки Стоп, Повтор, Пропустить. 3 — кнопки Да, Нет, Отмена. 4 — кнопки Да и Нет. 5 — кнопки Повтор и Отмена. 16 — значок Stop. 32 — значок Question. 48 — значок Exclamation. 64 — значок Information. .Outputs Возвращает целое значение, с помощью которого можно узнать, какая кнопка была нажата. Возможные значения: -1 — таймаут. 1 — кнопка ОК. 2 — кнопка Отмена. 3 — кнопка Стоп. 4 — кнопка Повтор. 5 — кнопка Пропустить. 6 — кнопка Да. 7 — кнопка Нет. .Example Example #1 Простая форма предупреждения с одной кнопкой Ок, без и иконок и автозакрытия. Show-Dailog "Отправка завершена" Example #2 Форма вопроса с двумя кнопками Да/Нет, иконкой вопроса и таймаутом на размышление 30 сек. Show-Dailog "Завершить работу?" 30 "Вопрос" (4+32) #> [CmdletBinding()] param( [Parameter(Mandatory=$True)][string]$Text, [int]$SecondsToWait, [string]$Title="Предупреждение", [int]$Type ) $wshell = New-Object -ComObject Wscript.Shell $Output = $wshell.Popup($Text,$SecondsToWait,$Title,$Type) return $Output }# end Show-Dialog #---------------------------------------------------------------------------------------- # Конвертирует PSObject полученный после Convert-FromJSON в обычный Hastable function Convert-PSObjectToHashtable { <# .Synopsis Конвертирует PSObject в Hashtable. .Description Рекурсивно конвертирует PSObject полученный после Convert-FromJSON в полноценный Hashtable. .Parameter InputObject Входной объект (может быть передан по конвейеру). .Outputs [System.Hastable] .Example $Config = Get-Content C:\Config.json | ConvertFrom-Json | Convert-PSObjectToHashtable #> param ( [Parameter(ValueFromPipeline)] $InputObject ) process { if ($null -eq $InputObject) { return $null } if ($InputObject -is [System.Collections.IEnumerable] -and $InputObject -isnot [string]) { $collection = @( foreach ($object in $InputObject) { Convert-PSObjectToHashtable $object } ) Write-Output -NoEnumerate $collection } elseif ($InputObject -is [psobject]) { $hash = @{} foreach ($property in $InputObject.PSObject.Properties) { $hash[$property.Name] = Convert-PSObjectToHashtable $property.Value } $hash } else { $InputObject } } }# end Convert-PSObjectToHashtable #---------------------------------------------------------------------------------------- # Выполняет перекодировку строки function ConvertTo-Encoding ([string]$From, [string]$To) { Begin { $encFrom = [System.Text.Encoding]::GetEncoding($from) $encTo = [System.Text.Encoding]::GetEncoding($to) } Process { $bytes = $encTo.GetBytes($_) $bytes = [System.Text.Encoding]::Convert($encFrom, $encTo, $bytes) $encTo.GetString($bytes) } }# end ConvertTo-Encoding #---------------------------------------------------------------------------------------- # Выводит результат теста function Write-Test($Name, $Result, $Count=25, $Sym='.'){ $Test = $Name.PadRight($Count, $Sym) if ($Result -is [bool]){ if ($Result) { Write-Host ($Test + "Ok") } else { Write-Host ($Test + "No") -ForegroundColor DarkYellow } } else { Write-Host ($Test + $Result) } }# end Write-Test
Set-DebugServer1C.ps1
1C.Utils-0.4.0
. $PSScriptRoot\CommonUtils\CommonUtils.ps1 New-Alias -Name 'Dbg-Srv1C' -Value 'Set-DebugServer1C' #---------------------------------------------------------------------------------------- # запускает платформу 1С с переданными ключами командной строки function Set-DebugServer1C { <# .SYNOPSIS Включает/выключает режим отладки на сервере приложений 1С. .DESCRIPTION Запуск без параметров добавляет ключ отладки в строку запуска сервера 1С в реестре Windows и перезапускает службу сервера 1С. Псевдоним: Dbg-Srv1C .PARAMETER Off Отключает отладку на сервере 1С. Если указан, то ключ отладки будет удален из строки запуска сервера. .PARAMETER NotRestart Не перезапускать службу сервера 1С. .PARAMETER Wait Для завершения работы ждать подтверждения от пользователя. #> [CmdletBinding()]# реагирует на стандартные параметры такие как -Verbose Param( [switch]$Off, # Выключить отладку [switch]$NotRestart, # Не перезапускать службу [switch]$Wait # Ожидать нажатия любой клавиши ) $Servers1C = @() # Массив - имен служб серверов 1С $Servers1C += "1C:Enterprise 8.3 Server Agent" $Servers1C += "1C:Enterprise 8.3 Server Agent (x86-64)" foreach($NameService in $Servers1C) {SetDebug $NameService (-not $Off)} if ($Wait) { Wait-PressAnyKey } } #---------------------------------------------------------------------------------------- function SetDebug($ServiceName, $OnDebug=$True) { $ServicePath = "HKLM:\SYSTEM\CurrentControlSet\services\" + $ServiceName if (-not(Test-Path $ServicePath)) {Return} $Service = Get-Item -path ($ServicePath) $ImagePath = $Service.GetValue("ImagePath") Write-Verbose "ImagePath = $ImagePath" if ($ImagePath -eq $null) { Write-Warning ('Не обнаружен путь к файлу запуска службы "{0}"' -f $ServiceName) Return } $CurrentDebugON = $ImagePath -match "-debug" # текущее состояние отладки $NewImagePath = "" $Message = "" # Если надо включить и нет в реестре - добавим в ключ if ($OnDebug -and !$CurrentDebugON) { $NewImagePath = $ImagePath -replace "-srvc", "-DEBUG -srvc" # НЕ чувствителен к регистру $Message = "`n`tОтладка включена" } # Если надо выключить и есть в реестре - удалим из ключа elseif (!$OnDebug -and $CurrentDebugON) { $NewImagePath = ($ImagePath -replace "-debug ") -replace "-debug" # оператор -replace не чувствителен к регистру в отличие от метода .Replace() $Message = "`n`tОтладка отключена" } # Текущий статус elseif ($CurrentDebugON) {$Message = "`n`tОтладка включена"} else {$Message = "`n`tОтладка отключена"} #Если были изменения - запишем их if ($NewImagePath) { Set-ItemProperty -Path $ServicePath -Name "ImagePath" –Value $NewImagePath #Если нет запрета на перезапуск - перезапустим сервер if (!$NotRestart) { Restart-Service -Name $ServiceName $Message = $Message + "`n`tПерезапущен сервер" } } #Cообщим о результатах "{0}{1}" -f $ServiceName, $Message }
1C.Utils.psm1
1C.Utils-0.4.0
. $PSScriptRoot\cmdlets\Clear-Cache1C.ps1 . $PSScriptRoot\cmdlets\Common1C.ps1 . $PSScriptRoot\cmdlets\CommonUtils\CommonUtils.ps1 . $PSScriptRoot\cmdlets\CommonUtils\classLog.ps1 . $PSScriptRoot\cmdlets\Designer1C.ps1 . $PSScriptRoot\cmdlets\Load-ToBase1C.ps1 . $PSScriptRoot\cmdlets\Set-DebugServer1C.ps1 . $PSScriptRoot\cmdlets\Start-1C.ps1 . $PSScriptRoot\cmdlets\Stop-1C.ps1 . $PSScriptRoot\cmdlets\Uninstall-1C.ps1 . $PSScriptRoot\cmdlets\Read-iBases.ps1 #region Utils #---------------------------------------------------------------------------------------- # получает файл списка объектов для захвата из отчета сравнения function Get-ObjectsXML { <# .SYNOPSIS Формирует xml-файл объектов метаданных для захвата в хранилище 1С. .DESCRIPTION Преобразует текстовый отчет сравнения в xml-файл списка объектов как требует платформа 1С для захвата объектов в хранилище 1С (см. справку ключа запуска платформы /ConfigurationRepositoryLock или /ConfigurationRepositoryUnLock). .PARAMETER ReportOfCompare Полный путь к тектовому отчету сравнения. .EXAMPLE #Получить список объектов метаданных для захвата в хранилище 1С: Get-ObjectsXML C:\ReportOfCompare.txt | Out-File C:\Objects.xml #> [CmdletBinding()] param( [string]$ReportOfCompare # отчет о сравнении полный в текстовом виде ) $Name = "" $NameFactor = @{} Write-Verbose "<--Прочитанные строки-->" $Text = Get-Content $ReportOfCompare | where {$_ -match "^\t{2,4}\- (\*{3})?(\w+\.\w+|\w|<--|-->)"} | foreach { if ($_ -match "^\t{2,3}\- \*{3}\w+\.\w+" -and $_ -notmatch "ТабличнаяЧасть") { $Name = $_.Trim().TrimStart("- ***") $NameFactor[$Name] = 0 Write-Verbose $Name } elseif ($_ -match "\- (\*{3})?(\w+|<--|-->)" -and $_ -notmatch "Справочная") { $NameFactor[$Name] += 1 Write-Verbose $_ } } $XML = "<Objects xmlns=`"http://v8.1c.ru/8.3/config/objects`" version=`"1.0`">`n" $NameFactor.GetEnumerator() | Sort-Object -Property Key | foreach {if ($_.Value -gt 0) {$XML += "`t<Object fullName = `"{0}`" includeChildObjects=`"false`" />`n" -f $_.Key}} $XML += "</Objects>" if ($VerbosePreference -eq 'Continue') { Write-Host "" Write-Verbose "<--Количество измененных подчиненных элементов-->" $NameFactor.GetEnumerator() | Sort-Object -Property Key | foreach{Write-Verbose ("{0} {1}" -f $_.Value, $_.Key)} Write-Host "" Write-Verbose "<--Результирующий XML-->" $XML | foreach{Write-Verbose $_} } Return $XML }# end of Get-ObjectsXML #---------------------------------------------------------------------------------------- # получает файл списка ролей для захвата из текста сообщений конфигуратора function Get-RolesXML { <# .SYNOPSIS Формирует xml-файл объектов метаданных для захвата в хранилище 1С. .DESCRIPTION Преобразует список сообщений конфигуратора в xml-файл списка объектов как требует платформа 1С для захвата объектов в хранилище 1С. Список сообщений выдается в окне сообщений конфигуратора при не удачной попытке удаления объектов метаданных в хранилище конфигурации 1С. .PARAMETER File Путь к файлу содержащий список сообщений конфигуратора при не удачном удалении метаданных. .PARAMETER Clipboard Сообщения конфигуратора взять из буфера обмена. .EXAMPLE #Получить список объектов метаданных для захвата в хранилище 1С: Get-ObjectsXML C:\ReportOfCompare.txt | Out-File C:\Objects.xml #> [CmdletBinding()] param( [string]$File, # файл содержащий список ролей которые требуется захватить (выдается в окне сообщений конфигуратора при не удачном удалении) [switch]$Clipboard # Если истина значит в буфер скопирован текст содержащий роли (из окна сообщений конфигуратора при не удачном удалении) ) if($Clipboard) { $TextClipboard = Get-Clipboard $tmp = New-TemporaryFile $TextClipboard | Out-File $tmp.FullName $File = $tmp.FullName } $ListRole = @{} $Text = Get-Content $File | where {$_ -match "(Роль\.|Role\.)"} | foreach { $Role = $_.Trim() # обрежем все перед Роль. $IndexRole = $Role.IndexOf("Роль.") $Role = $Role.Substring($IndexRole, $Role.Length-$IndexRole) # Вырежем от начала строки до первого TAB если есть $IndexTab = $Role.IndexOf("`t") if ($IndexTab -gt 0) {$Role = $Role.Substring(0, $IndexTab)} # Вырежем от начала строки до первого Пробела если есть $IndexSpace = $Role.IndexOf(" ") if ($IndexSpace -gt 0) {$Role = $Role.Substring(0, $Role.Length-$IndexSpace)} #Write-Verbose ("{0} {1} {2} {3} {4}" -f $Role, $IndexRole, $IndexSpace, $IndexTab, $Role.Length) $ListRole[$Role] = 0 } $XML = "<Objects xmlns=`"http://v8.1c.ru/8.3/config/objects`" version=`"1.0`">`n" $ListRole.GetEnumerator() | Sort-Object -Property Key | foreach {$XML += "`t<Object fullName = `"{0}`" includeChildObjects= `"false`" />`n" -f $_.Key} $XML += "</Objects>" if ($VerbosePreference -eq 'Continue') { Write-Host "" Write-Verbose "<--Прочитанные роли-->" $ListRole.GetEnumerator() | Sort-Object -Property Key | foreach{Write-Verbose ("{0}" -f $_.Key)} Write-Host "" Write-Verbose "<--Результирующий XML-->" $XML | foreach{Write-Verbose $_} } if($Clipboard) { Remove-Item $File } Return $XML }# end of Get-RolesXML #endregion Utils
1Cv83_InfoBaseManagement.psm1
1Cv83_InfoBaseManagement-1.0.3
# Connect-1cCluster; Connect-1cWP # Connect-1cCluster 10.0.0.31; Connect-1cWP Function Connect-1cCluster { param( [string]$Server = 'localhost', [PSCredential]$Credential, [string]$ComObject = 'V83.COMConnector' ) $Global:1c = [ordered]@{ 'Server' = $Server 'ComObject' = $Null 'Cluster' = $Null 'Agent' = [ordered]@{ 'Connect' = $Null 'Credential' = [PSCredential]$Null 'Authenticated' = $false 'WP' = @() } 'WP' = [ordered]@{ 'Credential' = [PSCredential]$Null 'Connect' = @() 'InfoBases' = @() 'InfoBaseInfo' = @() } } if(!$Credential) { if(!$1c.Agent.Credential) { [string]$UserName = $Null [string]$Password = $Null } else { [string]$UserName = $1c.Agent.Credential.UserName [string]$Password = $1c.Agent.Credential.GetNetworkCredential().Password } } else { $1c.Agent.Credential = $Credential [string]$UserName = $1c.Agent.Credential.UserName [string]$Password = $1c.Agent.Credential.GetNetworkCredential().Password } $1c.ComObject = New-Object -COMObject $ComObject $1c.Agent.Connect = $1c.ComObject.ConnectAgent($Server) $1c.Cluster = @($1c.Agent.Connect.GetClusters())[0] try { $1c.Agent.Authenticated = $true $1c.Agent.Connect.Authenticate($1c.Cluster, $UserName, $Password) } catch { $1c.Agent.Authenticated = $false Write-Error 'error[Authenticate]' } [pscustomobject][ordered]@{'Server' = $1c.Server; 'ConnectTo1cCluster' = [bool]$1c.Agent.Authenticated; 'ConnectTo1cWP' = [bool]$1c.WP.Connect} } Function Get-1cWorkingServers { if(!$1c.Cluster){ Write-Error 'use Connect-1cCluster' break } $1c.Agent.Connect.GetWorkingServers($1c.Cluster) } Function Get-1cCluster { if(!$1c.Cluster){ Write-Error 'use Connect-1cCluster' break } $1c.Cluster } Function Get-1cClusterInfoBase { param( [string]$infoBaseName = '*' ) if(!$1c.Agent.Authenticated){ Write-Error 'use Connect-1cCluster' break } $1c.Agent.Connect.GetInfoBases($1c.Cluster) | ? {$_.Name -like $infoBaseName} } Function Get-1cClusterConnection { <# .EXAMPLE Get-1cClusterConnection -ProcessMainPort 1562 #> param( [string]$infoBaseName = '*', [string]$SessionID = '*', [string]$ConnID = '*', [string]$ProcessMainPort = '*', [string]$ProcessPID = '*' ) if(!$1c.Agent.Authenticated){ Write-Error 'use Connect-1cCluster' break } $1c.Agent.Connect.GetConnections($1c.Cluster) | ? {($_.infoBase.Name -like $infoBaseName) -and ($_.SessionID -like $SessionID) -and ($_.ConnID -like $ConnID) -and ($_.process.MainPort -like $processMainPort) -and ($_.process.PID -like $ProcessPID)} } Function Get-1cClusterSession { <# .EXAMPLE Get-1cClusterSession #> param( [string]$infoBaseName = '*', [string]$userName = '*', [string]$SessionID = '*' ) if(!$1c.Agent.Authenticated){ Write-Error 'use Connect-1cCluster' break } $1c.Agent.Connect.GetSessions($1c.Cluster) | Select-Object -Property @{'Name'='infoBaseName'; 'Expression'={$_.infoBase.Name}},* | ? {($_.infoBase.Name -like $infoBaseName) -and ($_.userName -like $userName) -and ($_.SessionID -like $SessionID)} } Function Get-1cClusterInfoBaseSession { <# .EXAMPLE Get-1cClusterInfoBase DB* | Get-1cClusterInfoBaseSession #> param( [Parameter(Mandatory=$true,ValueFromPipeline=$true)][System.__ComObject[]]$InfoBase, [string]$infoBaseName = '*', [string]$userName = '*', [string]$SessionID = '*' ) begin{ if(!$1c.Agent.Authenticated){ Write-Error 'use Connect-1cCluster' break } } process{ $InfoBase | % { $1c.Agent.Connect.GetInfoBaseSessions($1c.Cluster,$_) | ? {($_.infoBase.Name -like $infoBaseName) -and ($_.userName -like $userName) -and ($_.SessionID -like $SessionID)} } } } Function Stop-1cClusterInfoBaseSession { <# .EXAMPLE Get-1cClusterInfoBase DB* | Get-1cClusterInfoBaseSession -userName *Smith* | Stop-1cClusterInfoBaseSession #> param( [Parameter(Mandatory=$true,ValueFromPipeline=$true,ValueFromPipelineByPropertyName=$true)][alias('Name')][System.__ComObject[]]$InfoBaseSession ) begin{ if(!$1c.Agent.Authenticated){ Write-Error 'use Connect-1cCluster' break } } process{ $InfoBaseSession | % { $1c.Agent.Connect.TerminateSession($1c.Cluster, $_) } } } Function Get-1cClusterWP { <# .EXAMPLE Get-1cClusterWP -MainPort *1 #> param( [string]$MainPort = '*', [string]$PidWP = '*' ) if(!$1c.Agent.Authenticated){ Write-Error 'use Connect-1cCluster' break } $1c.Agent.Connect.GetWorkingProcesses($1c.Cluster) | ? {($_.MainPort -like $MainPort) -and ($_.PID -like $PidWP)} } Function Connect-1cWP { param( [PSCredential]$Credential ) if(!$1c.Cluster){ Write-Error 'use Connect-1cCluster' break } if(!$Credential) { if(!$1c.WP.Credential) { [string]$UserName = $Null [string]$Password = $Null } else { [string]$UserName = $1c.WP.Credential.UserName [string]$Password = $1c.WP.Credential.GetNetworkCredential().Password } } else { $1c.WP.Credential = $Credential [string]$UserName = $1c.WP.Credential.UserName [string]$Password = $1c.WP.Credential.GetNetworkCredential().Password } $1c.Agent.WP = @($1c.Agent.Connect.GetWorkingProcesses($1c.Cluster)) if($1c.Agent.WP){ $1c.WP.Connect = @($1c.Agent.WP | ? {$_.MainPort -ge 1} | % { $1c.ComObject.ConnectWorkingProcess( $('tcp://' +$_.HostName+':'+$_.MainPort) ) }) $1c.WP.Connect | % {$_.AuthenticateAdmin($UserName,$Password)} $1c.WP.Connect | % {$_.AddAuthentication($UserName,$Password)} } else {Write-Error 'WorkingProcesses not connected'; break} [pscustomobject][ordered]@{'Server' = $1c.Server; 'ConnectTo1cCluster' = [bool]$1c.Agent.Authenticated; 'ConnectTo1cWP' = [bool]$1c.WP.Connect} } Function Get-1cWPInfoBase { param( [string]$Name = '*', [string]$DBName = '*' ) if(!$1c.WP.Connect){ Write-Error 'use Connect-1cWP' break } $1c.WP.Connect | % {$_.GetInfoBases()} | ? {($_.Name -like $Name) -and ($_.DBName -like $DBName)} | Group-Object -Property Name | % {$_.Group | Select-Object -Unique} } Function Set-1cWPInfoBase { <# .EXAMPLE Get-1cWPInfoBase -Name DB | Set-1cWPInfoBase -DeniedFrom (Get-Date).AddDays(-20) -DeniedTo (Get-Date).AddDays(-10) -DeniedMessage 'Test' #> param( [Parameter(Mandatory=$true,ValueFromPipeline=$true)][System.__ComObject[]]$InfoBase, [string]$DBServerName, [string]$DBName, [string]$DBUser, [string]$DBPassword, [bool]$ConnectDenied, [datetime]$DeniedFrom, [datetime]$DeniedTo, [string]$DeniedMessage, [string]$PermissionCode, [bool]$ScheduledJobsDenied, [bool]$SessionsDenied ) begin{ if(!$1c.WP.Connect){ Write-Error 'use Connect-1cWP' break } } process{ $InfoBase | % { if($DBServerName){$_.DBServerName = $DBServerName} if($DBName){$_.DBName = $DBName} if($DBUser){$_.DBUser = $DBUser} if($DBPassword){$_.DBPassword = $DBPassword} if($MyInvocation.BoundParameters.ContainsKey('ConnectDenied')){$_.ConnectDenied = $ConnectDenied} if($DeniedFrom){$_.DeniedFrom = $DeniedFrom} if($DeniedTo){$_.DeniedTo = $DeniedTo} if($DeniedMessage){$_.DeniedMessage = $DeniedMessage} if($PermissionCode){$_.PermissionCode = $PermissionCode} if($MyInvocation.BoundParameters.ContainsKey('ScheduledJobsDenied')){$_.ScheduledJobsDenied = $ScheduledJobsDenied} if($MyInvocation.BoundParameters.ContainsKey('SessionsDenied')){$_.SessionsDenied = $SessionsDenied} foreach ($connect in $1c.WP.Connect) {$connect.UpdateInfoBase($_)} $_ } } } Function Remove-1cWPInfoBase { <# .EXAMPLE Get-1cWPInfoBase DB* | Remove-1cWPInfoBase -SqlDatabaseAction Delete #> param( [Parameter(Mandatory=$true,ValueFromPipeline=$true)][System.__ComObject[]]$InfoBase, [ValidateSet('No','Delete','Clean')][string]$SqlDatabaseAction = 'No' ) begin{ if(!$1c.WP.Connect){ Write-Error 'use Connect-1cWP' break } $Action = @{'No' = 0; 'Delete' = 1; 'Clean' = 2;} } process{ $InfoBase | % { $_ $1c.wp.Connect[0].DropInfoBase($_, $($Action[$SqlDatabaseAction])) } } } Function Add-1cWPInfoBase { <# .EXAMPLE Add-1cWPInfoBase -Name DB -Descr DB -DBServerName localhost -DBName DB -DBUser sa -DBPassword P@$$w0rd -ScheduledJobsDenied $true -LicenseDistributionAllowed $false -CreateEmptyDB $true #> param( [Parameter(Mandatory=$true,ValueFromPipeline=$true)][string]$Name, [string]$Descr = 'PowerShell', [ValidateSet('MSSQLServer','PostgreSQL','IBMDB2','OracleDatabase')][string]$DBMS = 'MSSQLServer', [Parameter(Mandatory=$true,ValueFromPipeline=$true)][string]$DBServerName, [Parameter(Mandatory=$true,ValueFromPipeline=$true)][string]$DBName, [Parameter(Mandatory=$true,ValueFromPipeline=$true)][string]$DBUser, [Parameter(Mandatory=$true,ValueFromPipeline=$true)][string]$DBPassword, [datetime]$DeniedFrom, [datetime]$DeniedTo, [string]$DeniedMessage, [string]$PermissionCode, [string]$Locale = 'RU', [bool]$ConnectDenied = $False, [bool]$ScheduledJobsDenied = $False, [bool]$SessionsDenied = $False, [bool]$LicenseDistributionAllowed = $False, [bool]$CreateEmptyDB = $False ) if(!$1c.WP.Connect){ Write-Error 'use Connect-1cWP' break } $InfoBaseInfo = $1c.WP.Connect[0].CreateInfoBaseInfo() $InfoBaseInfo.Name = $Name if($Descr){$InfoBaseInfo.Descr = $Descr} $InfoBaseInfo.DBMS = $DBMS $InfoBaseInfo.DBServerName = $DBServerName $InfoBaseInfo.DBName = $DBName $InfoBaseInfo.DBUser = $DBUser $InfoBaseInfo.DBPassword = $DBPassword if($DeniedFrom){$InfoBaseInfo.DeniedFrom = $DeniedFrom} if($DeniedTo){$InfoBaseInfo.DeniedTo = $DeniedTo} if($DeniedMessage){$InfoBaseInfo.DeniedMessage = $DeniedMessage} if($PermissionCode){$InfoBaseInfo.PermissionCode = $PermissionCode} $InfoBaseInfo.Locale = $Locale $InfoBaseInfo.ConnectDenied = $ConnectDenied $InfoBaseInfo.ScheduledJobsDenied = $ScheduledJobsDenied $InfoBaseInfo.SessionsDenied = $SessionsDenied $InfoBaseInfo.LicenseDistributionAllowed = [int]$LicenseDistributionAllowed $InfoBaseInfo $1c.wp.Connect[0].CreateInfoBase($InfoBaseInfo,$([int]$CreateEmptyDB)) } Function Get-1cReportClusterConnection { param( [string]$infoBaseName = '*', [string]$UserName = '*', [string]$processMainPort = '*' ) if(!$1c.WP.Connect){ Write-Error 'use Connect-1cWP' break } $InfoBaseSessionHash = Get-1cClusterInfoBase | Get-1cClusterInfoBaseSession | Group-Object -Property SessionID -AsHashTable Get-1cClusterConnection | ? {($_.infoBase.Name -like $infoBaseName) -and ($_.Process.MainPort -like $ProcessMainPort)} | Select-Object -Property @( @{Name='infoBaseName'; Expression={$_.infoBase.Name}} @{Name='ProcessPID'; Expression={$_.process.PID}} @{Name='UserName'; Expression={$InfoBaseSessionHash[[int]$_.SessionID].userName}} @{Name='ProcessMainPort'; Expression={$_.process.MainPort}} @{Name='ProcessHostName'; Expression={$_.process.HostName}} @{Name='SessionHost'; Expression={$InfoBaseSessionHash[[int]$_.SessionID].Host}} @{Name='SessionAppID'; Expression={$InfoBaseSessionHash[[int]$_.SessionID].AppID}} @{Name='ProcessConnections'; Expression={$_.process.connections}} @{Name='ProcessStartedAt'; Expression={$_.process.StartedAt}} @{Name='SessionMemoryAll'; Expression={$InfoBaseSessionHash[[int]$_.SessionID].MemoryAll}} @{Name='ProcessMemorySize'; Expression={$_.process.MemorySize}} '*' ) | ? {$_.UserName -like $UserName} } Function Get-1cReportClusterInfoBaseSession { param( [string]$infoBaseName = '*', [string]$UserName = '*' ) if(!$1c.WP.Connect){ Write-Error 'use Connect-1cWP' break } Get-1cClusterInfoBase | Get-1cClusterInfoBaseSession | ? {($_.infoBase.Name -like $infoBaseName) -and ($_.userName -like $UserName)} | Select-Object -Property @( @{Name='infoBaseName'; Expression={$_.infoBase.Name}} '*' @{Name='LicenseFullPresentation'; Expression={$_.License.FullPresentation}} ) -ExcludeProperty License } Function Reset-1cConnection { if($1c.ComObject){[System.Runtime.Interopservices.Marshal]::ReleaseComObject($1c.ComObject)} if($1c.Cluster){[System.Runtime.Interopservices.Marshal]::ReleaseComObject($1c.Cluster)} if($1c.Agent.Connect){[System.Runtime.Interopservices.Marshal]::ReleaseComObject($1c.Agent.Connect)} if($1c){Remove-Variable -Name 1c -Scope Global -Force -ErrorAction SilentlyContinue} [System.GC]::Collect() }
1Cv83_InfoBaseManagement.psd1
1Cv83_InfoBaseManagement-1.0.3
# # Module manifest for module 1Cv83_InfoBaseManagement # # Generated by: Saw-Friendship # # Generated on: 2017-03-29 # @{ # Script module or binary module file associated with this manifest. RootModule = '1Cv83_InfoBaseManagement.psm1' # Version number of this module. ModuleVersion = '1.0.3' # ID used to uniquely identify this module GUID = '91343d96-0214-4601-9517-bad890b05514' # Author of this module Author = 'Saw-Friendship' # Company or vendor of this module # CompanyName = '' # Copyright statement for this module Copyright = 'Saw-Friendship' # Description of the functionality provided by this module Description = '1C v8.3 InfoBase Management over Com interface' # Minimum version of the Windows PowerShell engine required by this module PowerShellVersion = '3.0' # Name of the Windows PowerShell host required by this module # PowerShellHostName = '' # Minimum version of the Windows PowerShell host required by this module # PowerShellHostVersion = '' # Minimum version of Microsoft .NET Framework required by this module # DotNetFrameworkVersion = '' # Minimum version of the common language runtime (CLR) required by this module # CLRVersion = '' # Processor architecture (None, X86, Amd64) required by this module # ProcessorArchitecture = '' # Modules that must be imported into the global environment prior to importing this module # RequiredModules = '' # Assemblies that must be loaded prior to importing this module # RequiredAssemblies = @() # Script files (.ps1) that are run in the caller's environment prior to importing this module. # ScriptsToProcess = @() # Type files (.ps1xml) to be loaded when importing this module # TypesToProcess = @() # Format files (.ps1xml) to be loaded when importing this module # FormatsToProcess = @() # Modules to import as nested modules of the module specified in RootModule/ModuleToProcess NestedModules = @('1Cv83_InfoBaseManagement.psm1') # Functions to export from this module FunctionsToExport = '*' # Cmdlets to export from this module # CmdletsToExport = '' # Variables to export from this module VariablesToExport = '*' # Aliases to export from this module AliasesToExport = '*' # List of all modules packaged with this module # ModuleList = @() # List of all files packaged with this module # FileList = @() # Private data to pass to the module specified in RootModule/ModuleToProcess # PrivateData = '' # HelpInfo URI of this module # HelpInfoURI = '' # Default prefix for commands exported from this module. Override the default prefix using Import-Module -Prefix. # DefaultCommandPrefix = '' }
lib.ps1
1Poshword-1.0.0
################ # Shared helpers ################ function epoch([uint64] $Seconds) { (New-Object DateTime @(1970,1,1,0,0,0,0,'Utc')).AddSeconds($seconds).ToLocalTime() } function SecureString2String([SecureString] $ss) { (New-Object PSCredential @('xyz', $ss)).GetNetworkCredential().Password } function ClipboardCopy([string[]] $Data) { # turbo h4x to get stuff working cross-plat, with support for # copying w/o trailing newline $clipTemplate = if (Get-Command 'clip.exe' -CommandType Application -ea 0) { 'cmd.exe /c "type {0} | clip.exe"' } elseif (Get-Command 'pbcopy' -CommandType Application -ea 0) { "bash --noprofile --norc -c `"cat {0} | pbcopy`"" } elseif (Get-Command 'xclip' -CommandType Application -ea 0) { "bash --noprofile --norc -c `"cat {0} | xclip -selection clipboard`"" } else { Write-Error "Unable to locate clipboard utility" } $tmp = [IO.Path]::GetTempFileName() try { [IO.File]::WriteAllText($tmp, $data -join [Environment]::NewLine) Invoke-Expression ($clipTemplate -f $tmp) } finally { Remove-Item $tmp } } function NormalizeEntryType([string] $Type) { switch -regex ($type) { '001|WebForm' { 'Login' } '003|SecureNote' { 'SecureNote' } '005|Password' { 'Password' } 'GenericAccount' { 'GenericAccount' } default { $type } } } function DeriveKeyPbkdf2([string] $Password, [byte[]] $Salt, [int] $Iterations, [int] $byteCount, [string] $HashName) { $passBytes = [System.Text.UTF8Encoding]::UTF8.GetBytes($password) $derivation = # if hash algorithm is SHA1, can use built-in Rfc2898DeriveBytes # otherwise, need to use custom code if ($hashName -eq 'SHA1') { New-Object System.Security.Cryptography.Rfc2898DeriveBytes @($passBytes, $salt, $iterations) } else { $hashAlg = Invoke-Expression "New-Object System.Security.Cryptography.HMAC$hashName" Add-Type -TypeDefinition ((Get-Content "$psScriptRoot/pbkdf2.cs") -join "`n") ` -ReferencedAssemblies ([System.Security.Cryptography.HMAC].Assembly.Location),'System.IO' New-Object Medo.Security.Cryptography.Pbkdf2 @($hashAlg, $passBytes, $salt, $iterations) } $keyData = $derivation.GetBytes($byteCount) [PSCustomObject] @{ Key = $keyData | Select-Object -First ($byteCount / 2) Aux = $keyData | Select-Object -Last ($byteCount / 2) } } function DeriveKeyMD5([byte[]] $Key, [byte[]] $Salt) { $key = $key[0 .. ($key.length - 17)] $md5 = [System.Security.Cryptography.MD5]::Create() $prev = @() $keyData = @() while ($keyData.Length -lt 32) { $prev = $md5.ComputeHash($prev + $key + $salt) $keyData += $prev } [PSCustomObject] @{ Key = $keyData[0 .. 15] Aux = $keyData[16 .. 31] } } function AESDecrypt([byte[]] $Data, [byte[]] $Key, [byte[]] $IV) { $aes = [System.Security.Cryptography.Aes]::Create() $aes.Padding = 'None' $decryptor = $aes.CreateDecryptor($key, $iv) $memStream = New-Object System.IO.MemoryStream @(,$data) $cryptStream = New-Object System.Security.Cryptography.CryptoStream $memStream,$decryptor,'Read' $result = $( $b = $cryptStream.ReadByte() while ($b -ne -1) { $b $b = $cryptStream.ReadByte() } ) $cryptStream.Dispose() $memStream.Dispose() $decryptor.Dispose() $aes.Dispose() $result } function PickDecryptionKey([PSCustomObject] $Entry) { $keys = Get-Content "$($entry.VaultPath)/data/default/encryptionKeys.js" | ConvertFrom-Json |% List if ($entry.KeyId) { $keys |? Identifier -eq $entry.KeyId } else { $keys |? Level -eq $entry.SecurityLevel } } function GetPayloadFromDecryptedEntry([string] $DecryptedJson, [PSCustomObject] $Entry) { $decryptedEntry = $decryptedJson | ConvertFrom-Json $username = $null $password = $null $text = $null Set-StrictMode -Off switch($entry.Type) { 'Login' { $password = $decryptedEntry.fields |? Designation -eq 'password' |% Value $username = $decryptedEntry.fields |? Designation -eq 'username' |% Value } 'Password' { $password = $decryptedEntry.password } 'GenericAccount' { $username = $decryptedEntry.username $password = $decryptedEntry.password } 'SecureNote' { $text = $decryptedEntry.notesPlain } default { Write-Error "Entry type $($entry.Type) is not supported" } } Set-StrictMode -Version 2 [PSCustomObject] @{ Username = $username Password = $password SecureNote = $text } } ####################### # AgileKeychain helpers ####################### function DecodeAgileKeychainSaltedString([string] $EncodedString) { $bytes = [System.Convert]::FromBase64String($encodedString.Trim(0)) [PSCustomObject] @{ Salt = $bytes[8 .. 15] Data = $bytes[16 .. ($bytes.Length - 1)] } } function DecryptAgileKeychainData([string] $Data, [object] $Key, [int] $Iterations, [switch] $MD5, [switch] $Pbkdf2) { $decoded = DecodeAgileKeychainSaltedString $data $finalKey = if ($md5) { DeriveKeyMD5 ([byte[]] $key) $decoded.Salt } elseif ($pbkdf2) { $plainPass = SecureString2String $password DeriveKeyPbkdf2 $plainPass $decoded.Salt $iterations 32 'SHA1' } AESDecrypt $decoded.Data $finalKey.Key $finalKey.Aux } function DecryptAgileKeychainEntry([PSCustomObject] $Entry, [securestring] $Password) { $decryptionKey = PickDecryptionKey $entry $dataKey = DecryptAgileKeychainData -Pbkdf2 $decryptionKey.Data $password $decryptionKey.Iterations $dataKeyCheck = DecryptAgileKeychainData -MD5 $decryptionkey.Validation $dataKey if (Compare-Object $dataKey $dataKeyCheck) { Write-Error "Unable to validate master password" } $entryBytes = DecryptAgileKeychainData -MD5 $entry.EncryptedData $dataKey $entryString = [System.Text.Encoding]::UTF8.GetString($entryBytes).Trim() -replace '\p{C}+$' GetPayloadFromDecryptedEntry $entryString $entry } function GetAgileKeychainEntries([string] $VaultPath, [string] $name) { $contents = Get-Content "$vaultPath/data/default/contents.js" | ConvertFrom-Json $entryIds = $contents |? { $_[2] -like $name } |% { $_[0] } Set-StrictMode -Off $entryIds |%{ Get-ChildItem "$vaultPath/data/default/$_.1password" } | Get-Content | ConvertFrom-Json ` |? { $_.Uuid -and ($_.Trashed -ne 'true') } |% { [PSCustomObject] @{ Name = $_.Title Id = $_.Uuid VaultPath = (Resolve-Path $vaultPath).Path SecurityLevel = $_.SecurityLevel KeyId = $_.KeyId Location = $_.Location CreatedAt = (epoch $_.CreatedAt) Type = (NormalizeEntryType $_.TypeName) LastUpdated = (epoch $_.UpdatedAt) EncryptedData = $_.Encrypted KeyData = $null } } | Add-Member -TypeName 'Entry' -PassThru Set-StrictMode -Version 2 } function 1PTabExpansion($entryStub, $vaultPath) { $quote = $null if ($entryStub -match "^(`"|')") { $quote = $matches[1] $entryStub = $entryStub -replace "^(`"|')+" } $entryStub = $entryStub -replace "(`"|')+$" GetAgileKeychainEntries $vaultPath "$entryStub*" |% Name |% { $localQuote = if ($quote) { $quote } elseif ($_ -match '\s') { "'" } else { $null } "$localQuote$_$localQuote" } } ################# # OPVault helpers ################# function DecryptOPVaulOPData([string] $Data, [PSObject] $Key) { $dataBytes = [Convert]::FromBase64String($data) $dataLen = 0 $mul = 1 $dataBytes[8..15] |% { $dataLen += $mul * $_; $mul *= 256 } $padLength = 16 - ($dataLen % 16) $computedHash = (New-Object System.Security.Cryptography.HMACSHA256 @(,$key.Aux)).ComputeHash(($dataBytes | Select-Object -First (32 + $padLength + $dataLen))) $declaredHash = $dataBytes | Select-Object -Skip (32 + $padLength + $dataLen) if (Compare-Object $computedHash $declaredHash) { Write-Error "Unable to validate master password" } $iv = $dataBytes[16..31] $encryptedBytes = $dataBytes | Select-Object -Skip 32 | Select-Object -First ($dataLen + $padLength) AESDecrypt $encryptedBytes $key.Key $iv | Select-Object -Skip $padLength } function DecryptOPVaultItemKey([string] $Data, [PSObject] $Key) { $dataBytes = [Convert]::FromBase64String($data) $iv = $dataBytes[0..15] $encryptedKey = $dataBytes[16..79] $computedHash = (New-Object System.Security.Cryptography.HMACSHA256 @(,$key.Aux)).ComputeHash(($dataBytes | Select-Object -First 80)) $declaredHash = $dataBytes | Select-Object -Last 32 if (Compare-Object $computedHash $declaredHash) { Write-Error "Unable to validate master password" } AESDecrypt $encryptedKey $key.Key $iv } function GetOPVaultKeyFromBytes([byte[]] $Bytes, [switch] $NoHash) { $resultBytes = if ($noHash) { $bytes } else { [System.Security.Cryptography.SHA512]::Create().ComputeHash($bytes) } [PSCustomObject] @{ Key = $resultBytes | Select-Object -First 32 Aux = $resultBytes | Select-Object -Last 32 } } function DecryptOPVaultEntry([PSCustomObject] $Entry, [securestring] $Password) { $vaultProfile = ((Get-Content "$($entry.VaultPath)/default/profile.js") -replace '^var profile=(.+);$','$1') | ConvertFrom-Json $plainPass = SecureString2String $password $derivedKey = DeriveKeyPbkdf2 $plainPass ([Convert]::FromBase64String($vaultProfile.Salt)) $vaultProfile.Iterations 64 'SHA512' $encryptionKeyData = DecryptOPVaulOPData $vaultProfile.MasterKey $derivedKey $encryptionKey = GetOPVaultKeyFromBytes $encryptionKeyData $itemKeyBytes = DecryptOPVaultItemKey $entry.KeyData $encryptionKey $itemKey = GetOPVaultKeyFromBytes $itemKeyBytes -NoHash $entryBytes = DecryptOPVaulOPData $entry.EncryptedData $itemKey $entryString = [System.Text.Encoding]::UTF8.GetString($entryBytes) GetPayloadFromDecryptedEntry $entryString $entry } function GetOPVaultEntries([string] $VaultPath, [string] $Name, [securestring] $Password) { $vaultProfile = ((Get-Content "$vaultPath/default/profile.js") -replace '^var profile=(.+);$','$1') | ConvertFrom-Json $plainPass = SecureString2String $password $derivedKey = DeriveKeyPbkdf2 $plainPass ([Convert]::FromBase64String($vaultProfile.Salt)) $vaultProfile.Iterations 64 'SHA512' $overviewKeyData = DecryptOPVaulOPData $vaultProfile.OverviewKey $derivedKey $overviewKey = GetOPVaultKeyFromBytes $overviewKeyData $entries = Get-ChildItem "$vaultPath/default/band_*.js" | Get-Content |% { $bandEntries = $_ -replace '^ld\((.+)\);$', '$1' | ConvertFrom-Json $bandEntries | Get-Member -MemberType NoteProperty |% Name |% { $bandEntries.$_ } } Set-StrictMode -Off $entries |? Category -ne '099' |%{ $entryBytes = DecryptOPVaulOPData $_.o $overviewKey $entryData = [System.Text.Encoding]::UTF8.GetString($entryBytes) | ConvertFrom-Json [PSCustomObject] @{ Name = $entryData.Title Id = $_.Uuid VaultPath = (Resolve-Path $vaultPath).Path SecurityLevel = $null KeyId = $null Location = $entryData.Url CreatedAt = (epoch $_.Created) Type = (NormalizeEntryType $_.Category) LastUpdated = (epoch $_.Updated) EncryptedData = $_.D KeyData = $_.K } | Add-Member -TypeName 'Entry' -PassThru } |? Name -like $name Set-StrictMode -Version 2 }
1Poshword.psm1
1Poshword-1.0.0
#Requires -Version 4 param([string] $DefaultVaultPath) Set-StrictMode -Version 2 $errorActionPreference = 'Stop' $defaultVaultPath = $defaultVaultPath,"$home/Dropbox/1Password/1Password.agilekeychain","$home/Dropbox/1Password/1Password.opvault" ` |? { $_ -and (Test-Path $_) } ` | Resolve-Path ` | Select-Object -First 1 if(-not $DefaultVaultPath) { Write-Warning "Unable to auto-detect a 1Password vault location. Use Set-1PDefaultVaultPath to set a default." } . $psScriptRoot/lib.ps1 <# .SYNOPSIS Sets the default 1Password vault directory to a new value. .DESCRIPTION Sets the default 1Password vault directory to a new value. The 1Password vault at this location will be used by other 1Poshword cmdlets unless otherwise specified. .PARAMETER Path Specifies the root directory of the default 1Password vault. This is the ".agilekeychain" or ".opvault" directory. .EXAMPLE PS ~$ Set-1PDefaultVaultPath /Users/calvin/Dropbox/OtherVault.agilekeychain .EXAMPLE PS ~$ Set-1PDefaultVaultPath /Users/calvin/Dropbox/OtherVault.opvault #> function Set-1PDefaultVaultPath { [CmdletBinding(SupportsShouldProcess = $true)] param( [Parameter(Mandatory = $true)] [ValidateScript({ (Test-Path $_ -PathType Container) -and ($_ -match '\.(agilekeychain|opvault)(/|\\)?$') })] [string] $Path ) if ($psCmdlet.ShouldProcess($path)) { $script:DefaultVaultPath = Resolve-Path $path } } <# .SYNOPSIS Gets the default 1Password root directory. .DESCRIPTION Gets the default 1Password root directory. The 1Password vault at this location will be used by all other 1Poshword cmdlets unless otherwise specified. .EXAMPLE PS ~$ Get-1PDefaultVaultPath #> function Get-1PDefaultVaultPath { $script:DefaultVaultPath } <# .SYNOPSIS Gets encrypted 1Password entries and their associated metadata. .DESCRIPTION Gets one or more encrypted 1Password entries by name, along with associated metadata. The 'agilekeychain' vault format leaves entry metadata in plaintext, so no password is required for this operation. The 'opvault' vault format encrypts all entry metadata, so a password is required if this operation is run against an 'opvault' vault. .PARAMETER Name Specifies the name of the 1Password entry. A case-insensitive wildcard match is used. .PARAMETER VaultPassword Specifies the 1Password vault password. Required only if the 1Password vault is in 'opvault' format. In this case, if no value is specified, the user will be prompted to enter password interactively. .PARAMETER VaultPath Specifies the root directory of the 1Password vault from which to read. The default root directory can be read via Get-1PDefaultVaultPath, and changed via Set-1PDefaultVaultPath. .EXAMPLE # Gets an entry by name PS ~$ Get-1PEntry gmail Name Type LastUpdated Location ---- ---- ----------- -------- gmail Login 11/30/15 12:11:50 AM https://accounts.gmail.com/ServiceLogin # show all available properties PS ~$ Get-1PEntry gmail | Format-List * Name : gmail Id : 11C5741DE2294A1EB32FB088F5838951 VaultPath : /Users/calvin/Dropbox/1Password/1Password.agilekeychain SecurityLevel : SL5 KeyId : KeyData : Location : https://accounts.gmail.com/ServiceLogin Type : Login CreatedAt : 10/28/15 11:21:15 PM LastUpdated : 11/30/15 12:11:50 AM EncryptedData : U2FsdGVkX19ESuKr39T+d4185iU1NzMhKcfffu8 ... .EXAMPLE # Gets the list of all 1Password entries, sorted by last modified time PS ~$ Get-1PEntry | Sort-Object LastUpdated Name Type LastUpdated Location ---- ---- ----------- -------- Twitter Login 11/29/15 11:53:44 PM https://twitter.com/ Github Login 11/29/15 11:58:12 PM https://github.com/login Facebook Login 11/30/15 12:02:04 AM https://www.facebook.com/login.php Linkedin Login 11/30/15 12:09:11 AM https://www.linkedin.com/uas/login-submit ... #> function Get-1PEntry { param( [Parameter(Position = 0)] [string] $Name, [Parameter(Position = 1)] [SecureString] $VaultPassword, [ValidateScript({ (Test-Path $_ -PathType Container) -and ($_ -match '\.(agilekeychain|opvault)(/|\\)?$') })] [string] $VaultPath = ($script:DefaultVaultPath) ) if(-not $name){ $name = '*' } $result = $null if ($vaultPath -match '\.agilekeychain\b') { $result = GetAgileKeychainEntries $vaultPath $name } elseif ($vaultPath -match '\.opvault\b') { if (-not $vaultPassword) { $vaultPassword = Read-Host -AsSecureString -Prompt "1Password vault password" } $result = GetOPVaultEntries $vaultPath $name $vaultPassword } if((-not $result) -and ($name -notmatch '\*')) { Write-Error "No 1Password entries found with name $name" } $result } <# .SYNOPSIS Decrypts a 1Password Login, Password, Secure Note, or Generic Account. .DESCRIPTION Decrypts a 1Password Login, Password, Secure Note, or Generic Account to various output formats. Logins and Generic Adcounts are returned as PSCredential by default. Passwords and Secure Notes are returned as SecureString by default. All forms can optionally be returned as plaintext strings or copied to the clipboard. .PARAMETER Name Specifies the name of the 1Password entry. A case-insensitive wildcard match is used. An error is thrown if no entries, or more than one entry, match the specified name. .PARAMETER Entry Specifies the 1Password entry to decrypt. .PARAMETER VaultPassword Specifies the 1Password vault password. If no value is specified, the user will be prompted to enter password interactively. .PARAMETER Plaintext If specified, the decrypted data will be returned as plaintext strings. Logins and Generic Accounts will be returned as 2 strings (username followed by password) unless -PasswordOnly is also specified. Passwords and Secure Notes will be returned as 1 string. .PARAMETER PasswordOnly If specified, only the password field is included in the output. This parameter has no effect when returning Password or Secure Note entries. .PARAMETER Clip If specified, the plaintext content of the entry will be copied to the clipboard. Attempts to use a system utility for copying: - Windows: clip.exe - Mac: pbcopy - Linux: xclip .PARAMETER VaultPath Specifies the root directory of the 1Password vault from which to read. The default root directory can be read via Get-1PDefaultVaultPath, and changed via Set-1PDefaultVaultPath. .EXAMPLE # Gets a login as a PSCredential. PS ~$ Unprotect-1PEntry email 1Password vault password: ********** UserName Password -------- -------- calvin@gmail.com System.Security.SecureString .EXAMPLE # Pipes a decrypted password into another command which normally prompts for a password. PS ~$ Unprotect-1PEntry systemlogin -Plaintext -PasswordOnly | sudo -Sk echo "`ndude, sweet" 1Password vault password: ********** Password: dude, sweet .EXAMPLE # Temporarily reveals a Secure Note by piping it to 'less' PS ~$ Get-1PEntry mynote | Unprotect-1PEntry -Plaintext | less 1Password vault password: ********** .EXAMPLE # Copies a password to the clipboard PS ~$ Unprotect-1PEntry mylogin -Clip -PasswordOnly 1Password vault password: ********** .EXAMPLE # Uses a bound SecureString object to specify the 1Password vault password. PS ~$ $p = Read-Host -AsSecureString "Speak, friend, and enter" Speak, friend, and enter: ********** PS ~$ Unprotect-1PEntry mynote $p System.Security.SecureString PS ~$ Unprotect-1PEntry mynote $p -Plaintext s3cret m3ssage #> function Unprotect-1PEntry { [CmdletBinding(DefaultParameterSetName = 'Name/Secure')] param( [Parameter(Mandatory = $true, Position = 0, ParameterSetName = 'Name/Secure')] [Parameter(Mandatory = $true, Position = 0, ParameterSetName = 'Name/Plain')] [Parameter(Mandatory = $true, Position = 0, ParameterSetName = 'Name/Clip')] [string] $Name, [Parameter(Mandatory = $true, Position = 0, ValueFromPipeline = $true, ParameterSetName = 'Entry/Secure')] [Parameter(Mandatory = $true, Position = 0, ValueFromPipeline = $true, ParameterSetName = 'Entry/Plain')] [Parameter(Mandatory = $true, Position = 0, ValueFromPipeline = $true, ParameterSetName = 'Entry/Clip')] [PSCustomObject] $Entry, [Parameter(Position = 1)] [SecureString] $VaultPassword, [Parameter(Mandatory = $true, ParameterSetName = 'Name/Plain')] [Parameter(Mandatory = $true, ParameterSetName = 'Entry/Plain')] [switch] $Plaintext, [Parameter(ParameterSetName = 'Name/Secure')] [Parameter(ParameterSetName = 'Name/Plain')] [Parameter(ParameterSetName = 'Name/Clip')] [Parameter(ParameterSetName = 'Entry/Secure')] [Parameter(ParameterSetName = 'Entry/Plain')] [Parameter(ParameterSetName = 'Entry/Clip')] [Alias('po')] [switch] $PasswordOnly, [Parameter(Mandatory = $true, ParameterSetName = 'Name/Clip')] [Parameter(Mandatory = $true, ParameterSetName = 'Entry/Clip')] [switch] $Clip, [Parameter(ParameterSetName = 'Name/Secure')] [Parameter(ParameterSetName = 'Name/Plain')] [Parameter(ParameterSetName = 'Name/Clip')] [ValidateScript({ (Test-Path $_ -PathType Container) -and ($_ -match '\.(agilekeychain|opvault)(/|\\)?$') })] [string] $VaultPath = ($script:DefaultVaultPath) ) $paramSet = $psCmdlet.ParameterSetName $opVault = ($name -and ($vaultPath -match '\.opvault\b')) -or ($entry -and $entry.KeyData) if ($name) { if ($opVault -and (-not $vaultPassword)) { $vaultPassword = Read-Host -AsSecureString -Prompt "1Password vault password" } $entries = Get-1PEntry -Name $name -VaultPath $vaultPath -VaultPassword $vaultPassword if (-not $entries) { Write-Error "No 1Password entries found with name $name" } if (@($entries).Length -gt 1) { Write-Error "More than one entry matches ${name}: $($entries -join ', ')" } $entry = $entries } if(-not $vaultPassword){ $vaultPassword = Read-Host -AsSecureString -Prompt "1Password vault password" } $decrypted = if ($opVault) { DecryptOPVaultEntry $entry $vaultPassword } else { DecryptAgileKeychainEntry $entry $vaultPassword } if ($paramSet -match 'Secure') { if ($entry.Type -eq 'SecureNote') { ConvertTo-SecureString $decrypted.SecureNote -AsPlainText -Force } elseif (($entry.Type -eq 'Password') -or ($passwordOnly)) { ConvertTo-SecureString $decrypted.Password -AsPlainText -Force } else { New-Object PSCredential @($decrypted.Username, (ConvertTo-SecureString $decrypted.Password -AsPlainText -Force)) } } else { $result = $( if(-not $passwordOnly) { $decrypted.Username |? { $_ } } $decrypted.SecureNote |? { $_ } $decrypted.Password |? { $_ } ) if ($paramSet -match 'Plain') { $result } elseif ($paramSet -match 'Clip') { ClipboardCopy $result } } } $1pArgCompleter = { param($commandName, $parameterName, $wordToComplete, $commandAst, $boundParameters) if ($script:DefaultVaultPath -match '\.agilekeychain\b') { 1PTabExpansion $wordToComplete $script:DefaultVaultPath } } if (Get-Command 'Register-ArgumentCompleter' -ea 0) { Register-ArgumentCompleter -CommandName 'Get-1PEntry','Unprotect-1PEntry' -ParameterName Name -ScriptBlock $1pArgCompleter } else { $global:1pTabExpansionOptions = @{ CustomArgumentCompleters = @{} NativeArgumentCompleters = @{} } $global:1pTabExpansionOptions['CustomArgumentCompleters']['Get-1PEntry:Name'] = $1pArgCompleter $global:1pTabExpansionOptions['CustomArgumentCompleters']['Unprotect-1PEntry:Name'] = $1pArgCompleter $function:tabexpansion2 = $function:tabexpansion2 -replace 'End(\r|\n|\s)*{','End { if ($null -ne $options) { $options += $global:1pTabExpansionOptions} else {$options = $global:1pTabExpansionOptions};' } New-Alias g1p Get-1PEntry New-Alias 1p Unprotect-1PEntry Update-TypeData -TypeName 'Entry' -DefaultDisplayPropertySet Name,Type,LastUpdated,Location -Force Export-ModuleMember ` -Function 'Get-1PDefaultVaultPath','Set-1PDefaultVaultPath','Get-1PEntry','Unprotect-1PEntry','TabExpansion' ` -Alias 'g1p','1p'
1Poshword.psd1
1Poshword-1.0.0
@{ # Script module or binary module file associated with this manifest. RootModule = '1Poshword' # Version number of this module. ModuleVersion = '1.0.0' # ID used to uniquely identify this module GUID = '36a94a72-beaf-431f-aaaf-b102b1e37f8a' # Author of this module Author = 'Lincoln Atkinson' # Copyright statement for this module Copyright = 'Lincoln Atkinson, 2016' # Description of the functionality provided by this module Description = 'PowerShell client for the 1Password password manager' # Minimum version of the Windows PowerShell engine required by this module PowerShellVersion = '4.0' # Functions to export from this module, for best performance, do not use wildcards and do not delete the entry, use an empty array if there are no functions to export. FunctionsToExport = 'Get-1PDefaultVaultPath','Set-1PDefaultVaultPath','Get-1PEntry','Unprotect-1PEntry' # Cmdlets to export from this module, for best performance, do not use wildcards and do not delete the entry, use an empty array if there are no cmdlets to export. CmdletsToExport = @() # Variables to export from this module VariablesToExport = $null # Aliases to export from this module, for best performance, do not use wildcards and do not delete the entry, use an empty array if there are no aliases to export. AliasesToExport = 'g1p','1p' # List of all files packaged with this module FileList = @('1poshword.psd1', '1poshword.psm1', 'lib.ps1', 'pbkdf2.cs') # Private data to pass to the module specified in RootModule/ModuleToProcess. This may also contain a PSData hashtable with additional module metadata used by PowerShell. PrivateData = @{ PSData = @{ # Tags applied to this module. These help with module discovery in online galleries. Tags = @('1Poshword', '1Password', 'password', 'cryptography', 'crypto') # A URL to the license for this module. LicenseUri = 'https://raw.githubusercontent.com/latkin/1poshword/master/LICENSE' # A URL to the main website for this project. ProjectUri = 'https://github.com/latkin/1poshword' # ReleaseNotes of this module ReleaseNotes = 'Initial release' } } }
1Pwd.psd1
1Pwd-2.0.1
@{ RootModule = '1Pwd.psm1' ModuleVersion = '2.0.1' GUID = '37ae3083-de56-4688-8504-6df789c6e388' Author = 'Darren J Robinson' CompanyName = 'Community' Copyright = '(c) 2023 Darren J Robinson. All rights reserved.' Description = 'PowerShell Module for 1Password CLI v1.x and v2.x' PowerShellVersion = '5.1' CompatiblePSEditions = 'Core', 'Desktop' RequiredModules = '' FunctionsToExport = @('Set-1PasswordConfiguration', 'Switch-1PasswordConfiguration', 'Test-1PasswordCredentials', 'Invoke-1PasswordExpression') CmdletsToExport = @() VariablesToExport = @() AliasesToExport = @('1pwd') } # SIG # Begin signature block # MIIoKQYJKoZIhvcNAQcCoIIoGjCCKBYCAQExDzANBglghkgBZQMEAgEFADB5Bgor # BgEEAYI3AgEEoGswaTA0BgorBgEEAYI3AgEeMCYCAwEAAAQQH8w7YFlLCE63JNLG # KX7zUQIBAAIBAAIBAAIBAAIBADAxMA0GCWCGSAFlAwQCAQUABCDRQP1IajeN35UH # 7cZPWZnV+3hlz3wbnNOQvxa8/q08XKCCISwwggWNMIIEdaADAgECAhAOmxiO+dAt # 5+/bUOIIQBhaMA0GCSqGSIb3DQEBDAUAMGUxCzAJBgNVBAYTAlVTMRUwEwYDVQQK # EwxEaWdpQ2VydCBJbmMxGTAXBgNVBAsTEHd3dy5kaWdpY2VydC5jb20xJDAiBgNV # BAMTG0RpZ2lDZXJ0IEFzc3VyZWQgSUQgUm9vdCBDQTAeFw0yMjA4MDEwMDAwMDBa # Fw0zMTExMDkyMzU5NTlaMGIxCzAJBgNVBAYTAlVTMRUwEwYDVQQKEwxEaWdpQ2Vy # dCBJbmMxGTAXBgNVBAsTEHd3dy5kaWdpY2VydC5jb20xITAfBgNVBAMTGERpZ2lD # ZXJ0IFRydXN0ZWQgUm9vdCBHNDCCAiIwDQYJKoZIhvcNAQEBBQADggIPADCCAgoC # ggIBAL/mkHNo3rvkXUo8MCIwaTPswqclLskhPfKK2FnC4SmnPVirdprNrnsbhA3E # MB/zG6Q4FutWxpdtHauyefLKEdLkX9YFPFIPUh/GnhWlfr6fqVcWWVVyr2iTcMKy # unWZanMylNEQRBAu34LzB4TmdDttceItDBvuINXJIB1jKS3O7F5OyJP4IWGbNOsF # xl7sWxq868nPzaw0QF+xembud8hIqGZXV59UWI4MK7dPpzDZVu7Ke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agge7B/WBgW/DosL0bZMawTP4hMDDxW1uikyfTN2nV # qsi3P3Ny4eCy0e6PiAUcPQJe7jo5pYulS0HSAjpzcRSiDo11LDC1us4NXbEzGqW/ # vQ9GeW32DJSgl1e+HakChIm1sYJyJFb0hBQz/JDgLeOFcqfeaDm4eIIVnYzciB5Z # wvsdM1IAYT/Mw3E9ehPg9Wy3Gb8C7ezmsTVL1+W1nrxOQDb/9voaAt3vxe7bB4gK # cgkWDI5jncib2UqH1g== # SIG # End signature block
1Pwd.psm1
1Pwd-2.0.1
$CommandsToExport = @() $Global:1PasswordConfiguration = $null $Global:Vault = $null $Global:SignInAddress = $null $Global:SignInAccount = $null $Global:SecretKey = $null $Global:MasterPassword = $null $Global:DefaultVault = $null $Global:CliLocation = $null # Ensure op.exe is in the directory on load. if ($null -eq $CliLocation) { Try { $version = $(.\op.exe --version) $Global:CliLocation = (get-location).Path Set-Location -Path $Global:CliLocation if ($version -ge 2) { $Global:CLIVersion = 2 Write-Verbose "CLI Version $($Global:CLIVersion) detected in the local directory '$($Global:CliLocation)'. CLI Verson $($version)" } elseif ($version -lt 2 ) { $Global:CLIVersion = 1 Write-Verbose "CLI Version $($Global:CLIVersion) detected in the local directory '$($Global:CliLocation)'. CLI Verson $($version)" } } catch { Write-Error -message "1Password CLI not found in the current path. Download the 1Password CLI executable 'op.exe' and put it in the same directory as your script(s)." break } } $1PasswordConfigurationFile = Join-Path "$($env:LOCALAPPDATA)" 1PasswordConfiguration.clixml if (Test-Path $1PasswordConfigurationFile) { $1PasswordConfiguration = Import-Clixml $1PasswordConfigurationFile if ($1PasswordConfiguration.DefaultVault) { $Global:1PasswordConfiguration = $1PasswordConfiguration.($1PasswordConfiguration.DefaultVault) $Global:Vault = $Global:1PasswordConfiguration.Vault $Global:SignInAddress = $Global:1PasswordConfiguration.SignInAddress $Global:SignInAccount = $Global:1PasswordConfiguration.SignInAccount $Global:SecretKey = $Global:1PasswordConfiguration.SecretKey $Global:MasterPassword = $Global:1PasswordConfiguration.MasterPassword } } function Set-1PasswordConfiguration { <# .SYNOPSIS Sets the default 1Password Vault and credentials. .DESCRIPTION Sets the default 1Password Vault and credentials. Configuration values can be securely saved to a user's profile using Set-1PasswordConfiguration. .PARAMETER Default Set the profile configuration being set as the Default. Default indicates that configuration is loaded when the module loads. .PARAMETER Vault The Vault name used for the profile configuration. .PARAMETER SignInAddress The 1Password User's Sign-In URI .PARAMETER SignInAccount The 1Password User's Sign-In email address .PARAMETER SecretKey The 1Password User's Secret Key .PARAMETER MasterPassword The 1Password User's Master Password .EXAMPLE $1PSignInAddress = "https://my.1password.com" $1PSignInAccount = "you@yourDomain.com" $1PSecretKey = Read-Host "Enter your 1Password SecretKey" -AsSecureString $1PMasterPassword = Read-Host "Enter your 1Password Master Password" -AsSecureString $account = Test-1PasswordCredentials -SignInAddress $1PSignInAddress -SignInAccount $1PSignInAccount -SecretKey $1PSecretKey -MasterPassword $1PMasterPassword Set-1PasswordConfiguration -Vault $account.domain -SignInAddress $1PSignInAddress -SignInAccount $1PSignInAccount -SecretKey $1PSecretKey -MasterPassword $1PMasterPassword -Default .LINK http://darrenjrobinson.com/ #> [CmdletBinding()] param ( [Parameter(Mandatory = $false, ValueFromPipeline = $true)][switch]$default, [Parameter(Mandatory = $true, ValueFromPipeline = $true)][String]$Vault, [Parameter(Mandatory = $true, ValueFromPipeline = $true)][String]$SignInAddress, [Parameter(Mandatory = $true, ValueFromPipeline = $true)][String]$SignInAccount, [Parameter(Mandatory = $true, ValueFromPipeline = $true)][SecureString]$SecretKey, [Parameter(Mandatory = $true, ValueFromPipeline = $true)][SecureString]$MasterPassword) $newProfile = @{$Vault = @{ Vault = $Vault SignInAddress = $SignInAddress SignInAccount = $SignInAccount SecretKey = $SecretKey MasterPassword = $MasterPassword } } $Global:1PasswordConfiguration += $newProfile if ($default) { $1PasswordConfiguration.DefaultVault = $Vault Export-Clixml -Path $1PasswordConfigurationFile -InputObject $1PasswordConfiguration } else { Export-Clixml -Path $1PasswordConfigurationFile -InputObject $1PasswordConfiguration } } $CommandsToExport += 'Set-1PasswordConfiguration' function Switch-1PasswordConfiguration { <# .SYNOPSIS Changes the 1Password configuration to a different Vault. .DESCRIPTION Changes the 1Password configuration used to a different Vault. Optionally sets the default 1Password Vault. Configuration values can be securely saved to a user's profile using Set-1PasswordConfiguration. .PARAMETER Vault Vault to switch too. .PARAMETER default (Optional) Set the Vault being switched to as the new Default Vault that will be loaded on Module Load. .EXAMPLE Switch-1PasswordConfiguration -vault My .EXAMPLE Switch-1PasswordConfiguration -vault My -default .LINK http://darrenjrobinson.com/ #> [CmdletBinding()] param ( [Parameter(Mandatory = $true, Position = 0)] [string]$Vault, [Parameter(Mandatory = $false, Position = 0)] [switch]$default ) if ($1PasswordConfiguration.$Vault) { $Global:1PasswordConfiguration = $1PasswordConfiguration.($1PasswordConfiguration.Vault) Write-Information "Setting Globals" $Global:Vault = $Global:1PasswordConfiguration.Vault $Global:SignInAddress = $Global:1PasswordConfiguration.SignInAddress $Global:SignInAccount = $Global:1PasswordConfiguration.SignInAccount $Global:SecretKey = $Global:1PasswordConfiguration.SecretKey $Global:MasterPassword = $Global:1PasswordConfiguration.MasterPassword if ($default) { $Global:1PasswordConfiguration.DefaultVault = $Vault Export-Clixml -Path $1PasswordConfigurationFile -InputObject $1PasswordConfiguration } } else { Write-Error "No Vault with name $($Vault) was found in the 1Password Configuration file." break } } $CommandsToExport += 'Switch-1PasswordConfiguration' function Test-1PasswordCredentials { <# .SYNOPSIS Tests if the configured 1Password CLI configuration is valid. .DESCRIPTION Attempts to SignIn to 1Password using the configured credentials .PARAMETER SignInAddress The 1Password User's Sign-In URI .PARAMETER SignInAccount The 1Password User's Sign-In email address .PARAMETER SecretKey The 1Password User's Secret Key .PARAMETER MasterPassword The 1Password User's Master Password .EXAMPLE Test-1PasswordCredentials .LINK http://darrenjrobinson.com #> [CmdletBinding()] param ( [Parameter(Mandatory = $true, ValueFromPipeline = $true)][String]$SignInAddress, [Parameter(Mandatory = $true, ValueFromPipeline = $true)][String]$SignInAccount, [Parameter(Mandatory = $true, ValueFromPipeline = $true)][SecureString]$SecretKey, [Parameter(Mandatory = $true, ValueFromPipeline = $true)][SecureString]$MasterPassword ) try { if ($psversiontable.PSEdition -eq 'Desktop') { $bMPwd = [System.Runtime.InteropServices.Marshal]::SecureStringToBSTR($MasterPassword) $1PMasterPasswordDecrypted = [System.Runtime.InteropServices.Marshal]::PtrToStringAuto($bMPwd) $bSKey = [System.Runtime.InteropServices.Marshal]::SecureStringToBSTR($SecretKey) $1PSecretKeyDecrypted = [System.Runtime.InteropServices.Marshal]::PtrToStringAuto($bSKey) } else { $1PMasterPasswordDecrypted = ConvertFrom-SecureString $MasterPassword -AsPlainText $1PSecretKeyDecrypted = ConvertFrom-SecureString $SecretKey -AsPlainText } switch ($CLIVersion) { "1" { $Global:sessionToken = write-output $1PMasterPasswordDecrypted | .\op.exe signin $SignInAddress $SignInAccount $1PSecretKeyDecrypted -r if ($sessionToken) { return (.\op.exe get account --cache --session $($sessionToken) | ConvertFrom-Json) } } "2" { # Check if account prev added try { $accountList = $null $accountList = (.\op.exe account list) if ($accountList.count -ge 1) { # sign in $Global:sessionToken = write-output $1PMasterPasswordDecrypted | .\op.exe signin --raw if ($sessionToken) { return (.\op.exe account get --session $Global:sessionToken) } } else { # add account and signin $Global:sessionToken = write-output $1PMasterPasswordDecrypted | .\op.exe account add --address $SignInAddress --email $SignInAccount --secret-key $1PSecretKeyDecrypted --signin --raw if ($sessionToken) { return (.\op.exe account get) } } } catch { return $_ } } } } Catch { return $_ } } $CommandsToExport += 'Test-1PasswordCredentials' function Invoke-1PasswordExpression { <# .SYNOPSIS Invokes a 1Password CLI command. .DESCRIPTION Cmdlet to invoke 1Password CLI commands using session token and cache .PARAMETER Expression The 1Password command to be performed .PARAMETER sessionToken The 1Password current Session Token to be used to execute the CLI command .EXAMPLE Invoke-1PasswordExpression "Get Item Twitter" .EXAMPLE Invoke-1PasswordExpression "Item Get Twitter" .LINK http://darrenjrobinson.com #> [CmdletBinding()] [alias("1pwd")] param ( [Parameter(Mandatory = $true, ValueFromPipeline = $true)][String]$Expression, [Parameter(Mandatory = $false, ValueFromPipeline = $true)][String]$sessionToken = $Global:sessionToken ) try { if (!$sessionToken) { switch ($CLIVersion) { "1" { $Global:sessionToken = write-output $1PMasterPasswordDecrypted | .\op.exe signin $SignInAddress $SignInAccount $1PSecretKeyDecrypted -r return (Invoke-Expression -command "'.\op.exe get account --cache --session $($sessionToken)'" ) | ConvertFrom-json } "2" { $Global:sessionToken = write-output $1PMasterPasswordDecrypted | op.exe account add --address $1PSignInAddress --email $1PSignInAccount --secret-key $1PSecretKeyDecrypted --signin --raw if ($sessionToken) { return .\op.exe account get } } } } else { if ($Global:1PasswordConfiguration.Vault) { # Check if the Session Token is still valid $pinfo = New-Object System.Diagnostics.ProcessStartInfo $localPath = $null $localPath = ((get-location).path) $pinfo.FileName = "$($localPath)\op.exe" # nuances for CLI versions switch ($CLIVersion) { "1" { $pinfo.Arguments = "get vault $($Global:1PasswordConfiguration.Vault) --session $($sessionToken)" } "2" { $pinfo.Arguments = "vault get $($Global:1PasswordConfiguration.Vault) --session $($sessionToken)" } } $pinfo.UseShellExecute = $false $pinfo.CreateNoWindow = $true $pinfo.RedirectStandardOutput = $true $pinfo.RedirectStandardError = $true $process = New-Object System.Diagnostics.Process $process.StartInfo = $pinfo $process.Start() | Out-Null [int]$sleepcount = 0 do { Start-Sleep -Seconds 1 $sleepcount++ Write-Verbose "Waiting for response for Session Token expiration check." } until ($sleepcount -gt 5 -or $process.HasExited) if (!$process.HasExited) { $process.Kill() Write-Verbose "Killing process validating Session Token expiration check." } $stdout, $stderr = $null $stdout = $process.StandardOutput.ReadToEnd() $stderr = $process.StandardError.ReadToEnd() if ((($stdout.Contains("[ERROR]") -and $stdout.Contains("session expired")) -or ($stdout.Contains("[ERROR]") -and $stdout.Contains("You are not currently signed in")))) { # Session expired or invalid try { # Use the Test-1PasswordCredentials cmdlet so we don't have to decode the secure strings Test-1PasswordCredentials -SignInAddress $Global:1PasswordConfiguration.SignInAddress -SignInAccount $Global:1PasswordConfiguration.SignInAccount -SecretKey $Global:1PasswordConfiguration.SecretKey -MasterPassword $Global:1PasswordConfiguration.MasterPassword | out-null } catch { Write-Error "Session Token expired and a new one couldn't be obtained." return $_ break } } else { if ((($stderr.Contains("[ERROR]") -and $stderr.Contains("session expired")) -or ($stderr.Contains("[ERROR]") -and $stderr.Contains("You are not currently signed in")))) { # Session expired or invalid try { # Use the Test-1PasswordCredentials cmdlet so we don't have to decode the secure strings Test-1PasswordCredentials -SignInAddress $Global:1PasswordConfiguration.SignInAddress -SignInAccount $Global:1PasswordConfiguration.SignInAccount -SecretKey $Global:1PasswordConfiguration.SecretKey -MasterPassword $Global:1PasswordConfiguration.MasterPassword | out-null } catch { Write-Error "Session Token expired and a new one couldn't be obtained." return $_ break } } } } } # Not everything returns JSON, sometimes just a string. Go for gold and fall back if it fails # CLI version 2 we need to get as JSON and convert to a PSObject try { switch ($CLIVersion) { "1" { Write-Debug "CLI 1: Invoking command for JSON response" return (Invoke-Expression -command ".\op $($Expression) --cache --session `'$($Global:sessionToken)`'" ) | ConvertFrom-json } "2" { Write-Debug "CLI 2: Invoking command for JSON response" return (Invoke-Expression -command ".\op $($Expression) --cache --format=json --session `'$($Global:sessionToken)`'") | ConvertFrom-json } } } catch { try { Write-Debug "Fallback to non-json response local path" return (Invoke-Expression -command ".\op $($Expression) --cache --session `'$($Global:sessionToken)`'" ) } catch { return (op.exe $($Expression) --cache --session $($Global:sessionToken)) } } } Catch { return $_ } } $CommandsToExport += 'Invoke-1PasswordExpression' if ($1PasswordConfiguration.DefaultVault) { Write-Debug "1password Module Configuration Loaded. Initiating Session. " # Use the Test-1PasswordCredentials cmdlet so we don't have to decode the secure strings and sign-in so we're ready to go Test-1PasswordCredentials -SignInAddress $Global:1PasswordConfiguration.SignInAddress -SignInAccount $Global:1PasswordConfiguration.SignInAccount -SecretKey $Global:1PasswordConfiguration.SecretKey -MasterPassword $Global:1PasswordConfiguration.MasterPassword | out-null } else { Write-Debug "NO 1password Module Configuration Loaded. Test-1PasswordCredentials needs to be executed." } # SIG # Begin signature block # MIIoKQYJKoZIhvcNAQcCoIIoGjCCKBYCAQExDzANBglghkgBZQMEAgEFADB5Bgor # BgEEAYI3AgEEoGswaTA0BgorBgEEAYI3AgEeMCYCAwEAAAQQH8w7YFlLCE63JNLG # KX7zUQIBAAIBAAIBAAIBAAIBADAxMA0GCWCGSAFlAwQCAQUABCDWg2Ny1M1CIYZR # VspxSJZA/sICpCVQ//n1cVWGjD4t86CCISwwggWNMIIEdaADAgECAhAOmxiO+dAt # 5+/bUOIIQBhaMA0GCSqGSIb3DQEBDAUAMGUxCzAJBgNVBAYTAlVTMRUwEwYDVQQK # EwxEaWdpQ2VydCBJbmMxGTAXBgNVBAsTEHd3dy5kaWdpY2VydC5jb20xJDAiBgNV # BAMTG0RpZ2lDZXJ0IEFzc3VyZWQgSUQgUm9vdCBDQTAeFw0yMjA4MDEwMDAwMDBa # Fw0zMTExMDkyMzU5NTlaMGIxCzAJBgNVBAYTAlVTMRUwEwYDVQQKEwxEaWdpQ2Vy # dCBJbmMxGTAXBgNVBAsTEHd3dy5kaWdpY2VydC5jb20xITAfBgNVBAMTGERpZ2lD # ZXJ0IFRydXN0ZWQgUm9vdCBHNDCCAiIwDQYJKoZIhvcNAQEBBQADggIPADCCAgoC # ggIBAL/mkHNo3rvkXUo8MCIwaTPswqclLskhPfKK2FnC4SmnPVirdprNrnsbhA3E # MB/zG6Q4FutWxpdtHauyefLKEdLkX9YFPFIPUh/GnhWlfr6fqVcWWVVyr2iTcMKy # unWZanMylNEQRBAu34LzB4TmdDttceItDBvuINXJIB1jKS3O7F5OyJP4IWGbNOsF # xl7sWxq868nPzaw0QF+xembud8hIqGZXV59UWI4MK7dPpzDZVu7Ke13jrclPXuU1 # 5zHL2pNe3I6PgNq2kZhAkHnDeMe2scS1ahg4AxCN2NQ3pC4FfYj1gj4QkXCr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SWgrLIDXxgMWSKf # XokLnRy+hLHy3EcD0UvZeIkH8E8eAqAEmswse94YUuiqQX3+0IxcOD3HVGxn0rOQ # xtFRfIrD2VvsU5kemA8aHo6rbocdwnIrP4QTL6lzTzWrWcvbsmuVPwCYjV1Tx4pd # vRmxN9reS8ZT9RDz+Q== # SIG # End signature block
2atCrm.psd1
2atCrm-1.0.6049
# # Module manifest for module 'PSGet_2atCrm' # # Generated by: 2AT B.V. # # Generated on: 14-Mar-18 # @{ # Script module or binary module file associated with this manifest. RootModule = '2atCrm.psm1' # Version number of this module. ModuleVersion = '1.0.6049' # Supported PSEditions # CompatiblePSEditions = @() # ID used to uniquely identify this module GUID = 'c7981676-ac8b-4c18-8901-bd8732f884cd' # Author of this module Author = '2AT B.V.' # Company or vendor of this module CompanyName = ' 2AT B.V.' # Copyright statement for this module Copyright = '(c) 2018 2AT B.V. Alle rechten voorbehouden.' # Description of the functionality provided by this module Description = 'PowerShell Module to interact with Microsoft Dynamics CRM' # Minimum version of the Windows PowerShell engine required by this module # PowerShellVersion = '' # Name of the Windows PowerShell host required by this module # PowerShellHostName = '' # Minimum version of the Windows PowerShell host required by this module # PowerShellHostVersion = '' # Minimum version of Microsoft .NET Framework required by this module. This prerequisite is valid for the PowerShell Desktop edition only. # DotNetFrameworkVersion = '' # Minimum version of the common language runtime (CLR) required by this module. This prerequisite is valid for the PowerShell Desktop edition only. # CLRVersion = '' # Processor architecture (None, X86, Amd64) required by this module # ProcessorArchitecture = '' # Modules that must be imported into the global environment prior to importing this module RequiredModules = @('2atGeneral') # Assemblies that must be loaded prior to importing this module RequiredAssemblies = '.\Microsoft.Xrm.Sdk.dll', '.\Microsoft.Crm.Sdk.Proxy.dll' # Script files (.ps1) that are run in the caller's environment prior to importing this module. # ScriptsToProcess = @() # Type files (.ps1xml) to be loaded when importing this module # TypesToProcess = @() # Format files (.ps1xml) to be loaded when importing this module # FormatsToProcess = @() # Modules to import as nested modules of the module specified in RootModule/ModuleToProcess # NestedModules = @() # Functions to export from this module, for best performance, do not use wildcards and do not delete the entry, use an empty array if there are no functions to export. FunctionsToExport = 'Close-CrmRecord', 'New-CrmListMember', 'Edit-CrmRecord', 'New-CrmRecord', 'Get-CrmRecord', 'Get-OrgServiceProxy' # Cmdlets to export from this module, for best performance, do not use wildcards and do not delete the entry, use an empty array if there are no cmdlets to export. CmdletsToExport = '*' # Variables to export from this module VariablesToExport = '*' # Aliases to export from this module, for best performance, do not use wildcards and do not delete the entry, use an empty array if there are no aliases to export. AliasesToExport = '*' # DSC resources to export from this module # DscResourcesToExport = @() # List of all modules packaged with this module # ModuleList = @() # List of all files packaged with this module FileList = '2atCrm.psm1', '2atCrm.psd1', 'Microsoft.Xrm.Sdk.dll', 'Microsoft.Crm.Sdk.Proxy.dll' # Private data to pass to the module specified in RootModule/ModuleToProcess. This may also contain a PSData hashtable with additional module metadata used by PowerShell. PrivateData = @{ PSData = @{ # Tags applied to this module. These help with module discovery in online galleries. # Tags = @() # A URL to the license for this module. # LicenseUri = '' # A URL to the main website for this project. # ProjectUri = '' # A URL to an icon representing this module. # IconUri = '' # ReleaseNotes of this module # ReleaseNotes = '' # External dependent modules of this module # ExternalModuleDependencies = '' } # End of PSData hashtable } # End of PrivateData hashtable # HelpInfo URI of this module # HelpInfoURI = '' # Default prefix for commands exported from this module. Override the default prefix using Import-Module -Prefix. # DefaultCommandPrefix = '' } # SIG # Begin signature block # MIIhkgYJKoZIhvcNAQcCoIIhgzCCIX8CAQExDzANBglghkgBZQMEAgEFADB5Bgor # BgEEAYI3AgEEoGswaTA0BgorBgEEAYI3AgEeMCYCAwEAAAQQH8w7YFlLCE63JNLG # KX7zUQIBAAIBAAIBAAIBAAIBADAxMA0GCWCGSAFlAwQCAQUABCDiu1sQAZoWWcMt # TSWWbhAsgW2Zz82iv4cMM+6pV4bt4aCCCzswggU+MIIEJqADAgECAhEAqJN8Yygl # wn+qXuDcSIPe2DANBgkqhkiG9w0BAQsFADB8MQswCQYDVQQGEwJHQjEbMBk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Ib3DQEBAQUABIICADtAghOCqxwHSUXTFieUTmbft1WoCaw79vMy # JxLYqejXF+9oFTHo35tvqT1if4e0EZjzaljLuNRAn+QvvHkRDHYYKqT44FkfiiA7 # v9+/j0bfDpL7aCHHlrg7jX1tx0dr6s4XarTRsRzdNVH/WF/3YL3fN3+RpRitbVow # L7cDYJaSy0N+al+XY3n367jn6Cnyerw5ZHBxOjzDmS1QHXBAGIu3svXGs4UhktKa # 6ybaCKz9Pgxc21JHRlFwY2zhuojLkibqR1aTl73wzMfJK3ZFWrIKgMXbKSgUdMGr # twk9FZalCg8hdYuVT99xZyzP02YvNeakkBYy7iDjTVW961urHgchL43cLTTZ3YJs # MKMmbw24JQBZDSoJaX89xtGvJlsHqBDZiX1ufaEamzn6qzIAfzO4XDiRCon9X5gj # zfycla9uX0XFbl9qwGz34dEyaNpq+yFFqknUO7ERqXY4ofZ5Q1QHF4bNN3y+zxMl # xnraihKhgR02jPJOcAz2+jdBrcxW8HCSDsOy0l+DucA+0AC1/nbwfIqMgg7IKaeq # GgvuHOaAD3gUDDi5EvoGQZzvoKuzioeBf6NX9+V45ZROVPrQ/5p4p2G/p1aEcB96 # Qnf42srlT8JaT2LSCCY6v+n57h/VPdToOdjv/UBlPYleM8scuVsL4E8Szw2Wc8q7 # +T8auDEa # SIG # End signature block
2atCrm.psm1
2atCrm-1.0.6049
#Requires -Version 4.0 -Modules 2atGeneral $PSDefaultParameterValues.Clear() Set-StrictMode -Version 2.0 Import-Module (Join-Path -Path $PSScriptRoot -ChildPath Microsoft.Xrm.Sdk.dll) Import-Module (Join-Path -Path $PSScriptRoot -ChildPath Microsoft.Crm.Sdk.Proxy.dll) Import-Module 2atGeneral Function Get-OrgServiceProxy { Param ( [Parameter(Mandatory=$true)] $OrgServiceUri, [Parameter(Mandatory=$true)] $Credentials ) Get-CallerPreference -Cmdlet $PSCmdlet -SessionState $ExecutionContext.SessionState if ($Credentials -is [PSCredential]) { $Credentials = $Credentials.GetNetworkCredential() } if ($Credentials -is [System.Net.NetworkCredential]) { $ccred = New-Object System.ServiceModel.Description.ClientCredentials $ccred.UserName.UserName = $Credentials.UserName $ccred.UserName.Password = $Credentials.Password $Credentials = $ccred } if ($Credentials -isnot [System.ServiceModel.Description.ClientCredentials]) { throw "Session credentials specified are of an unsupported type: $($Credentials.GetType().FullName), please use either a PSCredential, a NetworkCredential or a ClientCredentials" } Write-Verbose "Creating Proxy for uri: $OrgServiceUri and user: $($Credentials.UserName.UserName)" New-Object Microsoft.Xrm.Sdk.Client.OrganizationServiceProxy($OrgServiceUri, $null, $Credentials, $null) } Function Get-CrmRecord { Param ( [Parameter(Mandatory=$true)] [Microsoft.Xrm.Sdk.Client.OrganizationServiceProxy] $OrgServiceProxy, [Parameter(Mandatory=$true)] [string] $FetchXml ) Get-CallerPreference -Cmdlet $PSCmdlet -SessionState $ExecutionContext.SessionState $OrgServiceProxy.RetrieveMultiple((New-Object Microsoft.Xrm.Sdk.Query.FetchExpression($FetchXml))).Entities } Function New-CrmRecord { Param ( [Parameter(Mandatory=$true)] [Microsoft.Xrm.Sdk.Client.OrganizationServiceProxy] $OrgServiceProxy, [Parameter(Mandatory=$true)] [string] $Entity, $Attributes ) Get-CallerPreference -Cmdlet $PSCmdlet -SessionState $ExecutionContext.SessionState Write-Debug "New-CrmRecord: About to create $Entity" $e = New-Object Microsoft.Xrm.Sdk.Entity($Entity) $Attributes.Keys | %{ $e[$_]=$Attributes[$_] } $n = $OrgServiceProxy.Create($e) $c = New-Object Microsoft.Xrm.Sdk.Query.ColumnSet $Attributes.Keys | %{ $c.Columns.Add($_) } $OrgServiceProxy.Retrieve($Entity, $n, $c) } Function Edit-CrmRecord { Param ( [Parameter(Mandatory=$true)] [Microsoft.Xrm.Sdk.Client.OrganizationServiceProxy] $OrgServiceProxy, [Microsoft.Xrm.Sdk.Entity] $Record, $AttributeUpdates ) $u = New-Object Microsoft.Xrm.Sdk.Entity($Record.LogicalName) $u["$($Record.LogicalName)id"]=$Record["$($Record.LogicalName)id"] $AttributeUpdates.Keys | %{ $u[$_]=$AttributeUpdates[$_] } $OrgServiceProxy.Update($u) $c = New-Object Microsoft.Xrm.Sdk.Query.ColumnSet $Record.Attributes.Keys | %{ $c.Columns.Add($_) } $AttributeUpdates.Keys | %{ $c.Columns.Add($_) } $OrgServiceProxy.Retrieve($Record.LogicalName, $Record.Id, $c) } Function New-CrmListMember { Param ( [Parameter(Mandatory=$true)] [Microsoft.Xrm.Sdk.Client.OrganizationServiceProxy] $OrgServiceProxy, [Parameter(Mandatory=$true)] [Guid] $ListId, [Parameter(Mandatory=$true)] [Guid] $MemberId ) Get-CallerPreference -Cmdlet $PSCmdlet -SessionState $ExecutionContext.SessionState Write-Debug "New-CrmListMember: About to add member $MemberId to list $ListId" $m = New-Object Microsoft.Crm.Sdk.Messages.AddMemberListRequest $m.EntityId = $MemberId $m.ListId = $ListId [void]$OrgServiceProxy.Execute($m) } Function Close-CrmRecord { Param ( [Parameter(Mandatory=$true)] [Microsoft.Xrm.Sdk.Client.OrganizationServiceProxy] $OrgServiceProxy, [Microsoft.Xrm.Sdk.Entity] $Record ) Get-CallerPreference -Cmdlet $PSCmdlet -SessionState $ExecutionContext.SessionState Write-Debug "Close-CrmRecord: about to close $($Record.LogicalName) with id=$($Record.Id)" $r = New-Object Microsoft.Crm.Sdk.Messages.SetStateRequest $r.EntityMoniker = New-Object Microsoft.Xrm.Sdk.EntityReference($Record.LogicalName, $Record.Id) $r.State = New-Object Microsoft.Xrm.Sdk.OptionSetValue(1) # State 1: Closed $r.Status = New-Object Microsoft.Xrm.Sdk.OptionSetValue(2) # Status 2: Closed [void]$OrgServiceProxy.Execute($r) } Export-ModuleMember -Function Close-* Export-ModuleMember -Function New-* Export-ModuleMember -Function Edit-* Export-ModuleMember -Function Get-* # SIG # Begin signature block # MIIhkgYJKoZIhvcNAQcCoIIhgzCCIX8CAQExDzANBglghkgBZQMEAgEFADB5Bgor # BgEEAYI3AgEEoGswaTA0BgorBgEEAYI3AgEeMCYC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zAJBgNV # BAYTAlVTMRMwEQYDVQQIEwpOZXcgSmVyc2V5MRQwEgYDVQQHEwtKZXJzZXkgQ2l0 # eTEeMBwGA1UEChMVVGhlIFVTRVJUUlVTVCBOZXR3b3JrMS4wLAYDVQQDEyVVU0VS # VHJ1c3QgUlNBIENlcnRpZmljYXRpb24gQXV0aG9yaXR5AhAwD2+s3WaYdHypRjan # eC25MA0GCSqGSIb3DQEBAQUABIICAFzjZcnmB6sHM0rVftltjDX6aq6roQSpAmc8 # sqDztLRIoibrksqvAmISQgjHWjqFg48ToGzfA/RoNHlwE8rc/VuUnJkotL+dPEiF # y+YaT2p8OGEBXBuTHrvYBTYYCejQo6m7+geKJAgWhj6WzYuR1Aa/o0Zccun4Vedx # XW7fH+dMONTpxxusZivYKD0xsnVvFRjS/mV8N+zOHrME1+QQOSNU4BubS/ZEu4nF # wL7n5/QzgywWdKDELpKqg7+NRRNOsNOJEM+vxH+l3C1W5XG3G1dJET4tEY6xLhvO # 3AvojyzONJ54u9ORCT3peEogsS1B1lEoHNjgtWNy0dWkSkdvRfdk3igmoyiOOLqP # 6KxGtkmYNSR2Yx7zWSpEl8dt97f8/E6J9uoOU3cPDNM3hybnJkDm30oCjTRAYCYJ # nlH3ZnNNLDYm5yW1GbMKTYuI5HmEfgb4eyq3a2AvsVAXwkEz+QVRELofai0XY3Xc # oymX728ttb29Abn2lr/AhTawlxnurvY+MhiwCoN98DIvP7JgL41sT6X/rOCo2spz # 9ZnCf6Gimo5hX3agiRmnucI+sy6k3lbNAvTEQsXzFE86vWjizMkqxXgdV3A7kssY # dDfi8TZ8Snv+rjOq4nwyO/T54H6m0JXloZxqdURc13TfCIGcXcuE+mE1IfFBTHPv # TPt6ABoI # SIG # End signature block
2atCrm9.psm1
2atCrm9-1.0.440
#Requires -Version 4.0 -Modules 2atGeneral $PSDefaultParameterValues.Clear() Set-StrictMode -Version 2.0 Import-Module (Join-Path -Path $PSScriptRoot -ChildPath Microsoft.Xrm.Sdk.dll) Import-Module (Join-Path -Path $PSScriptRoot -ChildPath Microsoft.Crm.Sdk.Proxy.dll) Import-Module 2atGeneral Function Get-OrgServiceProxy { Param ( [Parameter(Mandatory=$true)] $OrgServiceUri, [Parameter(Mandatory=$true)] $Credentials ) [Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12 Get-CallerPreference -Cmdlet $PSCmdlet -SessionState $ExecutionContext.SessionState if ($Credentials -is [PSCredential]) { $Credentials = $Credentials.GetNetworkCredential() } if ($Credentials -is [System.Net.NetworkCredential]) { $ccred = New-Object System.ServiceModel.Description.ClientCredentials $ccred.UserName.UserName = $Credentials.UserName $ccred.UserName.Password = $Credentials.Password $Credentials = $ccred } if ($Credentials -isnot [System.ServiceModel.Description.ClientCredentials]) { throw "Session credentials specified are of an unsupported type: $($Credentials.GetType().FullName), please use either a PSCredential, a NetworkCredential or a ClientCredentials" } Write-Verbose "Creating Proxy for uri: $OrgServiceUri and user: $($Credentials.UserName.UserName)" New-Object Microsoft.Xrm.Sdk.Client.OrganizationServiceProxy($OrgServiceUri, $null, $Credentials, $null) } Function Get-CrmRecord { Param ( [Parameter(Mandatory=$true)] [Microsoft.Xrm.Sdk.Client.OrganizationServiceProxy] $OrgServiceProxy, [Parameter(Mandatory=$true)] [string] $FetchXml ) Get-CallerPreference -Cmdlet $PSCmdlet -SessionState $ExecutionContext.SessionState $OrgServiceProxy.RetrieveMultiple((New-Object Microsoft.Xrm.Sdk.Query.FetchExpression($FetchXml))).Entities } Function New-CrmRecord { Param ( [Parameter(Mandatory=$true)] [Microsoft.Xrm.Sdk.Client.OrganizationServiceProxy] $OrgServiceProxy, [Parameter(Mandatory=$true)] [string] $Entity, $Attributes ) Get-CallerPreference -Cmdlet $PSCmdlet -SessionState $ExecutionContext.SessionState Write-Debug "New-CrmRecord: About to create $Entity" $e = New-Object Microsoft.Xrm.Sdk.Entity($Entity) $Attributes.Keys | %{ $e[$_]=$Attributes[$_] } $n = $OrgServiceProxy.Create($e) $c = New-Object Microsoft.Xrm.Sdk.Query.ColumnSet $Attributes.Keys | %{ $c.Columns.Add($_) } $OrgServiceProxy.Retrieve($Entity, $n, $c) } Function Edit-CrmRecord { Param ( [Parameter(Mandatory=$true)] [Microsoft.Xrm.Sdk.Client.OrganizationServiceProxy] $OrgServiceProxy, [Microsoft.Xrm.Sdk.Entity] $Record, $AttributeUpdates ) $u = New-Object Microsoft.Xrm.Sdk.Entity($Record.LogicalName) $u["$($Record.LogicalName)id"]=$Record["$($Record.LogicalName)id"] $AttributeUpdates.Keys | %{ $u[$_]=$AttributeUpdates[$_] } $OrgServiceProxy.Update($u) $c = New-Object Microsoft.Xrm.Sdk.Query.ColumnSet $Record.Attributes.Keys | %{ $c.Columns.Add($_) } $AttributeUpdates.Keys | %{ $c.Columns.Add($_) } $OrgServiceProxy.Retrieve($Record.LogicalName, $Record.Id, $c) } Function New-CrmListMember { Param ( [Parameter(Mandatory=$true)] [Microsoft.Xrm.Sdk.Client.OrganizationServiceProxy] $OrgServiceProxy, [Parameter(Mandatory=$true)] [Guid] $ListId, [Parameter(Mandatory=$true)] [Guid] $MemberId ) Get-CallerPreference -Cmdlet $PSCmdlet -SessionState $ExecutionContext.SessionState Write-Debug "New-CrmListMember: About to add member $MemberId to list $ListId" $m = New-Object Microsoft.Crm.Sdk.Messages.AddMemberListRequest $m.EntityId = $MemberId $m.ListId = $ListId [void]$OrgServiceProxy.Execute($m) } Function Close-CrmRecord { Param ( [Parameter(Mandatory=$true)] [Microsoft.Xrm.Sdk.Client.OrganizationServiceProxy] $OrgServiceProxy, [Microsoft.Xrm.Sdk.Entity] $Record ) Get-CallerPreference -Cmdlet $PSCmdlet -SessionState $ExecutionContext.SessionState Write-Debug "Close-CrmRecord: about to close $($Record.LogicalName) with id=$($Record.Id)" $r = New-Object Microsoft.Crm.Sdk.Messages.SetStateRequest $r.EntityMoniker = New-Object Microsoft.Xrm.Sdk.EntityReference($Record.LogicalName, $Record.Id) $r.State = New-Object Microsoft.Xrm.Sdk.OptionSetValue(1) # State 1: Closed $r.Status = New-Object Microsoft.Xrm.Sdk.OptionSetValue(2) # Status 2: Closed [void]$OrgServiceProxy.Execute($r) } Export-ModuleMember -Function Close-* Export-ModuleMember -Function New-* Export-ModuleMember -Function Edit-* Export-ModuleMember -Function Get-* # SIG # Begin signature block # MIIWbwYJKoZIhvcNAQcCoIIWYDCCFlwCAQExDzANBglghkgBZQMEAgEFADB5Bgor # BgEEAYI3AgEEoGswaTA0BgorBgEEAYI3AgEeMCYCAwEAAAQQH8w7YFlLCE63JNLG # KX7zUQIBAAIBAAIBAAIBAAIBADAxMA0GCWCGSAFlAwQCAQUABCAk2kpqyUzbz7EQ # egSUxScPjJ6BvG85FQ3lcMj7J+UMcqCCCxswggUzMIIEG6ADAgECAhEAgNHe/U3D # BzyckFGAgIDcJDANBgkqhkiG9w0BAQsFADB9MQswCQYDVQQGEwJHQjEbMBkGA1UE # CBMSR3JlYXRlciBNYW5jaGVzdGVyMRAwDgYDVQQHEwdTYWxmb3JkMRowGAYDVQQK # ExFDT01PRE8gQ0EgTGltaXRlZDEjMCEGA1UEAxMaQ09NT0RPIFJTQSBDb2RlIFNp # Z25pbmcgQ0EwHhcNMTcwMTEzMDAwMDAwWhcNMjAwMTEzMjM1OTU5WjCBgDELMAkG # A1UEBhMCTkwxEDAOBgNVBBEMBzM1NDIgRFoxEDAOBgNVBAgMB1V0cmVjaHQxEDAO # BgNVBAcMB1V0cmVjaHQxFTATBgNVBAkMDEVuZXJnaWV3ZWcgMTERMA8GA1UECgwI # MkFUIEIuVi4xETAPBgNVBAMMCDJBVCBCLlYuMIIBIjANBgkqhkiG9w0BAQEFAAOC # AQ8AMIIBCgKCAQEAzB3KZ2CBenaD2WDwOsy0cHE6mLIeIYqWP718FuWeUZ5eejvw # 8BozajbtBWgISZ2IMsTYZ1I7KFBzHgXXkNglmyboa6++x7j2Ws+T0hmHCUZ64AFb # OkXjqYsOBCPhi3yuKIRLwc4snA3F3DCH24mBpDYymrU22+0vM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kyNTExNTcy # NVowKwYLKoZIhvcNAQkQAgwxHDAaMBgwFgQUNlJ9T6JqaPnrRZbx2Zq7LA6nbfow # LwYJKoZIhvcNAQkEMSIEIH2/5yqD+uGE3GFOHdE9WnWaoxsEylAg+81+obKL90wd # MA0GCSqGSIb3DQEBAQUABIIBAINJRPp1McSNIRYGzydyXeZ4YOot3N4hZT+yCJld # 7VltoXiZbTSlu/aQyV8LRpq7ZOPfKO8f6g4XDcXt9vFgOJ1jUD7kZvk2nrvoqgys # t7QoFbVyXoadKIxJ9joIXd0TpB5lEv54WS5BqKn0pgfa89l6V4VZUlzBjqRzg4RV # cQL4lYRwUn2IiyMKt8D/ojfzLjdzylWJTTKrSDwtNiAWDv4dHyNeFHq1CPeTSoh+ # YD6zFLP2ZuOQvHQMdN83gFqTVqKWyj/KTpv+u9nd0gWeN2ieLZq+pX4xjXwsTD2I # hea2BDMhI0gSbVIF4+jaIi+597VzqZNLSJ3DOv8SJXB+8sQ= # SIG # End signature block
2atCrm9.psd1
2atCrm9-1.0.440
# # Module manifest for module 'PSGet_2atCrm9' # # Generated by: 2AT B.V. # # Generated on: 14-Mar-18 # @{ # Script module or binary module file associated with this manifest. RootModule = '2atCrm9.psm1' # Version number of this module. ModuleVersion = '1.0.440' # Supported PSEditions # CompatiblePSEditions = @() # ID used to uniquely identify this module GUID = '3488D844-F961-4D20-9FB1-9930FC084063' # Author of this module Author = '2AT B.V.' # Company or vendor of this module CompanyName = ' 2AT B.V.' # Copyright statement for this module Copyright = '(c) 2018 2AT B.V. Alle rechten voorbehouden.' # Description of the functionality provided by this module Description = 'PowerShell Module to interact with Microsoft Dynamics CRM' # Minimum version of the Windows PowerShell engine required by this module # PowerShellVersion = '' # Name of the Windows PowerShell host required by this module # PowerShellHostName = '' # Minimum version of the Windows PowerShell host required by this module # PowerShellHostVersion = '' # Minimum version of Microsoft .NET Framework required by this module. This prerequisite is valid for the PowerShell Desktop edition only. # DotNetFrameworkVersion = '' # Minimum version of the common language runtime (CLR) required by this module. This prerequisite is valid for the PowerShell Desktop edition only. # CLRVersion = '' # Processor architecture (None, X86, Amd64) required by this module # ProcessorArchitecture = '' # Modules that must be imported into the global environment prior to importing this module RequiredModules = @('2atGeneral') # Assemblies that must be loaded prior to importing this module RequiredAssemblies = '.\Microsoft.Xrm.Sdk.dll', '.\Microsoft.Crm.Sdk.Proxy.dll' # Script files (.ps1) that are run in the caller's environment prior to importing this module. # ScriptsToProcess = @() # Type files (.ps1xml) to be loaded when importing this module # TypesToProcess = @() # Format files (.ps1xml) to be loaded when importing this module # FormatsToProcess = @() # Modules to import as nested modules of the module specified in RootModule/ModuleToProcess # NestedModules = @() # Functions to export from this module, for best performance, do not use wildcards and do not delete the entry, use an empty array if there are no functions to export. FunctionsToExport = 'Close-CrmRecord', 'New-CrmListMember', 'Edit-CrmRecord', 'New-CrmRecord', 'Get-CrmRecord', 'Get-OrgServiceProxy' # Cmdlets to export from this module, for best performance, do not use wildcards and do not delete the entry, use an empty array if there are no cmdlets to export. CmdletsToExport = '*' # Variables to export from this module VariablesToExport = '*' # Aliases to export from this module, for best performance, do not use wildcards and do not delete the entry, use an empty array if there are no aliases to export. AliasesToExport = '*' # DSC resources to export from this module # DscResourcesToExport = @() # List of all modules packaged with this module # ModuleList = @() # List of all files packaged with this module FileList = '2atCrm9.psm1', '2atCrm9.psd1', 'Microsoft.Xrm.Sdk.dll', 'Microsoft.Crm.Sdk.Proxy.dll' # Private data to pass to the module specified in RootModule/ModuleToProcess. This may also contain a PSData hashtable with additional module metadata used by PowerShell. PrivateData = @{ PSData = @{ # Tags applied to this module. These help with module discovery in online galleries. # Tags = @() # A URL to the license for this module. # LicenseUri = '' # A URL to the main website for this project. # ProjectUri = '' # A URL to an icon representing this module. # IconUri = '' # ReleaseNotes of this module # ReleaseNotes = '' # External dependent modules of this module # ExternalModuleDependencies = '' } # End of PSData hashtable } # End of PrivateData hashtable # HelpInfo URI of this module # HelpInfoURI = '' # Default prefix for commands exported from this module. Override the default prefix using Import-Module -Prefix. # DefaultCommandPrefix = '' } # SIG # Begin signature block # MIIWcAYJKoZIhvcNAQcCoIIWYTCCFl0CAQExDzANBglghkgBZQMEAgEFADB5Bgor # BgEEAYI3AgEEoGswaTA0BgorBgEEAYI3AgEeMCYCAwEAAAQQH8w7YFlLCE63JNLG # KX7zUQIBAAIBAAIBAAIBAAIBADAxMA0GCWCGSAFlAwQCAQUABCBvyzsjwWhNSbZS # S5/c+0Sj8nU7X/6QF+2C3jRX7wOm2aCCCxswggUzMIIEG6ADAgECAhEAgNHe/U3D # BzyckFGAgIDcJDANBgkqhkiG9w0BAQsFADB9MQswCQYDVQQGEwJHQjEbMBkGA1UE # CBMSR3JlYXRlciBNYW5jaGVzdGVyMRAwDgYDVQQHEwdTYWxmb3JkMRowGAYDVQQK # ExFDT01PRE8gQ0EgTGltaXRlZDEjMCEGA1UEAxMaQ09NT0RPIFJTQSBDb2RlIFNp # Z25pbmcgQ0EwHhcNMTcwMTEzMDAwMDAwWhcNMjAwMTEzMjM1OTU5WjCBgDELMAkG # A1UEBhMCTkwxEDAOBgNVBBEMBzM1NDIgRFoxEDAOBgNVBAgMB1V0cmVjaHQxEDAO # BgNVBAcMB1V0cmVjaHQxFTATBgNVBAkMDEVuZXJnaWV3ZWcgMTERMA8GA1UECgwI # MkFUIEIuVi4xETAPBgNVBAMMCDJBVCBCLlYuMIIBIjANBgkqhkiG9w0BAQEFAAOC # AQ8AMIIBCgKCAQEAzB3KZ2CBenaD2WDwOsy0cHE6mLIeIYqWP718FuWeUZ5eejvw # 8BozajbtBWgISZ2IMsTYZ1I7KFBzHgXXkNglmyboa6++x7j2Ws+T0hmHCUZ64AFb # OkXjqYsOBCPhi3yuKIRLwc4snA3F3DCH24mBpDYymrU22+0vMIlDqpzRXBNEeIhG # ss3jehu86l85fWVS54F5KGeDYQ2BT0Tc0UO6hMlcpCEVKIbthLm36q1/oSchRYjH # B4JCT1KqACRhD0hJcQmTcJZvhpgOrglUVlj1ClS5xfWgHq3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XzD45h5eJIkRTaY5/A6L1GR0 # RTANBgkqhkiG9w0BAQEFAASCAQClPzJPGSZBNQ8MntHtrlA9+gnD/WVI1vyFPmBG # 5aUsh39hQMwgYbJCfCa8Z2DnauD8TiCpBW5R6ZfIR9sCew035IIDWTbkkjHi3gOw # D2+n2oEuEfbejAb+xVC/ZUbp2HZQJcrDtmbNwfO9z/2eYjHaHaCxWo9j1hhgfLlN # ebb+7OSZxTOQU5gsZRdAYO5LdTQ+YzSHbOchB89FJB/pOFaYB4LG0Ww8t4vB1b3l # 1ZhcUZcuw0Vqad9n3NRM4KB/gtnMZcwNao+I1JwBtRhOfyMxk+hot+5SmOOMvZuk # 9pTigNuDq54jq+xcNGH+XXFaNuDTmqbiDMq7MyVuR5SlF58Y # SIG # End signature block
2atGeneral.psd1
2atGeneral-1.0.277
# # Module manifest for module 'PSGet_2atGeneral' # # Generated by: 2AT B.V. # # Generated on: 14-Mar-18 # @{ # Script module or binary module file associated with this manifest. RootModule = '2atGeneral.psm1' # Version number of this module. ModuleVersion = '1.0.277' # Supported PSEditions # CompatiblePSEditions = @() # ID used to uniquely identify this module GUID = '2a845444-4631-4177-a8f3-0e994fde5c98' # Author of this module Author = '2AT B.V.' # Company or vendor of this module CompanyName = ' 2AT B.V.' # Copyright statement for this module Copyright = '(c) 2018 2AT B.V. Alle rechten voorbehouden.' # Description of the functionality provided by this module Description = 'PowerShell Module to interact with Microsoft Dynamics CRM' # Minimum version of the Windows PowerShell engine required by this module # PowerShellVersion = '' # Name of the Windows PowerShell host required by this module # PowerShellHostName = '' # Minimum version of the Windows PowerShell host required by this module # PowerShellHostVersion = '' # Minimum version of Microsoft .NET Framework required by this module. This prerequisite is valid for the PowerShell Desktop edition only. # DotNetFrameworkVersion = '' # Minimum version of the common language runtime (CLR) required by this module. This prerequisite is valid for the PowerShell Desktop edition only. # CLRVersion = '' # Processor architecture (None, X86, Amd64) required by this module # ProcessorArchitecture = '' # Modules that must be imported into the global environment prior to importing this module # RequiredModules = @() # Assemblies that must be loaded prior to importing this module # RequiredAssemblies = @() # Script files (.ps1) that are run in the caller's environment prior to importing this module. # ScriptsToProcess = @() # Type files (.ps1xml) to be loaded when importing this module # TypesToProcess = @() # Format files (.ps1xml) to be loaded when importing this module # FormatsToProcess = @() # Modules to import as nested modules of the module specified in RootModule/ModuleToProcess # NestedModules = @() # Functions to export from this module, for best performance, do not use wildcards and do not delete the entry, use an empty array if there are no functions to export. FunctionsToExport = 'Get-CallerPreference', 'Get-StoredCredential', 'Import-WebAssembly' # Cmdlets to export from this module, for best performance, do not use wildcards and do not delete the entry, use an empty array if there are no cmdlets to export. CmdletsToExport = '*' # Variables to export from this module VariablesToExport = '*' # Aliases to export from this module, for best performance, do not use wildcards and do not delete the entry, use an empty array if there are no aliases to export. AliasesToExport = '*' # DSC resources to export from this module # DscResourcesToExport = @() # List of all modules packaged with this module # ModuleList = @() # List of all files packaged with this module FileList = '2atGeneral.psm1', '2atGeneral.psd1' # Private data to pass to the module specified in RootModule/ModuleToProcess. This may also contain a PSData hashtable with additional module metadata used by PowerShell. PrivateData = @{ PSData = @{ # Tags applied to this module. These help with module discovery in online galleries. # Tags = @() # A URL to the license for this module. # LicenseUri = '' # A URL to the main website for this project. # ProjectUri = '' # A URL to an icon representing this module. # IconUri = '' # ReleaseNotes of this module # ReleaseNotes = '' # External dependent modules of this module # ExternalModuleDependencies = '' } # End of PSData hashtable } # End of PrivateData hashtable # HelpInfo URI of this module # HelpInfoURI = '' # Default prefix for commands exported from this module. Override the default prefix using Import-Module -Prefix. # DefaultCommandPrefix = '' } # SIG # Begin signature block # MIIWbwYJKoZIhvcNAQcCoIIWYDCCFlwCAQExDzANBglghkgBZQMEAgEFADB5Bgor # BgEEAYI3AgEEoGswaTA0BgorBgEEAYI3AgEeMCYCAwEAAAQQH8w7YFlLCE63JNLG # KX7zUQIBAAIBAAIBAAIBAAIBADAxMA0GCWCGSAFlAwQCAQUABCCK2/lA4TYzs0Uu # OWRmBBVHU4UMO2X9Td+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ythy0nEQEXdqf # n1V0ld25tRsdEXs+mxjZMAFMTmVx/ONwfx6Mjinofu4zVVdqOy2Z4PTyo8oy4Stf # DUUNbomnv7VuREuJIsZMYP6S3DwVC66LAx495RYh5th1rx4= # SIG # End signature block
2atGeneral.psm1
2atGeneral-1.0.277
#requires -Version 2.0 $PSDefaultParameterValues.Clear() Set-StrictMode -Version 2.0 Function Get-CallerPreference { <# .SYNOPSIS Fetches "Preference" variable values from the caller's scope. .DESCRIPTION Script module functions do not automatically inherit their caller's variables, but they can be obtained through the $PSCmdlet variable in Advanced Functions. This function is a helper function for any script module Advanced Function; by passing in the values of $ExecutionContext.SessionState and $PSCmdlet, Get-CallerPreference will set the caller's preference variables locally. .PARAMETER Cmdlet The $PSCmdlet object from a script module Advanced Function. .PARAMETER SessionState The $ExecutionContext.SessionState object from a script module Advanced Function. This is how the Get-CallerPreference function sets variables in its callers' scope, even if that caller is in a different script module. .EXAMPLE Get-CallerPreference -Cmdlet $PSCmdlet -SessionState $ExecutionContext.SessionState Imports the default PowerShell preference variables from the caller into the local scope. .LINK about_Preference_Variables #> [CmdletBinding()] param ( [Parameter(Mandatory = $true)] [ValidateScript({ $_.GetType().FullName -eq 'System.Management.Automation.PSScriptCmdlet' })] $Cmdlet, [Parameter(Mandatory = $true)] [System.Management.Automation.SessionState] $SessionState ) @('ErrorActionPreference', 'DebugPreference', 'ConfirmPreference', 'WhatIfPreference', 'VerbosePreference', 'WarningPreference') | %{ $SessionState.PSVariable.Set($_, $Cmdlet.SessionState.PSVariable.Get($_).Value) } } Function Get-StoredCredential{ <# .SYNOPSIS TODO .OUTPUTS System.Management.Automation.PSCredential #> [CmdletBinding()] Param( [string] #Specifies what username to look for in the stored credentials. If ommitted the first credentials found in the file will be returned. $UserName, [string] [ValidateScript({Test-Path $_ -IsValid -PathType Leaf})] #Specifies in what file to store the credentials. If ommitted the credentials will be stored in a file with the same name as the calling script with .cred added $FilePath = "$($MyInvocation.PSCommandPath).cred", [switch] #Indicates that if a valid credential can not be found the user will not be prompted to enter credentials. $DoNotPromptUser, [switch] #Indicates that an existing file may be overwritten if a parse error occurs. $OverwriteFileOnError ) Get-CallerPreference -Cmdlet $PSCmdlet -SessionState $ExecutionContext.SessionState $fileError = $false $creds = $null $credStore = @{} $fileExists = Test-Path $FilePath -PathType Leaf if ($fileExists) { try { $credStore = [HashTable](Import-CliXml $FilePath) if ($UserName) { if ($credStore[$UserName]) { return New-Object PSCredential $UserName, ($credStore[$UserName] | ConvertTo-SecureString) } } else { $credStore.Keys | Select -First 1 | %{ return New-Object PSCredential $_, ($credStore[$_] | ConvertTo-SecureString) } } } catch { Write-Warning "Error retrieving credentials from existing file. $($_.Exception.Message)" $fileError=$true } } if ($DoNotPromptUser) { throw 'No valid credential was found and -DoNotPromptUser was specified' } $cred = Get-Credential $UserName $credStore[$cred.UserName] = ($cred.Password | ConvertFrom-SecureString) if ($OverwriteFileOnError -or -not $fileError) { try { $credStore | Export-CliXml $FilePath -NoClobber:$OverwriteFileOnError } catch { Write-Warning "Error writing credentials to file '$FilePath'. $($_.Exception.Message)" } } return $cred } Function Import-WebAssembly { [CmdletBinding()] Param ( $Uri, $Thumbprint ) Get-CallerPreference -Cmdlet $PSCmdlet -SessionState $ExecutionContext.SessionState if ($Uri -isnot [Uri]) { $Uri=[Uri]$Uri } $tempfile = "$Env:TEMP\$($Uri.Segments[$Uri.Segments.Count-1])" if(!(Test-Path $tempfile)) { Invoke-WebRequest -Uri $Uri -OutFile $tempfile } $sig = Get-AuthenticodeSignature $tempfile if ($sig.Status -ne 'Valid' -or $sig.SignerCertificate.Thumbprint -ne $Thumbprint) { throw "Downloaded dll $tempfile either not signed or not signed with the expected thumbprint $Thumbprint" } Add-Type -Path $tempfile -Verbose:$false Write-Verbose "Assembly $Uri loaded" } Export-ModuleMember -Function Import-* Export-ModuleMember -Function Get-* # SIG # Begin signature block # MIIWcAYJKoZIhvcNAQcCoIIWYTCCFl0CAQExDzANBglghkgBZQMEAgEFADB5Bgor # Bg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Gf3l01zWUmLdrHuflp4w8JhvmzVx7h45zfqON17FCs27iKeDp # c8MKyAjk02bkYnIbFC1x6AOZXBca1mtMp3G0Bc+FyXTprvxSKQ1mZrw1VCAvVZWQ # j1v9xVqExHGt4cre/EOoQKc1TxMlSsVm1nAu3MD8H//W4GZt1ZOP64RQFhNpQu6L # UYGxSB/lWqKn30OvOFwn8ImnwCBYgMK2BcT7HJtkKXYIPgtqRPgSMulJ6IN6dTNQ # J3rtK/vOdVnZbZrG50SLTHa7sSUqYWi1RZWp5MjuhBjF+bFe # SIG # End signature block
2atMonitoring.psm1
2atMonitoring-1.1.4824
#Requires -Version 4.0 -Modules 2atWeb,2atGeneral,2atSql $PSDefaultParameterValues.Clear() Set-StrictMode -Version 2.0 $ErrorActionPreference = 'Stop' Add-Type -Assembly System.Web Import-Module 2atGeneral Import-Module 2atWeb Import-Module 2atSql Import-Module (Join-Path -Path $PSScriptRoot -ChildPath HtmlAgilityPack.dll) [HtmlAgilityPack.HtmlNode]::ElementsFlags.Remove("form") | Out-Null Function RelToAbs { Param( [Parameter(Mandatory=$true)] [ValidateScript({(New-Object System.Uri $_)})] [string]$BaseUrl, [Parameter(Mandatory=$true)] [string]$RelativeUrl, [switch]$NoHtmlDecode ) if (! $NoHtmlDecode) { $RelativeUrl = [System.Web.HttpUtility]::HtmlDecode($RelativeUrl) } if ([System.Uri]::IsWellFormedUriString($RelativeUrl,[System.UriKind]::Absolute)) { return $RelativeUrl } if ([System.Uri]::IsWellFormedUriString($RelativeUrl,[System.UriKind]::Relative)) { $l = (New-Object System.Uri((New-Object System.Uri $BaseUrl), $RelativeUrl)).AbsoluteUri Write-Verbose "Absolute URL is $l" return $l } if ($NoHtmlDecode -and ([Uri]$RelativeUrl).IsAbsoluteUri) { Write-Warning "RelativeUrl is not correctly URL encoded '$RelativeUrl'. If this is a HTTP REDIRECT Location header, this is incorrect server behavior. Retrying with encoded URL." return ([Uri]$RelativeUrl).AbsoluteUri } throw "RelativeUrl is not a valid (absolute or relative) url: '$RelativeUrl'" } Function Step { Param( [Parameter(Mandatory=$true)] [ValidateScript({(New-Object System.Uri $_)})] [string]$Url, [Parameter(Mandatory=$true)] [PSCustomObject]$Session, [string]$Method = 'GET', [ValidateScript({ $_ -is [HashTable] -or $_ -is [System.Collections.Generic.Dictionary[string,string]] })] [object]$FormData ) if ($Session.UserAgent) { $UserAgent = $Session.UserAgent } else { $UserAgent = 'Mozilla/5.0 (compatible; MSIE 10.0; Windows NT 6.2; WOW64; Trident/6.0; 2AT Monitoring; +http://2at.nl)' } $res = Get-WebResponse -Url $Url -Method $Method -FormData $FormData -HostIPs $Session.HostIPs -CookieContainer $Session.CookieContainer -Proxy $Session.Proxy -UserAgent $UserAgent -Credentials $Session.Credentials if ($Session.History | ?{ $Url -eq $_.Url -and $Method -eq $_.Method -and $res.ResponseBody -eq $_.ResponseBody }) { $res.WebRequestStatus='LoopDetected' $res.WebRequestStatusDescription="The same URL was already visited on the same Step and received the same ResponseBody. ($Url)" } $Session.History += $res if ($res.WebRequestStatus -eq [System.Net.WebExceptionStatus]::Success) { if ($res.HTTPStatus -In (301, 302, 303, 307)) { $l = RelToAbs -BaseUrl $url -RelativeUrl $res.ResponseHeaders['Location'] -NoHtmlDecode Write-Verbose "REDIRECT ($($res.HTTPStatus)) -> $l" Step -Url $l -Session $Session return } if ($res.HTTPStatus -eq 200) { if ($res.ResponseBody.EndsWith('<noscript><p>Script is disabled. Click Submit to continue.</p><input type="submit" value="Submit" /></noscript></form><script language="javascript">window.setTimeout(''document.forms[0].submit()'', 0);</script></body></html>')) { Write-Verbose "ADFS auto POST" ProcessForm -Previous $res -Session $Session return } $u = (new-object System.Uri $res.Url).GetLeftPart([System.UriPartial]::Path) if ($Session.LoginSteps[$u]) { RunStep -Step $Session.LoginSteps[$u] -Previous $res -Session $Session return } } } } Function ProcessForm { Param( [HashTable]$FormData, [string]$FormId, [Parameter(Mandatory=$true)] [PSCustomObject]$Previous, [Parameter(Mandatory=$true)] [PSCustomObject]$Session ) $htmldoc = New-Object HtmlAgilityPack.HtmlDocument $htmldoc.LoadHtml($Previous.ResponseBody) if ($FormId) { $form = $htmldoc.DocumentNode.SelectNodes("//form[@id='$FormId']")[0] if (!$form) { throw "No form with id='$FormId' found" } } else { $forms = $htmldoc.DocumentNode.SelectNodes('//form') if (!$forms) { throw 'No forms found' } if ($forms.Count -gt 1) { Write-Warning "Found $($forms.Count) forms but no FormId was specified, selecting the first" } $form=$forms[0] } $l = RelToAbs $Previous.Url $form.Attributes['action'].Value $b = New-Object 'System.Collections.Generic.Dictionary[string,string]' $form.SelectNodes('//input') | ?{ $_.Attributes['name'] -And $_.Attributes['value'] } | %{ $b[$_.Attributes['name'].Value] = [System.Web.HttpUtility]::HtmlDecode($_.Attributes['value'].Value) } if ($FormData) { $FormData.Keys | %{ $b[$_]=$FormData[$_] } } Write-Verbose "FORM: $(($b.Keys | %{ $_ + '=' + $b[$_] } ) -join [Environment]::NewLine)" Step -Url $l -Method $form.Attributes['method'].Value -FormData $b -Session $Session } Function ProcessLink { Param( [Parameter(Mandatory=$true)] [string]$LinkText, [Parameter(Mandatory=$true)] [PSCustomObject]$Previous, [Parameter(Mandatory=$true)] [PSCustomObject]$Session, [Parameter(Mandatory=$false)] [string]$LinkType ) $htmldoc = New-Object HtmlAgilityPack.HtmlDocument $htmldoc.LoadHtml($Previous.ResponseBody) if ($LinkType -eq 'IMG') { $links = $htmldoc.DocumentNode.SelectNodes('//img[@src]') | ? { $_ -and $_.Attributes['src'].Value.Contains($LinkText) } | % { $_.Attributes['src'].Value } | select -Unique } else { $links = $htmldoc.DocumentNode.SelectNodes('//a[@href]') | ? { $_ -and $_.InnerText.Trim() -eq $LinkText } | % { $_.Attributes['href'].Value } | select -Unique } $c = ($links | measure).Count if ($c -ne 1) { Write-Warning "Found $c links matching '$LinkText', expected exactly one." $Previous.WebRequestStatus='LinkFailed' $Previous.WebRequestStatusDescription="Found $c links matching '$LinkText', expected exactly one." return } $l = RelToAbs $Previous.Url $links Write-Verbose "LINK: $l" Step -url $l -Session $Session } Function ProcessScript { Param( [Parameter(Mandatory=$true)] [string]$ScriptId, [Parameter(Mandatory=$true)] [string]$ScriptRegEx, [Parameter(Mandatory=$true)] [PSCustomObject]$Previous, [Parameter(Mandatory=$true)] [PSCustomObject]$Session ) $htmldoc = New-Object HtmlAgilityPack.HtmlDocument $htmldoc.LoadHtml($Previous.ResponseBody) $s = $htmldoc.DocumentNode.SelectNodes('//script') | ?{ $_ -and $_.InnerText.Trim() -match [Regex]::Escape($ScriptId) } if (!$s) { throw "No script block matching '$ScriptId' found (using literal match)" } if ($s -is [HtmlAgilityPack.HtmlNodeCollection]) { Write-Warning 'Multiple matching script blocks found, using the first' $s = $s[0] } if (!($s.InnerText.Trim() -match $ScriptRegEx)) { throw "No url could be found: Script block doesn't match '$ScriptRegEx'" } if ($Matches['link']) { $l = RelToAbs $Previous.Url $Matches['link'] } else { if ($Matches.Count -eq 1) { Write-Warning 'No match groups found, using full match as link to follow' $l = RelToAbs $Previous.Url $Matches[0] } else { if ($Matches.Count -gt 2) { Write-Warning 'Found multiple match groups, using first (create a named group ''link'' to specify witch group to use)' } $l = RelToAbs $Previous.Url $Matches[1] } } Step -url $l -Session $Session } Function ProcessSOAP { param( [Parameter(Mandatory=$true)] [string]$Url, [HashTable]$RequestData, [Parameter(Mandatory=$false)] [PSCustomObject]$Previous, [Parameter(Mandatory=$true)] [PSCustomObject]$Session ) $Cred = New-Object System.Management.Automation.PSCredential ("$($session.Credentials.Domain)\$($session.Credentials.username)", (ConvertTo-SecureString $session.Credentials.Password -AsPlainText -Force) ) $FormData = @{ 'SOAP' = $RequestData['Request']; 'SOAPAction' = $RequestData['SOAPAction'] } $res = Get-WebResponse -Url $url -Method 'POST' -Credentials $cred -FormData $FormData -Proxy $Session.Proxy -UserAgent $Session.UserAgent $session.History += $res } Function ProcessAPI { param( [Parameter(Mandatory=$true)] [string]$Url, [HashTable]$RequestData, [Parameter(Mandatory=$false)] [PSCustomObject]$Previous, [Parameter(Mandatory=$true)] [PSCustomObject]$Session ) $Cred = New-Object System.Management.Automation.PSCredential ("$($session.Credentials.Domain)\$($session.Credentials.username)", (ConvertTo-SecureString $session.Credentials.Password -AsPlainText -Force) ) $res = Get-WebResponse -Url $url -Method 'GET' -Credentials $cred -FormData @{'API'=$RequestData} -Proxy $Session.Proxy -UserAgent $Session.UserAgent $session.History += $res } Function UpdateSession { Param( [Parameter(Mandatory=$true)] [HashTable]$Step, [Parameter(Mandatory=$true)] [PSCustomObject]$Session, [PSCustomObject]$TMGInfo, [Switch]$IsNewSession ) Write-Debug "Updating $(if($IsNewSession) {'NEW'})session" if (!$IsNewSession -and ($Step['SqlConnection'] -or $Step['Name'])) { throw 'Specifying a SqlConnection or Name is only supported for new sessions' } if ($Step['Proxy']) { $Session.Proxy = New-Object System.Net.WebProxy $Step.Proxy } if ($Step['LoginSteps']) { $Session.LoginSteps = $Step.LoginSteps } if ($Step['Servers']) { if($TMGInfo){ SetSessionCookiesTmg -Session $Session -TMGInfo $TMGInfo -Servers $Step.Servers } if($Step['CookieName'] -and $Step['TargetServer'] -and $Step['CookieUrls']) { SetSessionCookie -Session $Session -TargetServer $Step.TargetServer -CookieName $Step.CookieName -Urls $Step.CookieUrls} } if ($Step['TargetServer']) { $Session.TargetServer = $Step.TargetServer } if ($Step['NextLogMinutes']) { $Session.NextLogMinutes = $Step.NextLogMinutes } if ($Step['HostIPs']) { $Session.HostIPs = $Step.HostIPs } if ($Step['Credentials']) { if ($Step.Credentials -is [PSCredential]) { $Session.Credentials = $Step.Credentials.GetNetworkCredential() } elseif ($Step.Credentials -is [System.Net.ICredentials]) { $Session.Credentials = $Step.Credentials } else { throw "Session credentials specified are of an unsupported type: $($Step.Credentials.GetType().FullName), please use either a PSCredential or a NetworkCredential" } } if ($Step['UserAgent']) { $Session.UserAgent = $Step.UserAgent } else { $Session.UserAgent = 'Mozilla/5.0 (compatible; MSIE 10.0; Windows NT 6.2; WOW64; Trident/6.0; 2AT Monitoring; +http://2at.nl)' } if ($IsNewSession) { $Session } } Function NewSession { Param( [Parameter(Mandatory=$true)] [HashTable]$Step, [PSCustomObject]$TMGInfo ) $Session = @{ Id=-1 Name=$Step['Name'] HostIPs=@{} CookieContainer = New-Object System.Net.CookieContainer Proxy=$null SqlConnection=$Step['SqlConnection'] WSConnection=$Step['WSConnection'] ReportingConnection = $Step['ReportingConnection'] LoginSteps=@{} Credentials=$null History=@() RequestNumber=1 TargetServer=$null NextLogMinutes=10 UserAgent=$null } if ($Session.SqlConnection) { Write-Verbose "NEWSESSION: Connecting to SQL '$($Step.SqlConnection)'" Set-SqlData -ConnectionString $Session.SqlConnection -CommandText 'ops.LogJob' -Parameters @{ Job='HTTPMonitor'; Title='Job started' } $MonitorSession = Get-SqlData -ConnectionString $Session.SqlConnection -CommandText 'ops.SaveMonitorSession' -Parameters @{ Name=$Session.Name; Servers=($Step['Servers'] -Join ' / ') } $Session.Id = $MonitorSession.SessionId } if (!$Step['Servers']) { Write-Verbose 'NEWSESSION: New session created without cookies' } UpdateSession -Step $Step -Session ([PSCustomObject]$Session) -TMGInfo $TMGInfo -IsNewSession } Function SetSessionCookie{ Param( [Parameter(Mandatory=$true)] [PSCustomObject]$Session, [Parameter(Mandatory=$true)] [string]$TargetServer, [Parameter(Mandatory=$true)] [string]$CookieName, [Parameter(Mandatory=$true)] [string[]]$Urls ) foreach($url in $Urls) { $cookie = New-Object System.Net.Cookie $CookieName, $TargetServer $cookie.HttpOnly = $true $Session.CookieContainer.Add($url, $cookie) Write-Verbose "Added cookie to session: $cookieName=$TargetServer $url" } } Function SetSessionCookiesTmg { Param( [Parameter(Mandatory=$true)] [PSCustomObject]$Session, [Parameter(Mandatory=$true)] [PSCustomObject]$TMGInfo, [Parameter(Mandatory=$true)] [string[]]$Servers ) $TMGInfo.CookieIndex | %{ $cookieName = $_.Cookie $Url = New-Object System.Uri $_.Url $rule = $TMGInfo.Rules[$cookieName.SubString(7)] if (! $rule) { Write-Warning "Unable to add cookie to session. No matching rule found for cookie '$cookieName' ($Url). Possible cause is an outdated TMGRuleGUIDs.xml file." return } foreach($server in $Servers) { $entry = $rule.ServerFarm | ?{ $_.HostName -Match $server } if ($entry) { break } } if (! $entry) { Write-Warning "Unable to add cookie to session. No matching server found for rule '$($rule.Name)' ($Url)" return } $cookie = New-Object System.Net.Cookie $cookieName, $entry.GUID, '/', $Url.Host $cookie.HttpOnly = $true $Session.CookieContainer.Add($Url, $cookie) Write-Verbose "Added cookie to session: $cookieName=$($entry.GUID) ($Url)" } } Function GetServer { Param ( [Parameter(Mandatory=$true)] [PSCustomObject]$WebResponse ) if ($WebResponse.ResponseHeaders['X-WFE']) { $WebResponse.ResponseHeaders['X-WFE'] } else { $WebResponse.ResponseHeaders['X-Powered-by-server'] } } Function ValidateResponse { Param( [Parameter(Mandatory=$true)] [PSCustomObject]$Response, [Parameter(Mandatory=$true)] [PSCustomObject]$Validate ) #TODO: Transform $Response.WebRequestStatusDescription to hashtable (or xml) if ($Response.WebRequestStatus -ne [System.Net.WebExceptionStatus]::Success) { Write-Verbose "Skipped validation because request already marked as failed ($($Response.WebRequestStatus)" return } if ($Validate['Url']) { if ($Response.Url.TrimEnd('/') -ne $Validate.Url.TrimEnd('/')) { $Response.WebRequestStatus='UrlValidationFailed' $Response.WebRequestStatusDescription="Url validation failed, found '$($Response.Url)', expected '$($Validate.Url)'" Write-Warning $Response.WebRequestStatusDescription return } else { Write-Verbose 'Url validation succeeded' } } if ($Validate['ContentMatch']) { if (! ($Response.ResponseBody -match $Validate.ContentMatch)) { $Response.WebRequestStatus='ContentValidationFailed' $Response.WebRequestStatusDescription="Content validation failed, page '$($Response.Url)' does not match '$($Validate.ContentMatch)'" Write-Warning $Response.WebRequestStatusDescription return } else { Write-Verbose "Content validation succeeded '$($Validate.ContentMatch)'" } } if ($Validate['Time']) { if (! ([int]$Response.TimeToFirstByte.TotalMilliseconds -le [int]$Validate.Time)) { $Response.WebRequestStatus='TimeValidationFailed' $Response.WebRequestStatusDescription="Time exceeded, page took $([int]$Response.TimeToFirstByte.TotalMilliseconds)ms, maximum was set at $([int]$Validate.Time)ms ($($Response.Url))" Write-Warning $Response.WebRequestStatusDescription return } else { Write-Verbose "Time validation succeeded ($([int]$Response.TimeToFirstByte.TotalMilliseconds)ms < $([int]$Validate.Time)ms)" } } if ($Validate['TargetServer']) { $ResponseServer = GetServer -WebResponse $Response if ($Validate.TargetServer -ne $ResponseServer) { $Response.WebRequestStatus='TargetServerValidationFailed' $Response.WebRequestStatusDescription="Response received from other than TargetServer. TargetServer = '$($Validate.TargetServer)'. ResponseServer = '$ResponseServer'." Write-Warning $Response.WebRequestStatusDescription return } else { Write-Verbose "TargetServer validation succeeded. TargetServer = ResponseServer = '$ResponseServer'." } } if ($Validate['ResponseHeader']) { if ( $response.ResponseHeaders[$Validate.ResponseHeader] -ne $Validate.HeaderMatch) { $Response.WebRequestStatus='ResponseHeaderValidationFailed' $Response.WebRequestStatusDescription="Response header is different than expected value ($($response.ResponseHeaders[$Validate.ResponseHeader]), expected $($Validate.HeaderMatch))" Write-Warning $Response.WebRequestStatusDescription return } else { Write-Verbose "Response header validation succeeded. Header has expected value ($($Validate.HeaderMatch))" } } } Function PostEntityUpdate { Param ( [Parameter(Mandatory=$true)] [PSCustomObject]$Session, [string]$Monitor ) $lr = $Session.History[$Session.History.Length-1] $FormData = @{ name = "$Monitor-$($Session.TargetServer)"; webRequestStatus = $lr.WebRequestStatus; nextLogTime = $lr.DateTime.AddMinutes($Session.NextLogMinutes).ToUniversalTime().ToString('u'); logTime = $lr.DateTime.ToUniversalTime().ToString('u'); } if ($lr.WebRequestStatus -ne 'Success') { $information = @{ WebRequestStatusDescription = $lr.WebRequestStatusDescription } $FormData.information = New-Object PSObject -Property $information | ConvertTo-Xml -NoTypeInformation -as String } try { Write-Verbose "Posting to $($Session.WSConnection)" Invoke-RestMethod -Uri $Session.WSConnection -Method 'POST' -Body $FormData -TimeoutSec 5 } catch { #TODO This should become Write-Error once the new monitoring becomes permanent Write-Warning "Entity endpoint unavailable $($_.Exception.Message)" } } Function PostEntityReportData { Param ( [Parameter(Mandatory=$true)] [ValidateScript({(New-Object System.Uri $_)})] [string]$entityReportingUrl, [Parameter(Mandatory=$true)] [string]$entityName, [Parameter(Mandatory=$false)] [datetime]$logTime, [Parameter(Mandatory=$true)] [string]$propertyName, [Parameter(Mandatory=$true)] [int]$propertyValue ) $FormData = @{ Name = $entityName; LogTime = $logTime.ToUniversalTime().ToString('u'); PropertyName = $propertyName; PropertyValue = $propertyValue; } try { Write-Verbose "Posting reportingData to $entityReportingUrl" Invoke-RestMethod -Uri $entityReportingUrl -Method 'POST' -Body $FormData -TimeoutSec 5 } catch { #TODO This may need to become Write-Error once the new monitoring becomes permanent Write-Warning "Entity reporting endpoint unavailable $($_.Exception.Message)" } } Function LogSteps { Param( [Parameter(Mandatory=$true)] [PSCustomObject]$Session, [int] $StepNumber, [string]$Monitor, [switch] $PassThru ) $i=1 foreach($WebResponse in $Session.History) { $u = New-Object System.Uri $WebResponse.Url $hostname = "$($u.Host)" if ($u.Port -ne 80) { $hostname+=":$($u.Port)"} if ($u.Query.Length -ne 0) { $query=$u.Query.Substring(1) } else { $query='' } $p = @{ LogDateTime=$WebResponse.DateTime Host=$hostname UriStem=$u.AbsolutePath UriQuery=$query Method=$WebResponse.Method HTTPStatus=[int]$WebResponse.HTTPStatus TimeTaken=[int]$WebResponse.TimeToFirstByte.TotalMilliseconds RequestStatus=[string]$WebResponse.WebRequestStatus RequestStatusDescription=$WebResponse.WebRequestStatusDescription Url=$WebResponse.Url SessionId=$Session.Id Monitor=$Monitor TargetServer=$Session.TargetServer NextLogMinutes=$Session.NextLogMinutes StepNumber=$StepNumber RequestNumber=$Session.RequestNumber++ IsStepResult=($i -eq $Session.History.Count) } if ($WebResponse.FormData) { $p.FormData=(($WebResponse.FormData.Keys | %{ $_ + '=' + $WebResponse.FormData[$_] } ) -join [Environment]::NewLine) } if ($WebResponse.ResponseHeaders) { $p.Server=GetServer -WebResponse $WebResponse $p.XSharePointHealthScore=$WebResponse.ResponseHeaders['X-SharePointHealthScore'] $p.SPIisLatency=$WebResponse.ResponseHeaders['SPIisLatency'] $p.SPRequestDuration=$WebResponse.ResponseHeaders['SPRequestDuration'] $p.RequestGuid=$WebResponse.ResponseHeaders['request-id'] $p.RawResponse=Get-WebResponseString -WebResponse $WebResponse } Write-Debug "Writing data" if ($Session.SqlConnection) { Write-Verbose "Writing data to the database" Set-SqlData -ConnectionString $Session.SqlConnection -CommandText 'ops.SaveMonitorResult' -Parameters $p } if (!$Session.SqlConnection -And !$Session.WSConnection) { if ($p.HTTPStatus) { Write-Host "$(Get-Date) $($p.Server) ($($p.XSharePointHealthScore)) $($p.HTTPStatus) $($p.Method) $($u.GetLeftPart([System.UriPartial]::Path))" } else { Write-Host "$(Get-Date) $($p.RequestStatus) $($u.GetLeftPart([System.UriPartial]::Path))" } } if ($PassThru) { $WebResponse } $i++ } if ($Session.WSConnection) { Write-Verbose "Posting data to the entity endpoint" PostEntityUpdate -Session $Session -Monitor $Monitor } if ($Session.ReportingConnection) { Write-Verbose "Posting data to the reporting endpoint" $lastIndex = $Session.History.Length-1 if($Session.History[$lastIndex].WebRequestStatus -eq "Success"){ $logTime = $Session.History[$lastIndex].DateTime $propertyName="Response time" $propertyValue=[int]$Session.History[$lastIndex].TimeToFirstByte.TotalMilliseconds PostEntityReportData -entityReportingUrl $Session.ReportingConnection -entityName "$Monitor-$($Session.TargetServer)" -logTime $LogTime -propertyName $propertyName -propertyValue $propertyValue } } } Function RunStep { Param( [Parameter(Mandatory=$true)] [HashTable]$Step, [PSCustomObject]$Previous, [Parameter(Mandatory=$true)] [PSCustomObject]$Session ) switch ($Step.Action) { 'Url' { Write-Debug "URL: $($Step.Url)" Step -Url $Step.Url -Session $Session } 'Link' { Write-Debug "LINK: $($Step.LinkText)" ProcessLink -LinkText $Step.LinkText -Previous $Previous -Session $Session -LinkType $Step['LinkType'] } 'Form' { Write-Debug "FORM" ProcessForm -FormId $Step['FormId'] -FormData $Step['FormData'] -Previous $Previous -Session $Session } 'Script' { Write-Debug 'SCRIPT' ProcessScript -ScriptId $Step['ScriptId'] -ScriptRegEx $Step['ScriptRegEx'] -Previous $Previous -Session $Session } 'SOAP' { Write-Debug 'SOAP' ProcessSOAP -RequestData $Step['RequestData'] -Url $Step['Url'] -Previous $Previous -Session $Session } 'API' { Write-Debug 'API' ProcessAPI -RequestData $Step['RequestData'] -Url $Step['Url'] -Previous $Previous -Session $Session } default { throw "Unrecognized step $($CurrentStep.Action)" } } if ($Step['Validate']) { ValidateResponse -Response $Session.History[$Session.History.Length-1] -Validate $Step.Validate } } Function Invoke-Monitoring { Param( [Parameter(Mandatory=$true)] [System.Array]$Steps, [PSCustomObject]$TMGInfo ) Get-CallerPreference -Cmdlet $PSCmdlet -SessionState $ExecutionContext.SessionState $i=0 foreach($CurrentStep in $Steps) { switch ($CurrentStep.Action) { 'NewSession' { Write-Progress -Activity 'Initializing session' -PercentComplete (100*$i/$Steps.Count) Write-Debug 'NEWSESSION' $Session = NewSession -Step $CurrentStep -TMGInfo $TMGInfo $Previous = $null } 'UpdateSession' { Write-Progress -Activity 'Updating session' -PercentComplete (100*$i/$Steps.Count) Write-Debug 'UPDATESESSION' UpdateSession -Step $CurrentStep -TMGInfo $TMGInfo -Session $Session } default { Write-Progress -Activity 'Retrieving webpage' -CurrentOperation $CurrentStep.Url -PercentComplete (100*$i/$Steps.Count) RunStep -Step $CurrentStep -Previous $Previous -Session $Session LogSteps -Session $Session -StepNumber ($i+1) -Monitor $CurrentStep['Monitor'] -PassThru $Previous = $Session.History | Select-Object -Last 1 $Session.History=@() } } $i++ } } Export-ModuleMember -Function Invoke-* # SIG # Begin signature block # MIIhcgYJKoZIhvcNAQcCoIIhYzCCIV8CAQExDzANBglghkgBZQMEAgEFADB5Bgor # BgEEAYI3AgEEoGswaTA0BgorBgEEAYI3AgEeMCYCAwEAAAQQH8w7YFlLCE63JNLG # KX7zUQIBAAIBAAIBA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V0d29y # azEuMCwGA1UEAxMlVVNFUlRydXN0IFJTQSBDZXJ0aWZpY2F0aW9uIEF1dGhvcml0 # eQIQMA9vrN1mmHR8qUY2p3gtuTANBgkqhkiG9w0BAQEFAASCAgCfn45PfzGdHTrx # sv+q0UIU0ug6XLI8qsbW+cCMols5bKP7r3T4KqxK8XMjYeGN2LmvprwcOQWtsGuj # aXTk31WDncm1XTg3Mro9JRrvOYIfG7Qv0KIarqiq3VRXS7UyN+VgjVzUg04daO6W # lG/yG+/sI5pIY5sKuq2kUyOx1pDV3Ce2XdYWdkIgoyVyBpoI4OE6eUPFC5cy+pTJ # G1913nh9ut29uy1tOqGQOHMPqIuw7VWURajIvVr87u+bQ6JdEs7tB+v9qgyAB3Xv # A7G2txXU5OxivCs7DonMbvotB0R7XzsVNJJ+ke3HY5roH7rdHtCJ7baz5TRkzvoH # Z/y0pAwpj8L7trp/yJY9mm2+bGVABrgGlz+LTUzZloG/UNVhijs+y/rWcW5ezs50 # Md/YNLuEfuV4CF28NoGBto2B6oZkG2fJiWbwIVvKVdFraWCWxDPPKuFyGmRfMAiA # V3ukFTYru8bz3vEjlSCds686wyeBwFd+Hx6sMtdbO4mnBXmJC+RbfldSZ5zgO4VZ # HKMIr6Qd7zyxpCQ5OY8Y2HhTKDx+wkS5hxwoYCeVfCEzlM11+fn0Z/veGm1APUlw # hHp9WQztzRakN2wiX2EyuBpHO59bP7M8vmih0L1V0lzm/ybfO/TGCqkQ9+eBY/Nl # 0assPpfct1lgCYQYEIY55YZHeFtWdQ== # SIG # End signature block
2atMonitoring.psd1
2atMonitoring-1.1.4824
# # Module manifest for module 'PSGet_2atMonitoring' # # Generated by: 2AT B.V. # # Generated on: 23-May-19 # @{ # Script module or binary module file associated with this manifest. RootModule = '2atMonitoring.psm1' # Version number of this module. ModuleVersion = '1.1.4824' # Supported PSEditions # CompatiblePSEditions = @() # ID used to uniquely identify this module GUID = '62203ce7-f0df-4788-8ab3-d5c6bedb139b' # Author of this module Author = '2AT B.V.' # Company or vendor of this module CompanyName = ' 2AT B.V.' # Copyright statement for this module Copyright = '(c) 2018 2AT B.V. Alle rechten voorbehouden.' # Description of the functionality provided by this module Description = 'PowerShell Module to interact with Microsoft Dynamics CRM' # Minimum version of the Windows PowerShell engine required by this module # PowerShellVersion = '' # Name of the Windows PowerShell host required by this module # PowerShellHostName = '' # Minimum version of the Windows PowerShell host required by this module # PowerShellHostVersion = '' # Minimum version of Microsoft .NET Framework required by this module. This prerequisite is valid for the PowerShell Desktop edition only. # DotNetFrameworkVersion = '' # Minimum version of the common language runtime (CLR) required by this module. This prerequisite is valid for the PowerShell Desktop edition only. # CLRVersion = '' # Processor architecture (None, X86, Amd64) required by this module # ProcessorArchitecture = '' # Modules that must be imported into the global environment prior to importing this module RequiredModules = @('2atWeb', '2atGeneral', '2atSql') # Assemblies that must be loaded prior to importing this module RequiredAssemblies = '.\HtmlAgilityPack.dll' # Script files (.ps1) that are run in the caller's environment prior to importing this module. # ScriptsToProcess = @() # Type files (.ps1xml) to be loaded when importing this module # TypesToProcess = @() # Format files (.ps1xml) to be loaded when importing this module # FormatsToProcess = @() # Modules to import as nested modules of the module specified in RootModule/ModuleToProcess # NestedModules = @() # Functions to export from this module, for best performance, do not use wildcards and do not delete the entry, use an empty array if there are no functions to export. FunctionsToExport = 'Invoke-Monitoring' # Cmdlets to export from this module, for best performance, do not use wildcards and do not delete the entry, use an empty array if there are no cmdlets to export. CmdletsToExport = '*' # Variables to export from this module VariablesToExport = '*' # Aliases to export from this module, for best performance, do not use wildcards and do not delete the entry, use an empty array if there are no aliases to export. AliasesToExport = '*' # DSC resources to export from this module # DscResourcesToExport = @() # List of all modules packaged with this module # ModuleList = @() # List of all files packaged with this module FileList = '2atMonitoring.psm1', '2atMonitoring.psd1', 'HtmlAgilityPack.dll' # Private data to pass to the module specified in RootModule/ModuleToProcess. This may also contain a PSData hashtable with additional module metadata used by PowerShell. PrivateData = @{ PSData = @{ # Tags applied to this module. These help with module discovery in online galleries. # Tags = @() # A URL to the license for this module. # LicenseUri = '' # A URL to the main website for this project. # ProjectUri = '' # A URL to an icon representing this module. # IconUri = '' # ReleaseNotes of this module # ReleaseNotes = '' # External dependent modules of this module # ExternalModuleDependencies = '' } # End of PSData hashtable } # End of PrivateData hashtable # HelpInfo URI of this module # HelpInfoURI = '' # Default prefix for commands exported from this module. Override the default prefix using Import-Module -Prefix. # DefaultCommandPrefix = '' } # SIG # Begin signature block # MIIhcgYJKoZIhvcNAQcCoIIhYzCCIV8CAQExDzANBglghkgBZQMEAgEFADB5Bgor # BgEEAYI3AgEEoGswaTA0BgorBgEEAYI3AgEeMCYCAwEAAAQQH8w7YFlLCE63JNLG # KX7zUQIBAAIBAAIBAAIBAAIBADAxMA0GCWCGSAFlAwQCAQUABCAIdO7HONrmCd6B # B4dvY1cbEr4OvsHhtLWj2SQTyZHgFaCCCxswggUzMIIEG6ADAgECAhEAgNHe/U3D # BzyckFGAgIDcJDANBgkqhkiG9w0BAQsFADB9MQswCQYDVQQGEwJHQjEbMBkGA1UE # CBMSR3JlYXRlciBNYW5jaGVzdGVyMRAwDgYDVQQHEwdTYWxmb3JkMRowGAYDVQQK # ExFDT01PRE8gQ0EgTGltaXRlZDEjMCEGA1UEAxMaQ09NT0RPIFJTQSBDb2RlIFNp # Z25pbmcgQ0EwHhcNMTcwMTEzMDAwMDAwWhcNMjAwMTEzMjM1OTU5WjCBgDELMAkG # A1UEBhMCTkwxEDAOBgNVBBEMBzM1NDIgRFoxEDAOBgNVBAgMB1V0cmVjaHQxEDAO # BgNVBAcMB1V0cmVjaHQxFTATBgNVBAkMDEVuZXJnaWV3ZWcgMTERMA8GA1UECgwI # MkFUIEIuVi4xETAPBgNVBAMMCDJBVCBCLlYuMIIBIjANBgkqhkiG9w0BAQEFAAOC # AQ8AMIIBCgKCAQEAzB3KZ2CBenaD2WDwOsy0cHE6mLIeIYqWP718FuWeUZ5eejvw # 8BozajbtBWgISZ2IMsTYZ1I7KFBzHgXXkNglmyboa6++x7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GyRnY4fL4lRJmxA1tjK2Iz30P7A # YjcGHUxd19NUezFE7DM+EhHMsHowivEvy9NAyEM0VPQx4ryZw1Cj3w5H0GMcduQQ # JgxtLYkh1V70y89TJjWL/Qi5yzUiEg== # SIG # End signature block
2atSql.psd1
2atSql-1.0.278
# # Module manifest for module 'PSGet_2atSql' # # Generated by: 2AT B.V. # # Generated on: 14-Mar-18 # @{ # Script module or binary module file associated with this manifest. RootModule = '2atSql.psm1' # Version number of this module. ModuleVersion = '1.0.278' # Supported PSEditions # CompatiblePSEditions = @() # ID used to uniquely identify this module GUID = '9a310499-7a22-44ac-b415-0be4dbadb459' # Author of this module Author = '2AT B.V.' # Company or vendor of this module CompanyName = ' 2AT B.V.' # Copyright statement for this module Copyright = '(c) 2018 2AT B.V. Alle rechten voorbehouden.' # Description of the functionality provided by this module Description = 'PowerShell Module to interact with Microsoft Dynamics CRM' # Minimum version of the Windows PowerShell engine required by this module # PowerShellVersion = '' # Name of the Windows PowerShell host required by this module # PowerShellHostName = '' # Minimum version of the Windows PowerShell host required by this module # PowerShellHostVersion = '' # Minimum version of Microsoft .NET Framework required by this module. This prerequisite is valid for the PowerShell Desktop edition only. # DotNetFrameworkVersion = '' # Minimum version of the common language runtime (CLR) required by this module. This prerequisite is valid for the PowerShell Desktop edition only. # CLRVersion = '' # Processor architecture (None, X86, Amd64) required by this module # ProcessorArchitecture = '' # Modules that must be imported into the global environment prior to importing this module RequiredModules = @('2atGeneral') # Assemblies that must be loaded prior to importing this module # RequiredAssemblies = @() # Script files (.ps1) that are run in the caller's environment prior to importing this module. # ScriptsToProcess = @() # Type files (.ps1xml) to be loaded when importing this module # TypesToProcess = @() # Format files (.ps1xml) to be loaded when importing this module # FormatsToProcess = @() # Modules to import as nested modules of the module specified in RootModule/ModuleToProcess # NestedModules = @() # Functions to export from this module, for best performance, do not use wildcards and do not delete the entry, use an empty array if there are no functions to export. FunctionsToExport = 'Get-SqlData', 'Set-SqlData' # Cmdlets to export from this module, for best performance, do not use wildcards and do not delete the entry, use an empty array if there are no cmdlets to export. CmdletsToExport = '*' # Variables to export from this module VariablesToExport = '*' # Aliases to export from this module, for best performance, do not use wildcards and do not delete the entry, use an empty array if there are no aliases to export. AliasesToExport = '*' # DSC resources to export from this module # DscResourcesToExport = @() # List of all modules packaged with this module # ModuleList = @() # List of all files packaged with this module FileList = '2atSql.psm1', '2atSql.psd1' # Private data to pass to the module specified in RootModule/ModuleToProcess. This may also contain a PSData hashtable with additional module metadata used by PowerShell. PrivateData = @{ PSData = @{ # Tags applied to this module. These help with module discovery in online galleries. # Tags = @() # A URL to the license for this module. # LicenseUri = '' # A URL to the main website for this project. # ProjectUri = '' # A URL to an icon representing this module. # IconUri = '' # ReleaseNotes of this module # ReleaseNotes = '' # External dependent modules of this module # ExternalModuleDependencies = '' } # End of PSData hashtable } # End of PrivateData hashtable # HelpInfo URI of this module # HelpInfoURI = '' # Default prefix for commands exported from this module. Override the default prefix using Import-Module -Prefix. # DefaultCommandPrefix = '' } # SIG # Begin signature block # MIIWcAYJKoZIhvcNAQcCoIIWYTCCFl0CAQExDzANBglghkgBZQMEAgEFADB5Bgor # BgEEAYI3AgEEoGswaTA0BgorBgEEAYI3AgEeMCYCAwEAAAQQH8w7YFlLCE63JNLG # KX7zUQIBAAIBAAIBAAIBAAIBADAxMA0GCWCGSAFlAwQCAQUABCBaL3KhawBrzol1 # zvowKDOeU2A+NdEqQ4np4xElt0qzqaCCCxswggUzMIIEG6ADAgECAhEAgNHe/U3D # BzyckFGAgIDcJDANBgkqhkiG9w0BAQsFADB9MQswCQYDVQQGEwJHQjEbMBkGA1UE # CBMSR3JlYXRlciBNYW5jaGVzdGVyMRAwDgYDVQQHEwdTYWxmb3JkMRowGAYDVQQK # ExFDT01PRE8gQ0EgTGltaXRlZDEjMCEGA1UEAxMaQ09NT0RPIFJTQSBDb2RlIFNp # Z25pbmcgQ0EwHhcNMTcwMTEzMDAwMDAwWhcNMjAwMTEzMjM1OTU5WjCBgDELMAkG # A1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Bn25OE2jGHA5Lnn+Ppz1pWyGjgUkmUXDGCAnEwggJtAgEBMIGqMIGV # MQswCQYDVQQGEwJVUzELMAkGA1UECBMCVVQxFzAVBgNVBAcTDlNhbHQgTGFrZSBD # aXR5MR4wHAYDVQQKExVUaGUgVVNFUlRSVVNUIE5ldHdvcmsxITAfBgNVBAsTGGh0 # dHA6Ly93d3cudXNlcnRydXN0LmNvbTEdMBsGA1UEAxMUVVROLVVTRVJGaXJzdC1P # YmplY3QCEE6wh4/MJDU2stjJ9785VXcwDQYJYIZIAWUDBAIBBQCggZgwGgYJKoZI # hvcNAQkDMQ0GCyqGSIb3DQEJEAEEMBwGCSqGSIb3DQEJBTEPFw0xODAzMjIwODA1 # NDVaMCsGCyqGSIb3DQEJEAIMMRwwGjAYMBYEFDZSfU+iamj560WW8dmauywOp236 # MC8GCSqGSIb3DQEJBDEiBCAj6mbv8W9uEw94v1sQa6AKmGuILv/eNbWVIlgiY42a # ljANBgkqhkiG9w0BAQEFAASCAQCw85Hbep4TwV7olbwxPg84wqwHXZmP/b9ka1m7 # O+Fd26tBXrs6sgJn9fremB9s0P7kYgF45GrlQl1sI1CcNQKs58kJk+Z46JYxdaDr # F4mm/pOBFTIo8jj7ZR/XrVTptva+QSSSg9JzpUVcHBkCzvG+MZ880t82D9dsRJY8 # OoMIRzVjJdSOq4oHgwh8GG5hcROxVzgGGRLBMGywFEws+8iukuFbLxR44LckrNqH # XzRnCHfTJVzaJFFx3aWqJevumbm2g1baQDoLOriYL40AWFdH/E+a3NZoGfz6m83q # CLJbNh/JhUNnN35vN1PmvYONY81q2Gs77o13DlSB7UOiXYWM # SIG # End signature block
2atSql.psm1
2atSql-1.0.278
#Requires -Version 4.0 -Modules 2atGeneral $PSDefaultParameterValues.Clear() Set-StrictMode -Version 2.0 Import-Module 2atGeneral Function execSql { [CmdletBinding()] param ( [string] $ConnectionString, [Parameter(ValueFromPipeline)] [System.Data.SqlClient.SqlConnection] $SqlConnection, [Parameter(Position=0)] [ValidateNotNullorEmpty()] [string] $CommandText, [bool] $CommandIsQuery, [Parameter(Position=1)] [hashtable] $Parameters=@{}, [scriptblock] $Script, [int] $Timeout ) Write-Verbose "Executing SQL: $CommandText" if ($SqlConnection -and ![string]::IsNullOrEmpty($ConnectionString)) { Write-Warning "Both SqlConnection and ConnectionString set. Using SqlConnection and ignoring ConnectionString value." } if (!$SqlConnection) { if ([string]::IsNullOrEmpty($ConnectionString)) { throw "Either supply a SqlConnection object or a ConnectionString" } $SqlConnection = New-Object System.Data.SqlClient.SqlConnection($ConnectionString) $disposeConnection = $true } $SqlCmd = $SqlConnection.CreateCommand() $SqlCmd.CommandText = $CommandText if ($Timeout -ne -1) { $SqlCmd.CommandTimeout = $Timeout } if (!$CommandIsQuery) { $SqlCmd.CommandType = [System.Data.CommandType]'StoredProcedure' } foreach($p in $parameters.Keys) { if ($parameters[$p] -ne $null) { $v = $Parameters[$p] } else { $v = [DBNull]::Value } Write-Verbose " $p = $v" [void]$SqlCmd.Parameters.AddWithValue("@$p",$v) } if ($SqlConnection.State -eq [System.Data.ConnectionState]::Closed) { $SqlConnection.Open() } $script.Invoke($SqlCmd) $SqlCmd.Dispose() if ($disposeConnection) { $SqlConnection.Dispose() } } Function Get-SqlData { [CmdletBinding()] param ( [string] $ConnectionString, [Parameter(ValueFromPipeline)] [System.Data.SqlClient.SqlConnection] $SqlConnection, [Parameter(Position=0)] [ValidateNotNullorEmpty()] [string] $CommandText, [switch] $CommandIsQuery, [Parameter(Position=1)] [hashtable] $Parameters=@{}, [int] $Timeout=-1 ) Get-CallerPreference -Cmdlet $PSCmdlet -SessionState $ExecutionContext.SessionState execSql -ConnectionString $ConnectionString -SqlConnection $SqlConnection -CommandText $CommandText -CommandIsQuery $CommandIsQuery -Timeout $Timeout -Parameters $Parameters -Script { param ( [System.Data.SqlClient.SqlCommand]$SqlCmd ) $dt=New-Object system.Data.DataTable [void](New-Object system.Data.SqlClient.SqlDataAdapter($SqlCmd)).fill($dt) $dt } } Function Set-SqlData { [CmdletBinding()] param ( [string] $ConnectionString, [Parameter(ValueFromPipeline)] [System.Data.SqlClient.SqlConnection] $SqlConnection, [Parameter(Position=0)] [ValidateNotNullorEmpty()] [string] $CommandText, [switch] $CommandIsQuery, [Parameter(Position=1)] [hashtable] $Parameters=@{}, [int] $Timeout=-1 ) Get-CallerPreference -Cmdlet $PSCmdlet -SessionState $ExecutionContext.SessionState execSql -ConnectionString $ConnectionString -SqlConnection $SqlConnection -CommandText $CommandText -CommandIsQuery $CommandIsQuery -Timeout $Timeout -Parameters $Parameters -Script { param ( [System.Data.SqlClient.SqlCommand]$SqlCmd ) [void]$SqlCmd.ExecuteNonQuery() } } Export-ModuleMember -Function Get-* Export-ModuleMember -Function Set-* # SIG # Begin signature block # MIIWcAYJKoZIhvcNAQcCoIIWYTCCFl0CAQExDzANBglghkgBZQMEAgEFADB5Bgor # BgEEAYI3AgEEoGswaTA0BgorBgEEAYI3AgEeMCYCAwEAAAQQH8w7YFlLCE63JNLG # KX7zUQIBAAIBAAIBAAIBAAIBADAxMA0GCWCGSAFlAwQCAQUABCAQAHPEHsFva1X7 # Cf/iUGoZN0F5e3uk25XNDyWtlZEqOKCCCxswggUzMIIEG6ADAgECAhEAgNHe/U3D # BzyckFGAgIDcJDANBgkqhkiG9w0BAQsFADB9MQswCQYDVQQGEwJHQjEbMBkGA1UE # CBMSR3JlYXRlciBNYW5jaGVzdGVyMRAwDgYDVQQHEwdTYWxmb3JkMRowGAYDVQQK # ExFDT01PRE8gQ0EgTGltaXRlZDEjMCEGA1UEAxMaQ09NT0RPIFJTQSBDb2RlIFNp # Z25pbmcgQ0EwHhcNMTcwMTEzMDAwMDAwWhcNMjAwMTEzMjM1OTU5WjCBgDELMAkG # A1UEBhMCTkwxEDAOBgNVBBEMBzM1NDIgRFoxEDAOBgNVBAgMB1V0cmVjaHQxEDAO # BgNVBAcMB1V0cmVjaHQxFTATBgNVBAkMDEVuZXJnaWV3ZWcgMTERMA8GA1UECgwI # MkFUI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# aXR5MR4wHAYDVQQKExVUaGUgVVNFUlRSVVNUIE5ldHdvcmsxITAfBgNVBAsTGGh0 # dHA6Ly93d3cudXNlcnRydXN0LmNvbTEdMBsGA1UEAxMUVVROLVVTRVJGaXJzdC1P # YmplY3QCEE6wh4/MJDU2stjJ9785VXcwDQYJYIZIAWUDBAIBBQCggZgwGgYJKoZI # hvcNAQkDMQ0GCyqGSIb3DQEJEAEEMBwGCSqGSIb3DQEJBTEPFw0xODAzMjIwODA1 # NDhaMCsGCyqGSIb3DQEJEAIMMRwwGjAYMBYEFDZSfU+iamj560WW8dmauywOp236 # MC8GCSqGSIb3DQEJBDEiBCDdjbfaLRCS+ulDJSl06yxyZ6iC23R/lJuYlR9d1b6p # pzANBgkqhkiG9w0BAQEFAASCAQBJQZnQU8JK3fz+kg1zSf/5ejSvJwCf6rqYx+Im # 7O6dDm6fGpyFO56HvRl4/dAZXLjoiYfV69XB6lRaQcrVQpA7DHavVse+Nb2EG6dw # TuPk1+D1W4fz6Gjwl0Ze4hBIQAZsVEytFs4yuVkCjPRaNSBUKPcpeGyiL+9A5o3/ # N6rW80NvCJ+dK0R3FCTRxCR9/A9K1/HTrKMnZiNmfiVBW10X3gzMkFkQMF/85ozy # uUnr/722l8L0tfgoRbINFh6Z6Pa8PRslRpnfUESqDPS++A1HHYpgyiG6bmPqruKG # TPdq+3iLZtkaxqoPxEp4RyW5ixTXwpoUr9h8Rt1nwQpXmYpZ # SIG # End signature block
2atWeb.psd1
2atWeb-1.0.4825
# # Module manifest for module 'PSGet_2atWeb' # # Generated by: 2AT B.V. # # Generated on: 14-Mar-18 # @{ # Script module or binary module file associated with this manifest. RootModule = '2atWeb.psm1' # Version number of this module. ModuleVersion = '1.0.4825' # Supported PSEditions # CompatiblePSEditions = @() # ID used to uniquely identify this module GUID = 'f1ecc09e-8985-4f89-81c3-4f1b6deb9f36' # Author of this module Author = '2AT B.V.' # Company or vendor of this module CompanyName = ' 2AT B.V.' # Copyright statement for this module Copyright = '(c) 2018 2AT B.V. Alle rechten voorbehouden.' # Description of the functionality provided by this module Description = 'PowerShell Module to interact with Microsoft Dynamics CRM' # Minimum version of the Windows PowerShell engine required by this module # PowerShellVersion = '' # Name of the Windows PowerShell host required by this module # PowerShellHostName = '' # Minimum version of the Windows PowerShell host required by this module # PowerShellHostVersion = '' # Minimum version of Microsoft .NET Framework required by this module. This prerequisite is valid for the PowerShell Desktop edition only. # DotNetFrameworkVersion = '' # Minimum version of the common language runtime (CLR) required by this module. This prerequisite is valid for the PowerShell Desktop edition only. # CLRVersion = '' # Processor architecture (None, X86, Amd64) required by this module # ProcessorArchitecture = '' # Modules that must be imported into the global environment prior to importing this module RequiredModules = @('2atGeneral') # Assemblies that must be loaded prior to importing this module # RequiredAssemblies = @() # Script files (.ps1) that are run in the caller's environment prior to importing this module. # ScriptsToProcess = @() # Type files (.ps1xml) to be loaded when importing this module # TypesToProcess = @() # Format files (.ps1xml) to be loaded when importing this module # FormatsToProcess = @() # Modules to import as nested modules of the module specified in RootModule/ModuleToProcess # NestedModules = @() # Functions to export from this module, for best performance, do not use wildcards and do not delete the entry, use an empty array if there are no functions to export. FunctionsToExport = 'Get-WebResponseString', 'Get-WebResponse' # Cmdlets to export from this module, for best performance, do not use wildcards and do not delete the entry, use an empty array if there are no cmdlets to export. CmdletsToExport = '*' # Variables to export from this module VariablesToExport = '*' # Aliases to export from this module, for best performance, do not use wildcards and do not delete the entry, use an empty array if there are no aliases to export. AliasesToExport = '*' # DSC resources to export from this module # DscResourcesToExport = @() # List of all modules packaged with this module # ModuleList = @() # List of all files packaged with this module FileList = '2atWeb.psm1', '2atWeb.psd1' # Private data to pass to the module specified in RootModule/ModuleToProcess. This may also contain a PSData hashtable with additional module metadata used by PowerShell. PrivateData = @{ PSData = @{ # Tags applied to this module. These help with module discovery in online galleries. # Tags = @() # A URL to the license for this module. # LicenseUri = '' # A URL to the main website for this project. # ProjectUri = '' # A URL to an icon representing this module. # IconUri = '' # ReleaseNotes of this module # ReleaseNotes = '' # External dependent modules of this module # ExternalModuleDependencies = '' } # End of PSData hashtable } # End of PrivateData hashtable # HelpInfo URI of this module # HelpInfoURI = '' # Default prefix for commands exported from this module. Override the default prefix using Import-Module -Prefix. # DefaultCommandPrefix = '' } # SIG # Begin signature block # MIIhcwYJKoZIhvcNAQcCoIIhZDCCIWACAQExDzANBglghkgBZQMEAgEFADB5Bgor # BgEEAYI3AgEEoGswaTA0BgorBgEEAYI3AgEeMCYCAwEAAAQQH8w7YFlLCE63JNLG # KX7zUQIBAAIBAAIBAAIBAAIBADAxMA0GCWCGSAFlAwQCAQUABCBRikh1AuJnC3L9 # PpT/vgzjPH5MYD1iY9alTJUlM41I4aCCCxswggUzMIIEG6ADAgECAhEAgNHe/U3D # BzyckFGAgIDcJDANBgkqhkiG9w0BAQsFADB9MQswCQYDVQQGEwJHQjEbMBkGA1UE # CBMSR3JlYXRlciBNYW5jaGVzdGVyMRAwDgYDVQQHEwdTYWxmb3JkMRowGAYDVQQK # ExFDT01PRE8gQ0EgTGltaXRlZDEjMCEGA1UEAxMaQ09NT0RPIFJTQSBDb2RlIFNp # Z25pbmcgQ0EwHhcNMTcwMTEzMDAwMDAwWhcNMjAwMTEzMjM1OTU5WjCBgDELMAkG # A1UEBhMCTkwxEDAOBgNVBBEMBzM1NDIgRFoxEDAOBgNVBAgMB1V0cmVjaHQxEDAO # BgNVBAcMB1V0cmVjaHQxFTATBgNVBAkMDEVuZXJnaWV3ZWcgMTERMA8GA1UECgwI # MkFUIEIuVi4xETAPBgNVBAMMCDJBVCBCLlYuMIIBIjANBgkqhkiG9w0BAQEFAAOC # AQ8AMIIBCgKCAQEAzB3KZ2CBenaD2WDwOsy0cHE6mLIeIYqWP718FuWeUZ5eejvw # 8BozajbtBWgISZ2IMsTYZ1I7KFBzHgXXkNglmyboa6++x7j2Ws+T0hmHCUZ64AFb # OkXjqYsOBCPhi3yuKIRLwc4snA3F3DCH24mBpDYymrU22+0vMIlDqpzRXBNEeIhG # ss3jehu86l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Bopex+ZL45VryEW # 98F9i8HGypFu5hS73+5vS0Aj4w+a49Y= # SIG # End signature block
2atWeb.psm1
2atWeb-1.0.4825
#Requires -Version 4.0 -Modules 2atGeneral $PSDefaultParameterValues.Clear() Set-StrictMode -Version 2.0 $ErrorActionPreference = 'Stop' Add-Type -Assembly System.Net.Http Import-Module 2atGeneral Function HashTableToDictionary { Param( [Parameter(Mandatory=$true)] [HashTable]$HashTable ) $Dictionary = New-Object 'System.Collections.Generic.Dictionary[string,string]' $HashTable.Keys | %{ $Dictionary.Add($_, $HashTable[$_]) } $Dictionary } Function ReadCookiesFromResponseHeader{ Param( [Parameter(Mandatory=$true)] $CookieHeaders, [string]$Url ) $CookieCollection = New-Object System.Net.CookieCollection foreach($c in $CookieHeaders) { $Cookie = New-Object System.Net.Cookie $cookieName = $c.Substring(0,$c.Indexof('=')) if (-Not ($CookieName -match "[,; ]")) { $Cookie.Name = $c.Substring(0,$c.Indexof('=')) } else { return $CookieCollection } $cValue = ($c.Substring($c.Indexof('=')+1, $c.Length - $c.Indexof('=')-1)).Split(';') Foreach ($var in $cValue) { if ($var.Contains('path=')) { $path = ($var.Split('='))[1].Trim() if ($path.LastIndexOf('/') -eq $path.Length -1 ) { $path = $path.Substring(0, $path.Length-1) } $Cookie.Path = $path } if ($var.Contains('HttpOnly')) { $Cookie.HttpOnly = $true } if ($var.Contains('expires')) { if ($var.Split('=')[1] -as [DateTime]) { $Cookie.Expires = Get-Date $var.Split('=')[1] } } } $Cookie.Value = $cValue[0] $Cookie.Domain = ([System.Uri]$url).DnsSafeHost $CookieCollection.Add($Cookie) Write-Verbose "ReadCookiesFromResponseHeader: Added cookie to collection: $($cookie.Name)" } $CookieCollection } Function Get-WebResponseString { Param( [Parameter(Mandatory=$true)] [PSCustomObject]$WebResponse ) Get-CallerPreference -Cmdlet $PSCmdlet -SessionState $ExecutionContext.SessionState $headers = ($WebResponse.ResponseHeaders | %{ "$($_): $($WebResponse.ResponseHeaders[$_])" }) -join [Environment]::NewLine "HTTP/$($WebResponse.ProtocolVersion) $([int]$WebResponse.HTTPStatus) $($WebResponse.HTTPStatusDescription) $headers $($WebResponse.ResponseBody)" } Function Get-WebResponse { Param( [Parameter(Mandatory=$true)] [ValidateScript({(New-Object System.Uri $_)})] [string]$Url, [hashtable]$HostIPs = @{}, [System.Net.CookieContainer]$CookieContainer, [string]$Method = 'GET', [object]$FormData, [System.Net.WebProxy]$Proxy, [System.Net.ICredentials]$Credentials, [string]$UserAgent ) Get-CallerPreference -Cmdlet $PSCmdlet -SessionState $ExecutionContext.SessionState if ($FormData -And -Not ($FormData -is [HashTable] -or $FormData -is [System.Collections.Generic.Dictionary[string,string]])) { throw 'FormData must be either a HashTable or a Dictionary[string,string]' } $o = [ordered]@{ DateTime=Get-Date Url=$Url Method=$Method HostHeader=$null FormData=$null WebRequestStatus=[System.Net.WebExceptionStatus]::Success WebRequestStatusDescription=$null ProtocolVersion=$null HTTPStatus=$null HTTPStatusDescription=$null ResponseHeaders=$null ResponseBody=$null } if ($HostIPs.Keys | ?{ $url -match "(https?://)($_)(/.*)" }) { $req = [System.Net.WebRequest]::Create("$($Matches[1])$($HostIPs[$Matches[2]])$($Matches[3])") $o.HostHeader = $req.Host = $Matches[2] } else { $req = [System.Net.WebRequest]::Create($Url) } $req.AllowAutoRedirect = $false if (!$UserAgent) { $req.UserAgent = 'Mozilla/5.0 (compatible; MSIE 10.0; Windows NT 6.2; WOW64; Trident/6.0; 2AT Monitoring; +http://2at.nl)' } else { $req.UserAgent = $UserAgent } $req.CookieContainer = $CookieContainer $req.Method = $Method $req.Proxy = $Proxy $req.Credentials = $Credentials $c = $null if ($FormData) { if ($FormData['SOAP'] -OR $FormData['API']) { if ($FormData['SOAP']) { $o.FormData = $FormData $c = New-Object System.Net.Http.StringContent $FormData['SOAP'].InnerXml $req.ContentType = 'text/xml' $req.Headers['SOAPAction'] = $FormData['SOAPAction'] } if ($FormData['API']) { $o.FormData = $FormData $FormData['API'].Keys | % { $req.Headers[$_] = $FormData['API'][$_] } $req.Accept = 'application/json' } } else { if ($FormData -is [HashTable]) { $FormData = HashTableToDictionary $FormData } $o.FormData = $FormData $c = New-Object System.Net.Http.FormUrlEncodedContent $FormData $req.ContentType = $c.Headers.ContentType.MediaType } } $reader = $null $resp = $null try { $o.TotalTime = Measure-Command { $o.TimeToFirstByte = Measure-Command { try { if ($c) { Wait-Job $c.CopyToAsync($req.GetRequestStream()) } $resp = $req.GetResponse() } catch [System.Net.WebException] { $e = $_.Exception Write-Warning "$Method $Url : $($e.Status) - $($e.Message)" $resp = $e.Response $o.WebRequestStatus = $e.Status $o.WebRequestStatusDescription = $e.Message } } if ($resp) { $encoding = if ($resp.CharacterSet) { try { [System.Text.Encoding]::GetEncoding($resp.CharacterSet) } catch { Write-Warning "$Method $Url : Invalid encoding $($resp.CharacterSet)" } } if ($encoding) { $reader = New-Object System.IO.StreamReader $resp.GetResponseStream(), $encoding } else { $reader = New-Object System.IO.StreamReader $resp.GetResponseStream() } $o.ResponseBody = $reader.ReadToEnd() } } if ($resp) { $o.ProtocolVersion = $resp.ProtocolVersion $o.ResponseHeaders = $resp.Headers $o.HTTPStatus = $resp.StatusCode $o.HTTPStatusDescription = $resp.StatusDescription } # With some ASP.net applications the response cookies are not added to the cookiecontainer if ($resp.Cookies.Count -eq 0 -AND $resp.Headers['Set-Cookie'] -ne $null) { $Cookies = ReadCookiesFromResponseHeader -CookieHeaders $resp.Headers.GetValues('Set-Cookie') -Url $Url ForEach ($cookie in $Cookies) { $uri = [System.Uri] $url $CookieContainer.Add("$($uri.scheme)://$($cookie.Domain)$($cookie.Path)", $cookie) } } [PSCustomObject]$o } finally { if ($reader) { $reader.Dispose() } if ($resp) { $resp.Dispose() } } } Export-ModuleMember -Function Get-* # SIG # Begin signature block # MIIhcgYJKoZIhvcNAQcCoIIhYzCCIV8CAQExDzANBglghkgBZQMEAgEFADB5Bgor # BgEEAYI3AgEEoGswaTA0BgorBgEEAYI3AgEeMCYCAwEAAAQQH8w7Y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HjAcBgNVBAoTFVRoZSBVU0VSVFJVU1QgTmV0d29y # azEuMCwGA1UEAxMlVVNFUlRydXN0IFJTQSBDZXJ0aWZpY2F0aW9uIEF1dGhvcml0 # eQIQMA9vrN1mmHR8qUY2p3gtuTANBgkqhkiG9w0BAQEFAASCAgCcEr7hkfnts8+Z # FXmtwnPjViKyZh+S7+1ebGs5jJ5WH5e/hHktbXIB/GINei5nq8Y84HOwBHI8Qbh/ # 7V7qw8ebF39IOIWkB6IiHIbBJpjo1fXBUzOpu1XA9Ap+ut7psbXHF+khfNrwP1Du # 2rOXdWL2gWqnlfO6J5pXJL6R712MspUTeoQZMFM86VD9go5vgbAVCqvrFzJhd7ht # v1eYVHdvtx2eebdpv1K0U41uYi9BoZP9G1hDoqto/gycvqhYF8brGm5rTNU1TkeF # 07Ug3amnQo1vIkxR0iaohH5xmc+wE5y3rSEVc8IcmE4AlnG3BHzOKnEjeXmEaWjE # VtrePQqGDe2WWbqhcoVacDMbEKhiOcy/QO+YptAPLxNRjgTjgARC+jhRspd4QtfM # U2jGHkChMjki56YfYsLM4lxbxDDKSJtc5PtmBjs0B7b2wH/R7ryHEKFE30t5s5Yc # +nGeIrHgiUZGKbYzHR3GVmRySnEKUQyd61mPWqQ9XZH7DtzV8GweiFrGJtZ6+33E # JCJfguCu1PapHJ7aeE3pI+GoR0x2Glz4V0hfKA00AYhGRU0B7TTR4crJTJ2vMGli # /dRTZUUTovYprUs1Czy+nehjvTpAjGAwwGmWO3NA47IU1BpzPhROPwhqSD/IGr4J # sFjDFyEOwLVxkwbiJukOpw0dF3ejCA== # SIG # End signature block
Watch-EOLMigrationStatus.ps1
365Admin-1.0.2.1
function Watch-EOLMigrationStatus { <# .SYNOPSIS Connects to Exchange Online and grabs the status of any pending migrations. .DESCRIPTION Connects to Exchange Online and grabs the status of any pending migrations. .EXAMPLE Watch-EOLMigrationStatus -SleepingMinutes 5 Connects to EOL, reports back pending transfers, then sleeps 5 minutes. #> [CmdletBinding()] param ( [Parameter(Mandatory=$false, Position=0)] [System.Int32] $SleepingMinutes = 5 ) if ((Get-ExchangeOnlineConnectionState) -eq 'Connected') {} ELSE {Connect-ExchangeOnline} while (1) { $MSGs = Get-MessageTrace -Status Pending; if ($MSGs.count -gt 10) { Write-Host 10 messages pending. Consider a reboot Write-Host '' $MSGs $n = 0 while ($n -lt 10) { Start-Sleep -Seconds 3 $n++ } } Write-Host "Acceptable count of Pending Messages. PENDING: $(($MSGs).count). Sleeping for 5 minutes. $(Get-Date -displayhint datetime)" Start-Sleep -Seconds ($SleepingMinutes*60) } }
Confirm-ExchangeOnlineConnection.ps1
365Admin-1.0.2.1
function Confirm-ExchangeOnlineConnection { <# .SYNOPSIS Confirms there is an active connection to Exchange Online. Connects if prompted. .DESCRIPTION Confirms there is an active connection to Exchange Online. Connects if prompted. .EXAMPLE Confirm-ExchangeOnlineConnection -ConnectIfDisconnected Confirms connection. If disconnected, we connect. .EXAMPLE Confirm-ExchangeOnlineConnection Only confirms connection. #> [CmdletBinding()] param ( [Parameter(Mandatory=$false, Position=0)] [Switch] $ConnectIfDisconnected ) #Confirm we are connected to EOL. If not, connect. $ConnectionState = (Get-PSSession | ? {$_.ConfigurationName -eq "Microsoft.Exchange" -and $_.State -eq "Opened" -and $_.ComputerName -eq "outlook.office365.com"}).count if ($ConnectionState -eq 0) { #return "Disconnected" Write-Output 'Not connected to Exchange Online.' if ($ConnectIfDisconnected) { Write-Output 'Connecting...' Connect-ExchangeOnline -Verbose #Import-PSSession (Get-PSSession | ? {$_.ComputerName -like "*outlook*" -and $_.State -eq 'Opened'}) #return $session } } Else {return 'Already Connected'} }
Connect-ExchangeComplianceOnline.ps1
365Admin-1.0.2.1
Function Connect-ExchangeComplianceOnline { [CmdletBinding()] param ( [Parameter(Mandatory = $False)] [System.Management.Automation.PsCredential]$Credential = $Host.UI.PromptForCredential('Enter Global Admin Credential', 'Enter the username and password of an Exchange Online Global Administrator account.', '', 'userCreds'), [Parameter(Mandatory = $False)] [System.Uri]$Uri = 'https://ps.compliance.protection.outlook.com/powershell-liveid/' ) $Session = New-PSSession -ConfigurationName Microsoft.Exchange -ConnectionUri $Uri -Credential $Credential -Authentication Basic -AllowRedirection Import-PSSession -Session $session -AllowClobber Return $session }
Get-ExchangeOnlineConnectionState.ps1
365Admin-1.0.2.1
Function Get-ExchangeOnlineConnectionState { $ConnectionState = (Get-PSSession | ? {$_.ConfigurationName -eq 'Microsoft.Exchange' -and $_.State -eq 'Opened' -and $_.ComputerName -eq 'ps.outlook.com'}).count if ($ConnectionState -eq 0) { return 'Disconnected' } if ($ConnectionState -eq 1) { return 'Connected' } }
Connect-SPOL.ps1
365Admin-1.0.2.1
function Connect-SPOL { <# .SYNOPSIS Connects to SharePoint Online .DESCRIPTION Connects to SharePoint Online REF: https://technet.microsoft.com/library/fp161372%28v=office.15%29.aspx?f=255&MSPPError=-2147217396 REF: https://www.microsoft.com/en-us/download/confirmation.aspx?id=35588 .EXAMPLE Connect-SPOL -adminUPN myaccount@myorg.co -orgName myco1 #> [CmdletBinding()] param ( [Parameter(Mandatory=$true, Position=0)] [System.String] $adminUPN = "", [Parameter(Mandatory=$true, Position=1)] [System.String] $orgName = "" ) $userCredential = Get-Credential -UserName $adminUPN -Message "Type the password." Connect-SPOService -Url https://$orgName-admin.sharepoint.com -Credential $userCredential }
Get-DailyEmailCounts.ps1
365Admin-1.0.2.1
function Get-DailyEmailCounts { <# .SYNOPSIS Gathers a simple report of number/basic info of emails received by a certain Exchange Online address. .DESCRIPTION Connects to Exchange Online and gathers daily email counts for the last day ("Number of emails sent TO this email box from Midnight Yesterday to Midnight this morning") and sends an email report .EXAMPLE Get-DailyEmailCounts -AddressToQuery example@company.com -username admin@company.com -password 'Pa$$w0rd!' -SMTPServer webmail.company.com -email_from me@company.com -email_to you@company.com Sends a report for number of messages received, who from, and subject, for example@company.com and emails you@company.com a report .EXAMPLE Get-DailyEmailCounts -AddressToQuery example@company.com,example2@company.com,example3@company.com -username admin@company.com -password Pa$$w0rd! -SMTPServer webmail.company.com -email_from me@company.com -email_to you@company.com -DaysToQuery 3 Sends a report for number of messages received, who from, and subject, for the last 3 days, for example@company.com, example2@company.com, and example3@company.com and emails you@company.com a report .EXAMPLE Get-DailyEmailCounts -AddressToQuery example@company.com -username admin@company.com -password 'Pa$$w0rd!' -SMTPServer webmail.company.com -email_from me@company.com -email_to you@company.com -Uri https://customURI.microsoft.com Sends a report for number of messages received, who from, and subject, for example@company.com and emails you@company.com a report. Utilizes the custom URI switch. #> [CmdletBinding()] param ( [Parameter(Mandatory=$True, Position=0)] [String[]] $AddressToQuery, [Parameter(Mandatory=$True, Position=1, HelpMessage='Enter in an Administrator account that is able to query Exchange Online.')] [System.String] $username, [Parameter(Mandatory=$True, Position=2, HelpMessage='Enter the password for the Exchange Online Administrator Account')] [Object] $password, [Parameter(Mandatory=$false, Position=3, HelpMessage='Optionally specify the URI used to connect to Exchange Online. Default: https://outlook.office365.com/powershell-liveid/')] [System.Uri] $Uri = 'https://outlook.office365.com/powershell-liveid/', [Parameter(Mandatory=$True, Position=4, HelpMessage='Specify the SMTP Server address to use to send the email report')] [System.String] $SMTPServer, [Parameter(Mandatory=$True, Position=5, HelpMessage='Specify the sender address to use to send the email report')] [System.String] $email_from, [Parameter(Mandatory=$True, Position=6, HelpMessage='Specify the recipient address(es) to use to send the email report')] [System.String] $email_to, [Parameter(Mandatory=$false, Position=7, HelpMessage='Specify the Email subject address to use to send the email report')] [System.String] $email_subject = 'Daily Email Counts', [Parameter(Mandatory=$false, Position=8, HelpMessage='Number of historical Days to Query')] $DaysToQuery = 1 ) $spwd = ConvertTo-SecureString -AsPlainText $password -Force $Credential = New-Object System.Management.Automation.PSCredential $username,$spwd $session = New-PSSession -ConfigurationName Microsoft.Exchange -ConnectionUri $Uri -Credential $Credential -Authentication Basic -AllowRedirection #-Verbose Import-PSSession -Session $session -AllowClobber #-Verbose $body = " <strong>Script Runtime: $(Get-Date -DisplayHint DateTime)</strong><br/> <strong>Emails from: </strong>$(((Get-Date -Hour 0 -Minute 0 -Second 0).AddDays(-$DaysToQuery)))<br> <strong>Emails to: </strong>$(((Get-Date -Hour 0 -Minute 0 -Second 0)))<br/><p/> <table style=`"width: 100%;`" border=`"1`"> <tbody> <tr> <td style=`"width: 20%;`"><strong>Email</strong></td> <td style=`"width: 80%;`"><strong>Information</strong></td> </tr>" $body_emailrow = " <tr> <td>{0}</td> <td>Daily Count = <strong><font color=`"blue`">{1}</font></strong><br> <br> {2}</td> </tr>" $body_Footer = ' </tbody> </table>' foreach ($email in $AddressToQuery) { $email_results = Get-MessageTrace -RecipientAddress $email -StartDate ((Get-Date -Hour 0 -Minute 0 -Second 0).AddDays(-$DaysToQuery)) -EndDate ((Get-Date -Hour 0 -Minute 0 -Second 0)) [String]$html_fragment = ($email_results | sort SenderAddress | Select SenderAddress,Subject | ConvertTo-Html -Fragment -As Table) $body += $body_emailrow -f $email, $($email_results.count), $($html_fragment); #$body } $body += $body_Footer Send-MailMessage -SmtpServer $SMTPServer -From $email_from -To $email_to -Subject $email_subject -Body $body -BodyAsHtml Remove-PSSession $session }
Start-ExternalEmailTester.ps1
365Admin-1.0.2.1
Function Start-ExternalEmailTester { param( [Parameter(Mandatory=$true)] [System.Management.Automation.PsCredential] $Cred = $Host.UI.PromptForCredential('Enter Outlook.com Credential', 'Enter the username and password of your outlook.com account.', '', 'userCreds'), [String] [Parameter(Mandatory=$true)] $DestinationEmailAddress, [int32] $SecondDelay = 180 ) $counter = 0 $subjectBase = 'Test Email ' $SMTPServer = 'smtp-mail.outlook.com' #$Cred = Get-Credential while (1) { $subject = "[TESTING]External Email Tester - POSH on $($env:COMPUTERNAME)"; $subjectBase + $counter + "- $(Get-Date -DisplayHint Time)" $body = "$($subjectBase) $($counter) - $(Get-Date -DisplayHint Time) Test sent at $(Get-Date -DisplayHint DateTime) Next Email Expected at $((Get-Date).AddSeconds(180))" Send-MailMessage -SmtpServer $SMTPServer -Subject $subject -Body $body -Credential $Cred ` -To $DestinationEmailAddress ` -From $cred.UserName ` -UseSsl $counter++ Start-Sleep -Seconds $SecondDelay } }
loader.psm1
365Admin-1.0.2.1
# DO NOT MODIFY THIS FILE! # THIS FILE WAS AUTOGENERATED BY ISESTEROIDS AND WILL BE OVERWRITTEN WHEN YOU EXPORT FUNCTIONS TO THIS MODULE. # USE THIS FILE FOR ADDITIONAL MODULE CODE. THIS FILE WILL NOT BE OVERWRITTEN # WHEN NEW CONTENT IS PUBLISHED TO THIS MODULE: . $PSScriptRoot\init.ps1 # LOADING ALL FUNCTION DEFINITIONS: . $PSScriptRoot\Add-FullAccessPermission.ps1 . $PSScriptRoot\Add-SendAsPermission.ps1 . $PSScriptRoot\Backup-Whitelist.ps1 . $PSScriptRoot\Confirm-ExchangeOnlineConnection.ps1 . $PSScriptRoot\Connect-ExchangeComplianceOnline.ps1 . $PSScriptRoot\Connect-ExchangeOnline.ps1 . $PSScriptRoot\Connect-SPOL.ps1 . $PSScriptRoot\Disconnect-ExchangeComplianceOnline.ps1 . $PSScriptRoot\Disconnect-ExchangeOnline.ps1 . $PSScriptRoot\Get-DailyEmailCounts.ps1 . $PSScriptRoot\Get-ExchangeOnlineConnectionState.ps1 . $PSScriptRoot\Get-Wasted365License.ps1 . $PSScriptRoot\Start-DirSync.ps1 . $PSScriptRoot\Start-ExternalEmailTester.ps1 . $PSScriptRoot\Watch-EOLMigrationStatus.ps1
Start-DirSync.ps1
365Admin-1.0.2.1
function Start-DirSync { <# .SYNOPSIS Kicks off AD Connect Sync Cycle .DESCRIPTION Kicks off AD Connect Sync Cycle of specified type on specified server. .EXAMPLE Start-DirSync -SyncType Initial Starts Initial (Full) DirSync on AD Sync Server scrp-nettools01 (Default Value) .EXAMPLE Start-DirSync -SyncType Delta -ADSyncServer scrp-dirsync01 -Debug Starts Delta DirSync on AD Sync Server scrp-dirsync01 with debugging options (Writes output of current steps.) #> [CmdletBinding()] param ( # Define type of sync to start [Parameter(Mandatory = $true, Position = 0)] [ValidateSet('Delta','Initial')] [string] $SyncType, # Define AD Connect Server [Parameter(Mandatory = $true, Position = 1)] [System.String] $ADSyncServer, # Wait switch [Parameter(Mandatory = $false, Position = 2)] [switch] $Wait = $false, [Parameter(Mandatory = $false, Position = 3)] [switch] $Debug = $false ) $colors = 'Black', 'DarkBlue', 'DarkGreen', 'DarkCyan', 'DarkRed', 'DarkMagenta', 'DarkYellow', 'Gray', 'DarkGray', 'Blue', 'Green', 'Cyan', 'Red', 'Magenta', 'Yellow', 'White' if ($SyncType -eq 'Delta') { $sb = { Start-ADSyncSyncCycle -PolicyType Initial } } if ($SyncType -eq 'Initial') { $sb = { Start-ADSyncSyncCycle -PolicyType Delta } } Write-Progress -Activity 'Invoking a DirSync Cycle' -Status "Connecting to AD Sync Server $($ADSyncServer)" -PercentComplete 10 if ($Debug) { Write-Host -ForegroundColor Yellow -BackgroundColor Black -Object '-----------------------------------------------------' Write-Host -ForegroundColor Yellow -BackgroundColor Black -Object "-----Initiating Delta AADsync on $($ADSyncServer)-----" Write-Host -ForegroundColor Yellow -BackgroundColor Black -Object '-----------------------------------------------------' } Write-Progress -Activity 'Invoking a DirSync Cycle' -Status "Creating PSSession to $($ADSyncServer)" -PercentComplete 15 $DirSyncServerSession = New-PSSession -ComputerName $ADSyncServer if ($Debug) { Write-Host -ForegroundColor Magenta -BackgroundColor Black -Object 'Session opened' } Start-Sleep -Seconds 5 Write-Progress -Activity 'Invoking a DirSync Cycle' -Status "Entering PSSession to AD Sync Server $($ADSyncServer)" -PercentComplete 20 Enter-PSSession $DirSyncServerSession Write-Progress -Activity 'Invoking a DirSync Cycle' -Status "Starting AD Sync Cyle on $($ADSyncServer)" -PercentComplete 50 if ($Debug) { Write-Host -ForegroundColor Magenta -BackgroundColor Black -Object 'Entered Session' } Start-Sleep -Seconds 5 if ($Debug) { Write-Host -ForegroundColor Magenta -BackgroundColor Black -Object 'Initiating AADsync' } Write-Progress -Activity 'Invoking a DirSync Cycle' -Status "AD Sync Cyle finished starting on $($ADSyncServer)" -PercentComplete 80 #icm -ScriptBlock {cmd /C "C:\Program Files\Microsoft Azure AD Sync\Bin\DirectorySyncClientCmd.exe" initial} -Session $nettools01session Invoke-Command -ScriptBlock $sb -Session $DirSyncServerSession if ($Debug) { Write-Host -ForegroundColor Magenta -BackgroundColor Black -Object 'AADsync Completed' Write-Host -ForegroundColor Magenta -BackgroundColor Black -Object 'Exiting PSSession' } Exit-PSSession Start-Sleep -Seconds 5 Remove-PSSession -Session $DirSyncServerSession -Verbose Write-Progress -Activity 'Invoking a DirSync Cycle' -Status "Exited & Closed PSSession on $($ADSyncServer)" -PercentComplete 100 if ($Debug) { Write-Host -ForegroundColor Magenta -BackgroundColor Black -Object 'Session Removed' Write-Host Run the following command to check status of the latest 20 messages associated with Azure AD Connect. -ForegroundColor Magenta -BackgroundColor Black } Write-Output -Object "Get-EventLog -ComputerName $($ADSyncServer) -LogName Application -Source `"Directory Synchronization`" -Newest 20 | select TimeGenerated,EntryType,Message" if ($Wait) { Write-Host "Wait flag set. Beginning query of $ADSyncServer Logs..." -ForegroundColor Green -BackgroundColor Black Start-Sleep -Seconds 5 Write-Host "Still Working." -NoNewline -ForegroundColor Gray -BackgroundColor Black while ((Get-EventLog -ComputerName $ADSyncServer -LogName Application -Source "Directory Synchronization" -Newest 20 | select TimeGenerated, EntryType, Message | ? {$_.Message -contains "Finished" -and $_.TimeGenerated -gt (Get-Date).AddMinutes(-1)}).count -eq 0) { Write-Host '.' -NoNewline -ForegroundColor (Get-Random $colors) -BackgroundColor Black Start-Sleep -Seconds 3 } #Print out finished message (Get-EventLog -ComputerName $ADSyncServer -LogName Application -Source "Directory Synchronization" -Newest 20 | select TimeGenerated, EntryType, Message | ? {$_.Message -contains "Finished" -and $_.TimeGenerated -gt (Get-Date).AddMinutes(-1)}) } }
365Admin.psd1
365Admin-1.0.2.1
# # Module Manifest for Module '365Admin.psd1 # # This manifest file is a PowerShell hashtable with all technical requirements for this module # This module was autogenerated by ISESteroids (http://www.isesteroids.com) # # Generated: 2017-05-01 # @{ # Module Loader File RootModule = 'loader.psm1' # Version Number ModuleVersion = '1.0.2.1' # Unique Module ID GUID = '4a19de77-c990-4734-83a2-d94e2ebdf79a' # Module Author Author = 'mRiston' # Company CompanyName = 'mRiston' # Copyright Copyright = '(c) 2017 mRiston. All rights reserved.' # Module Description Description = 'Functions used for managing various aspects of Office 365.' # Minimum PowerShell Version Required PowerShellVersion = '' # Name of Required PowerShell Host PowerShellHostName = '' # Minimum Host Version Required PowerShellHostVersion = '' # Minimum .NET Framework-Version DotNetFrameworkVersion = '' # Minimum CLR (Common Language Runtime) Version CLRVersion = '' # Processor Architecture Required (X86, Amd64, IA64) ProcessorArchitecture = '' # Required Modules (will load before this module loads) RequiredModules = @() # Required Assemblies RequiredAssemblies = @() # PowerShell Scripts (.ps1) that need to be executed before this module loads ScriptsToProcess = @() # Type files (.ps1xml) that need to be loaded when this module loads TypesToProcess = @() # Format files (.ps1xml) that need to be loaded when this module loads FormatsToProcess = @() # NestedModules = @() # List of exportable functions FunctionsToExport = '*' # List of exportable cmdlets CmdletsToExport = '*' # List of exportable variables VariablesToExport = '*' # List of exportable aliases AliasesToExport = '*' # List of all modules contained in this module ModuleList = @() # List of all files contained in this module FileList = @() # Private data that needs to be passed to this module PrivateData = '' }
init.ps1
365Admin-1.0.2.1
# use this file to define global variables on module scope # or perform other initialization procedures. # this file will not be touched when new functions are exported to # this module.
Add-FullAccessPermission.ps1
365Admin-1.0.2.1
function Add-FullAccessPermission { <# .SYNOPSIS Adds FullAccess to target user .EXAMPLE Add-FullAccessPermission -enduser steve -targetmailbox bob Adds SendAs permission on bob's mailbox for end user steve WITHOUT AutoMapping. .EXAMPLE Add-FullAccessPermission -enduser steve -targetmailbox bob -AutoMapping Adds SendAs permission on bob's mailbox for end user steve WITH AutoMapping #> param ( [String] [Parameter(Mandatory)] $enduser, [Parameter(Mandatory)] [String] $targetmailbox, [Switch] $AutoMapping ) Confirm-ExchangeOnlineConnection -ConnectIfDisconnected try { if ($AutoMapping) { Write-Output 'AutoMapping Flag Set. Automapping = $true' Add-MailboxPermission ` -Identity $targetmailbox ` -User $enduser ` -AutoMapping $true ` -AccessRights FullAccess ` -Verbose } if (!$AutoMapping) { Write-Output 'AutoMapping Flag NOT Set. Automapping = $false' Add-MailboxPermission ` -Identity $targetmailbox ` -User $enduser ` -AutoMapping $false ` -AccessRights FullAccess ` -Verbose } } catch { Write-Output -InputObject 'Error in adding FullAccess permissions.' Return $_.Exception } }
Disconnect-ExchangeComplianceOnline.ps1
365Admin-1.0.2.1
Function Disconnect-ExchangeComplianceOnline { Get-PSSession | ?{$_.ComputerName -like '*ps.compliance.protection.outlook.com'} | Remove-PSSession }
Backup-Whitelist.ps1
365Admin-1.0.2.1
Function Backup-Whitelist { param( [System.Diagnostics.Switch] $Debugging, [Switch] $SendEmail, [Parameter(Mandatory = $False)] [String] $BackupPath = 'C:\scripts\powershell\EOL_WhitelistBackups\', [Parameter(Mandatory = $true)] [String] $EmailRecipient, [Parameter(Mandatory = $true)] [String] $EmailSenders, [Parameter(Mandatory = $true)] [String] $SMTPServer ) #region Varialbes New-Item $BackupPath -ItemType Directory -ErrorAction SilentlyContinue -Force [String]$Runtime = Get-Date -Format yyyy.MM.dd_HH.mm.sstt $BackupZip = $BackupPath + $Runtime + '.zip' $StartingLocation = Get-Location #endregion #region Connect to Exchange Online [System.Management.Automation.PsCredential]$Credential = $Host.UI.PromptForCredential('Enter Global Admin Credential', 'Enter the username and password of an Exchange Online Global Administrator account.', '', 'userCreds') [System.Uri]$Uri = 'https://outlook.office365.com/powershell-liveid/' #'https://ps.outlook.com/powershell/' $session = New-PSSession -ConfigurationName Microsoft.Exchange -ConnectionUri $Uri -Credential $Credential -Authentication Basic -AllowRedirection -Verbose Import-PSSession -Session $session -AllowClobber -Verbose #endregion Connect to Exchange Online $AllPolicies = Get-HostedContentFilterPolicy foreach ($SpamPolicy in $AllPolicies) { $OutFile = $BackupPath + $Runtime + '_' + $SpamPolicy.Name + '_AllowedSenderDomains.csv' $SpamPolicy.AllowedSenderDomains | Export-Csv -Path $OutFile -NoTypeInformation $OutFile = $BackupPath + $Runtime + '_' + $SpamPolicy.Name + '_AllowedSenders.csv' $SpamPolicy.AllowedSenders | Export-Csv -Path $OutFile -NoTypeInformation $OutFile = $BackupPath + $Runtime + '_' + $SpamPolicy.Name + '_BlockedSenderDomains.csv' $SpamPolicy.BlockedSenderDomains | Export-Csv -Path $OutFile -NoTypeInformation $OutFile = $BackupPath + $Runtime + '_' + $SpamPolicy.Name + '_BlockedSenders.csv' $SpamPolicy.BlockedSenders | Export-Csv -Path $OutFile -NoTypeInformation } Set-Location $BackupPath $BackupFiles = Get-ChildItem -Path $BackupPath*csv $BackupFiles | Write-Zip -Level 9 -OutputPath $BackupZip $BackupFiles | Remove-Item -Force -ErrorAction SilentlyContinue Set-Location $StartingLocation if ($SendEmail) { Send-MailMessage -SmtpServer $SMTPServer -To $EmailRecipient -From $EmailSenders -Subject "Exchange Spam Filter Backups - $($Runtime)" -Attachments $BackupZip } }
Get-Wasted365License.ps1
365Admin-1.0.2.1
function Get-Wasted365License { <# .SYNOPSIS Checks EOL for users with associated licenses who are also disabled in AD .DESCRIPTION This script is meant to find disabled users in Active Directory who are burning a 365 license. .EXAMPLE Get-Wasted365License -ProductType EnterprisePack -LicensePrefix SPANG1 Gets all users who are disabled that have an associated SPANG1:ENTERPRISEPACK license #> [CmdletBinding()] param ( # IFS Instance Selection [Parameter(ParameterSetName = 'ParameterSet1', Mandatory = $true, HelpMessage = 'Select the 365 License Type')] [ValidateSet('EnterprisePack','Visio','Project')] [string] $ProductType, [Parameter(Mandatory = $True)] [string] $LicensePrefix ) if ((Get-ExchangeOnlineConnectionState) -eq 'Disconnected') { $Cred = Get-Credential -Message "Enter your username and password for connecting to Exchange & Azure." Connect-ExchangeOnline -Credential $Cred; Connect-MsolService -Credential $Cred} switch ($ProductType) { EnterprisePack { $SKU = 'ENTERPRISEPACK' } Visio { $SKU = 'VISIOCLIENT' } Project { $SKU = 'PROJECTCLIENT' } } $ProductCompleteSKU = "$($LicensePrefix):$($SKU)" $MSOLUsers = Get-MsolUser -All $LicensedUsers = $MSOLUsers | Where-Object -FilterScript { $_.Licenses.AccountSKUId -eq $ProductCompleteSKU } $wastedLicense = @() foreach ($user in $LicensedUsers) { $name = ($user.UserPrincipalName.Split('@')[0]) if ((Get-ADUser -Identity $name -ErrorAction SilentlyContinue).Enabled -eq $false) { $wastedLicense += $name } } Remove-Variable -Name ProductType, SKU, LicensedUsers, user, name, ProductCompleteSKU return $wastedLicense Write-host "You must be connected to Exchange Online and MSOLService." -ForegroundColor Green -BackgroundColor Black Write-host "Use Connect-ExchangeOnline & Connect-MSOLService to ensure you are connected as required." -ForegroundColor Green -BackgroundColor Black }
Connect-ExchangeOnline.ps1
365Admin-1.0.2.1
Function Connect-ExchangeOnline { [CmdletBinding()] param ( [Parameter(Mandatory = $False)] [System.Management.Automation.PsCredential]$Credential = $Host.UI.PromptForCredential('Enter Global Admin Credential', 'Enter the username and password of an Exchange Online Global Administrator account.', '', 'userCreds'), [Parameter(Mandatory = $False)] [System.Uri]$Uri = 'https://outlook.office365.com/powershell-liveid/' #'https://ps.outlook.com/powershell/' ) $progressActivity = 'Connecting to Exchange Online' $prog_pctcomplete = 0 $prog_numofupdates = 3 $pctIncrement = (100 / $prog_numofupdates) Write-Progress -Activity $progressActivity -Status 'Creating Session Link to Exchange Online' -PercentComplete ($prog_pctcomplete += $pctIncrement) $session = New-PSSession -ConfigurationName Microsoft.Exchange -ConnectionUri $Uri -Credential $Credential -Authentication Basic -AllowRedirection -Verbose Write-Progress -Activity $progressActivity -Status 'Sleeping' -PercentComplete ($prog_pctcomplete += $pctIncrement) Start-Sleep -Seconds 1 Write-Progress -Activity $progressActivity -Status 'Importing the PowerShell Session' -PercentComplete ($prog_pctcomplete += $pctIncrement) Import-PSSession -Session $session -AllowClobber -Verbose Return $session }
Disconnect-ExchangeOnline.ps1
365Admin-1.0.2.1
Function Disconnect-ExchangeOnline { Get-PSSession | ?{$_.ComputerName -like '*outlook.office365.com'} | Remove-PSSession }
Add-SendAsPermission.ps1
365Admin-1.0.2.1
function Add-SendAsPermission { <# .SYNOPSIS Adds SendAs Extended Right to target user .EXAMPLE Add-SendAsPermission -enduser steve -targetmailbox bob Adds SendAs permission on bob's mailbox for end user steve. #> param ( [String] [Parameter(Mandatory)] $enduser, [Parameter(Mandatory)] [String] $targetmailbox ) Confirm-ExchangeOnlineConnection -ConnectIfDisconnected try { #Add-RecipientPermission -Identity "$($targetmailbox.samaccountname)" -Trustee "$($enduser.samaccountname)" -AccessRights SendAs -Verbose Add-RecipientPermission -Identity $targetmailbox -Trustee $enduser -AccessRights SendAs -Verbose } catch { Write-Output -InputObject 'Error in adding Recipient permissions.' Return $_.Exception } }
Invoke-365AutomatedCheck.ps1
365AutomatedCheck-0.0.11
<# .SYNOPSIS Invokes the 365AutomatedCheck function to perform automated checks on Microsoft 365 environments. .DESCRIPTION The Invoke-365AutomatedCheck function performs automated checks on Microsoft 365 environments by running Pester tests. It generates an HTML report from the test results, and optionally, an Excel report for detailed analysis. .PARAMETER PesterConfiguration Specifies the Pester configuration hashtable to be used for running the tests. .PARAMETER Verbosity Specifies the verbosity level for the Pester output. Valid values are 'None', 'Normal', 'Detailed', and 'Diagnostic'. The default value is 'None'. .PARAMETER XsltPath Specifies the path to the XSLT file used for transforming the XML report to HTML. The default path is "$RootPath/functions/private/DefaultReportConfig.xslt". .PARAMETER XmlPath Specifies the path to the XML report file generated by the Pester tests. If not provided, the default path is '365ACReport.xml'. .PARAMETER Path Specifies the path to the Pester test files. The default path is "$RootPath/tests/". .PARAMETER OutputHtmlPath Specifies the path to save the generated HTML report. If not provided, the default path is '365ACReport.html'. .PARAMETER PassThru Indicates whether to pass the Pester test results through the pipeline. By default, it is set to $false. .PARAMETER Tag Specifies the tags to include when running the Pester tests. Multiple tags can be specified using an array. .PARAMETER ExcludeTag Specifies the tags to exclude when running the Pester tests. Multiple tags can be specified using an array. .PARAMETER ExcelFilePath Specifies the path to the Excel file used for additional validation. This parameter is optional. .PARAMETER NoExcel Specifies whether to skip importing the Excel validation workbook. If set to $true, no Excel file imported. The default value is $false. .EXAMPLE Invoke-365AutomatedCheck -PesterConfiguration $config -Verbosity 'Detailed' -XmlPath 'C:\Reports\365ACReport.xml' -OutputHtmlPath 'C:\Reports\365ACReport.html' -Tag 'Basic', 'HR' Runs the 365AutomatedCheck function with a detailed verbosity level, specifying the XML report path and the output HTML path. It includes tests with the 'Basic' and 'HR' tags. .NOTES This function requires the Pester and ImportExcel modules to be installed. If the ImportExcel module is not installed and the Excel report is requested, the function will throw an error. .LINK https://github.com/DevClate/365AutomatedCheck #> function Invoke-365AutomatedCheck { [CmdletBinding()] param ( [hashtable] $PesterConfiguration, [ValidateSet('None', 'Normal', 'Detailed', 'Diagnostic')] [string] $Verbosity = 'None', [string] $XsltPath = "$RootPath/functions/private/DefaultReportConfig.xslt", [string] $XmlPath, [string] $Path = (Join-Path -Path $RootPath -ChildPath "tests"), [ValidatePattern(".*\.html$")] [string] $OutputHtmlPath, [bool] $PassThru = $false, [string[]] $Tag, [string[]] $ExcludeTag, [string] $ExcelFilePath, [bool] $NoExcel = $false ) #Requires -Module Pester, ImportExcel if (-not $XmlPath -and $OutputHtmlPath) { # Change the extension of $OutputHtmlPath to .xml and assign it to $XmlPath $XmlPath = [System.IO.Path]::ChangeExtension($OutputHtmlPath, '.xml') } $XmlPath = Set-365ACDefaultOutputPath -Path $XmlPath -DefaultPath '365ACReport.xml' Write-PSFMessage -Level Host -Message "Using XML Path: $XmlPath" $OutputHtmlPath = Set-365ACDefaultOutputPath -Path $OutputHtmlPath -DefaultPath '365ACReport.html' Write-PSFMessage -Level Host -Message "Using HTML Output Path: $OutputHtmlPath" $pesterConfig = Get-365ACPesterConfiguration -Path $Path -Tag $Tag -ExcludeTag $ExcludeTag -XmlPath $XmlPath -PesterConfiguration $PesterConfiguration -Verbosity $Verbosity -PassThru $PassThru -NoExcel $NoExcel # Conditionally set the ExcelFilePath environment variable if (-not $NoExcel) { $env:ExcelFilePath = $ExcelFilePath $env:NoExcel = $false } else { $env:NoExcel = $true } Invoke-Pester -Configuration $pesterConfig Start-Sleep -Seconds 2 Convert-365ACXmlToHtml -XmlPath $XmlPath -XsltPath $XsltPath -OutputHtmlPath $OutputHtmlPath }
Test-365ACCountry.ps1
365AutomatedCheck-0.0.11
<# .SYNOPSIS Tests whether users in Microsoft 365 have a country assigned and optionally validates against a list of valid countries. .DESCRIPTION The Test-365ACCountry function checks if users in Microsoft 365 have a country assigned to their profile. It can also validate these countries against a provided list of valid countries. The results of this test can be exported to an Excel file, an HTML file, or displayed in the console. .PARAMETER Users Specifies the users to be tested. If not specified, the function will test all users in the organization by retrieving their DisplayName and Country properties. .PARAMETER TenantID The ID of the tenant to connect to. Required if using app-only authentication. .PARAMETER ClientID The ID of the client to use for app-only authentication. Required if using app-only authentication. .PARAMETER CertificateThumbprint The thumbprint of the certificate to use for app-only authentication. Required if using app-only authentication. .PARAMETER AccessToken The access token to use for authentication. Required if using app-only authentication. .PARAMETER InteractiveLogin Specifies whether to use interactive login. If this switch is present, interactive login will be used. Otherwise, app-only authentication will be used. .PARAMETER ValidationExcelFilePath Specifies the path to an Excel file containing a list of valid countries. If specified, the function will validate the countries of the users against this list. .PARAMETER OutputExcelFilePath Specifies the path to save the test results as an Excel file. If not specified, the test results will be displayed in the console. The path must end with '.xlsx'. .PARAMETER OutputHtmlFilePath Specifies the path to save the test results as an HTML file. If not specified, the test results will be displayed in the console. The path must end with '.html'. .PARAMETER TestedProperty Specifies the name of the tested property. This will be used as the column name in the test results. Defaults to 'Has Country' but changes to 'Has Valid Country' if a validation list is provided. .EXAMPLE Test-365ACCountry -Users (Get-MgUser -All) -ValidationExcelFilePath "C:\Validation.xlsx" -OutputExcelFilePath "C:\Results.xlsx" Tests all users in the organization, validates their countries against the list of valid countries in "Validation.xlsx", and saves the test results to "Results.xlsx". .EXAMPLE Test-365ACCountry -Users (Get-MgUser -All) -OutputHtmlFilePath "C:\Results.html" Tests all users in the organization and saves the test results as an HTML file named "Results.html". .NOTES Requires the ImportExcel module for exporting results to Excel. If not installed, an error will be displayed. The Export-365ACResultToExcel and Export-365ACResultToHtml functions must be defined for exporting results to Excel or HTML, respectively. .LINK https://github.com/DevClate/365AutomatedCheck #> Function Test-365ACCountry { [CmdletBinding()] param ( [Parameter(ValueFromPipeline = $true)] [array]$Users = (Get-MgUser -All -Property DisplayName, Country | Select-Object DisplayName, Country), [Parameter(Mandatory = $false)] [string]$TenantID, [Parameter(Mandatory = $false)] [string]$ClientID, [Parameter(Mandatory = $false)] [string]$CertificateThumbprint, [Parameter(Mandatory = $false)] [string]$AccessToken, [Parameter(Mandatory = $false)] [switch]$InteractiveLogin, [ValidatePattern('\.xlsx$')] [string]$ValidationExcelFilePath, [ValidatePattern('\.xlsx$')] [string]$OutputExcelFilePath, [ValidatePattern('\.html$')] [string]$OutputHtmlFilePath, [string]$TestedProperty = 'Has Country' ) BEGIN { $validCountries = @() if ($ValidationExcelFilePath) { if (!(Get-Command Import-Excel -ErrorAction SilentlyContinue)) { Stop-PSFFunction -Message "Import-Excel cmdlet not found. Please install the ImportExcel module." -ErrorRecord $_ -Tag 'MissingModule' return@ } # Import the Excel file to get valid countries $validCountries = Import-Excel -Path $ValidationExcelFilePath | Select-Object -ExpandProperty Country -Unique } if ($InteractiveLogin) { Write-PSFMessage "Using interactive login..." -Level Host Connect-MgGraph -Scopes "User.Read.All", "AuditLog.read.All" -NoWelcome } else { Write-PSFMessage "Using app-only authentication..." -Level Host Connect-MgGraph -ClientId $ClientID -TenantId $TenantID -CertificateThumbprint $CertificateThumbprint -Scopes "User.Read.All", "AuditLog.Read.All" } $results = @() } PROCESS { $columnName = $ValidationExcelFilePath ? 'Has Valid Country' : 'Has Country' foreach ($user in $Users) { $hasCountry = [bool]($user.Country) if ($ValidationExcelFilePath) { $hasCountry = $user.Country -in $validCountries } $result = [PSCustomObject]@{ 'User Display Name' = $user.DisplayName $columnName = $hasCountry } $results += $result } } END { $totalTests = $results.Count $passedTests = ($results | Where-Object { $_.$columnName }).Count $failedTests = $totalTests - $passedTests if ($OutputExcelFilePath) { Export-365ACResultToExcel -Results $results -OutputExcelFilePath $OutputExcelFilePath -TotalTests $totalTests -PassedTests $passedTests -FailedTests $failedTests -TestedProperty $columnName } elseif ($OutputHtmlFilePath) { Export-365ACResultToHtml -Results $results -OutputHtmlFilePath $OutputHtmlFilePath -TotalTests $totalTests -PassedTests $passedTests -FailedTests $failedTests -TestedProperty $columnName } else { Write-PSFMessage -Level Output -Message ($results | Out-String) } } }
Test-365ACStreetAddress.ps1
365AutomatedCheck-0.0.11
<# .SYNOPSIS Tests whether users have a street address and generates a report. .DESCRIPTION The Test-365ACStreetAddress function tests whether users have a street address and generates a report. It takes a list of users as input and checks if each user has a street address. The function generates a report that includes the user's display name and whether they have a street address. The report can be exported to an Excel file or an HTML file. .PARAMETER Users Specifies the list of users to test. If not provided, it retrieves all users from the Microsoft Graph API. .PARAMETER TenantID The ID of the tenant to connect to. Required if using app-only authentication. .PARAMETER ClientID The ID of the client to use for app-only authentication. Required if using app-only authentication. .PARAMETER CertificateThumbprint The thumbprint of the certificate to use for app-only authentication. Required if using app-only authentication. .PARAMETER AccessToken The access token to use for authentication. Required if using app-only authentication. .PARAMETER InteractiveLogin Specifies whether to use interactive login. If this switch is present, interactive login will be used. Otherwise, app-only authentication will be used. .PARAMETER OutputExcelFilePath Specifies the file path to export the report as an Excel file. The file must have a .xlsx extension. .PARAMETER OutputHtmlFilePath Specifies the file path to export the report as an HTML file. The file must have a .html extension. .PARAMETER TestedProperty Specifies the name of the property being tested. Default value is 'Has Street Address'. .EXAMPLE Test-365ACStreetAddress -Users $users -OutputExcelFilePath 'C:\Reports\StreetAddressReport.xlsx' This example tests the specified list of users for street addresses and exports the report to an Excel file. .EXAMPLE Test-365ACStreetAddress -OutputExcelFilePath 'C:\Reports\StreetAddressReport.xlsx' This example retrieves all users from the Microsoft Graph API, tests them for street addresses, and exports the report to an Excel file. #> Function Test-365ACStreetAddress { [CmdletBinding()] param ( [Parameter(ValueFromPipeline = $true)] [array]$Users = (Get-MgUser -All -Property DisplayName, StreetAddress | Select-Object DisplayName, StreetAddress), [Parameter(Mandatory = $false)] [string]$TenantID, [Parameter(Mandatory = $false)] [string]$ClientID, [Parameter(Mandatory = $false)] [string]$CertificateThumbprint, [Parameter(Mandatory = $false)] [string]$AccessToken, [Parameter(Mandatory = $false)] [switch]$InteractiveLogin, [ValidatePattern('\.xlsx$')] [string]$OutputExcelFilePath, [ValidatePattern('\.html$')] [string]$OutputHtmlFilePath, [string]$TestedProperty = 'Has Street Address' ) BEGIN { if ($InteractiveLogin) { Write-PSFMessage "Using interactive login..." -Level Host Connect-MgGraph -Scopes "User.Read.All", "AuditLog.read.All" -NoWelcome } else { Write-PSFMessage "Using app-only authentication..." -Level Host Connect-MgGraph -ClientId $ClientID -TenantId $TenantID -CertificateThumbprint $CertificateThumbprint -Scopes "User.Read.All", "AuditLog.Read.All" } $results = @() } PROCESS { foreach ($user in $Users) { $hasStreetAddress = [bool]($user.StreetAddress) $result = [PSCustomObject]@{ 'User Display Name' = $user.DisplayName $TestedProperty = $hasStreetAddress } $results += $result } } END { $totalTests = $results.Count $passedTests = ($results | Where-Object { $_.$TestedProperty }).Count $failedTests = $totalTests - $passedTests if ($OutputExcelFilePath) { Export-365ACResultToExcel -Results $results -OutputExcelFilePath $OutputExcelFilePath -TotalTests $totalTests -PassedTests $passedTests -FailedTests $failedTests -TestedProperty $TestedProperty } elseif ($OutputHtmlFilePath) { Export-365ACResultToHtml -Results $results -OutputHtmlFilePath $OutputHtmlFilePath -TotalTests $totalTests -PassedTests $passedTests -FailedTests $failedTests -TestedProperty $TestedProperty } else { Write-Output $results } } }
Test-365ACMailNickName.ps1
365AutomatedCheck-0.0.11
<# .SYNOPSIS Tests if users have a mail nickname assigned in their Microsoft 365 profiles. .DESCRIPTION The Test-365ACMailNickname function checks each user retrieved from Microsoft 365 for a mail nickname value. It processes a list of users, determining whether each user has a mail nickname assigned. The results can be exported to an Excel file, an HTML file, or output directly. .PARAMETER Users An array of users to be tested. This can be piped in or specified directly. Each user should have DisplayName and MailNickname properties. .PARAMETER TenantID The ID of the tenant to connect to. Required if using app-only authentication. .PARAMETER ClientID The ID of the client to use for app-only authentication. Required if using app-only authentication. .PARAMETER CertificateThumbprint The thumbprint of the certificate to use for app-only authentication. Required if using app-only authentication. .PARAMETER AccessToken The access token to use for authentication. Required if using app-only authentication. .PARAMETER InteractiveLogin Specifies whether to use interactive login. If this switch is present, interactive login will be used. Otherwise, app-only authentication will be used. .PARAMETER OutputExcelFilePath The file path where the Excel report will be saved. The file must have an .xlsx extension. .PARAMETER OutputHtmlFilePath The file path where the HTML report will be saved. The file must have an .html extension. .PARAMETER TestedProperty The property being tested. This is set to 'Has Mail Nickname' by default. .EXAMPLE PS> $users = Get-MgUser -All -Property DisplayName, MailNickname | Select-Object DisplayName, MailNickname PS> Test-365ACMailNickname -Users $users -OutputExcelFilePath "C:\Reports\MailNicknameReport.xlsx" This example retrieves all users with their DisplayName and MailNickname, then tests each user to see if they have a mail nickname assigned. The results are exported to an Excel file. .EXAMPLE PS> Get-MgUser -All -Property DisplayName, MailNickname | Select-Object DisplayName, MailNickname | Test-365ACMailNickname -OutputHtmlFilePath "C:\Reports\MailNicknameReport.html" This example pipes a list of users directly into Test-365ACMailNickname, which then checks if each user has a mail nickname assigned. The results are exported to an HTML file. .NOTES This function requires the Microsoft Graph PowerShell SDK to retrieve user information from Microsoft 365. .LINK https://docs.microsoft.com/powershell/module/microsoft.graph.users/get-mguser .LINK https://github.com/DevClate/365AutomatedCheck #> Function Test-365ACMailNickname { [CmdletBinding()] param ( [Parameter(ValueFromPipeline = $true)] [array]$Users = (Get-MgUser -All -Property DisplayName, MailNickname | Select-Object DisplayName, MailNickname), [Parameter(Mandatory = $false)] [string]$TenantID, [Parameter(Mandatory = $false)] [string]$ClientID, [Parameter(Mandatory = $false)] [string]$CertificateThumbprint, [Parameter(Mandatory = $false)] [string]$AccessToken, [Parameter(Mandatory = $false)] [switch]$InteractiveLogin, [ValidatePattern('\.xlsx$')] [string]$OutputExcelFilePath, [ValidatePattern('\.html$')] [string]$OutputHtmlFilePath, [string]$TestedProperty = 'Has Mail Nickname' ) BEGIN { if ($InteractiveLogin) { Write-PSFMessage "Using interactive login..." -Level Host Connect-MgGraph -Scopes "User.Read.All", "AuditLog.read.All" -NoWelcome } else { Write-PSFMessage "Using app-only authentication..." -Level Host Connect-MgGraph -ClientId $ClientID -TenantId $TenantID -CertificateThumbprint $CertificateThumbprint -Scopes "User.Read.All", "AuditLog.Read.All" } $results = @() } PROCESS { foreach ($user in $Users) { $hasMailNickname = [bool]($user.MailNickname) $result = [PSCustomObject]@{ 'User Display Name' = $user.DisplayName $TestedProperty = $hasMailNickname } $results += $result } } END { $totalTests = $results.Count $passedTests = ($results | Where-Object { $_.$TestedProperty }).Count $failedTests = $totalTests - $passedTests if ($OutputExcelFilePath) { Export-365ACResultToExcel -Results $results -OutputExcelFilePath $OutputExcelFilePath -TotalTests $totalTests -PassedTests $passedTests -FailedTests $failedTests -TestedProperty $TestedProperty } elseif ($OutputHtmlFilePath) { Export-365ACResultToHtml -Results $results -OutputHtmlFilePath $OutputHtmlFilePath -TotalTests $totalTests -PassedTests $passedTests -FailedTests $failedTests -TestedProperty $TestedProperty } else { Write-Output $results } } }
Test-365ACAddressBook.ps1
365AutomatedCheck-0.0.11
<# .SYNOPSIS Tests if users are hidden from the Address Book in their Microsoft 365 profiles. .DESCRIPTION The Test-365ACAddressBook function checks each user retrieved from Microsoft 365 to determine if they are hidden from the Address Book. It processes a list of users, checking the 'HiddenFromAddressListsEnabled' property. The results can be exported to an Excel file, an HTML file, or output directly. .PARAMETER Users An array of users to be tested. This can be piped in or specified directly. Each user should have DisplayName and HiddenFromAddressListsEnabled properties. .PARAMETER TenantID The ID of the tenant to connect to. Required if using app-only authentication. .PARAMETER ClientID The ID of the client to use for app-only authentication. Required if using app-only authentication. .PARAMETER CertificateThumbprint The thumbprint of the certificate to use for app-only authentication. Required if using app-only authentication. .PARAMETER AccessToken The access token to use for authentication. Required if using app-only authentication. .PARAMETER InteractiveLogin Specifies whether to use interactive login. If this switch is present, interactive login will be used. Otherwise, app-only authentication will be used. .PARAMETER OutputExcelFilePath The file path where the Excel report will be saved. The file must have an .xlsx extension. .PARAMETER OutputHtmlFilePath The file path where the HTML report will be saved. The file must have an .html extension. .PARAMETER TestedProperty The property being tested. This is set to 'HiddenFromAddressBook' by default. .EXAMPLE $users = Get-MgUser -All -Property DisplayName, HiddenFromAddressListsEnabled | Select-Object DisplayName, HiddenFromAddressListsEnabled Test-365ACAddressBook -Users $users -OutputExcelFilePath "C:\Reports\AddressBookReport.xlsx" This example retrieves all users with their DisplayName and HiddenFromAddressListsEnabled properties, then tests each user to see if they are hidden from the Address Book. The results are exported to an Excel file. .EXAMPLE Get-MgUser -All -Property DisplayName, HiddenFromAddressListsEnabled | Select-Object DisplayName, HiddenFromAddressListsEnabled | Test-365ACAddressBook -OutputHtmlFilePath "C:\Reports\AddressBookReport.html" This example pipes a list of users directly into Test-365ACAddressBook, which then checks if each user is hidden from the Address Book. The results are exported to an HTML file. .NOTES This function requires the Microsoft Graph PowerShell SDK to retrieve user information from Microsoft 365. .LINK https://docs.microsoft.com/powershell/module/microsoft.graph.users/get-mguser #> Function Test-365ACAddressBook { [CmdletBinding()] param ( [Parameter(ValueFromPipeline = $true)] [array]$Users = (Get-MgUser -All -Property DisplayName, HiddenFromAddressListsEnabled | Select-Object DisplayName, HiddenFromAddressListsEnabled), [Parameter(Mandatory = $false)] [string]$TenantID, [Parameter(Mandatory = $false)] [string]$ClientID, [Parameter(Mandatory = $false)] [string]$CertificateThumbprint, [Parameter(Mandatory = $false)] [string]$AccessToken, [Parameter(Mandatory = $false)] [switch]$InteractiveLogin, [ValidatePattern('\.xlsx$')] [string]$OutputExcelFilePath, [ValidatePattern('\.html$')] [string]$OutputHtmlFilePath, [string]$TestedProperty = 'HiddenFromAddressBook' ) BEGIN { if ($InteractiveLogin) { Write-PSFMessage "Using interactive login..." -Level Host Connect-MgGraph -Scopes "User.Read.All", "AuditLog.read.All" -NoWelcome } else { Write-PSFMessage "Using app-only authentication..." -Level Host Connect-MgGraph -ClientId $ClientID -TenantId $TenantID -CertificateThumbprint $CertificateThumbprint -Scopes "User.Read.All", "AuditLog.Read.All" } $results = @() } PROCESS { foreach ($user in $Users) { $isHiddenFromAddressBook = [bool]($user.HiddenFromAddressListsEnabled) $result = [PSCustomObject]@{ 'User Display Name' = $user.DisplayName $TestedProperty = $isHiddenFromAddressBook } $results += $result } } END { $totalTests = $results.Count $passedTests = ($results | Where-Object { $_.$TestedProperty }).Count $failedTests = $totalTests - $passedTests if ($OutputExcelFilePath) { Export-365ACResultToExcel -Results $results -OutputExcelFilePath $OutputExcelFilePath -TotalTests $totalTests -PassedTests $passedTests -FailedTests $failedTests -TestedProperty $TestedProperty } elseif ($OutputHtmlFilePath) { Export-365ACResultToHtml -Results $results -OutputHtmlFilePath $OutputHtmlFilePath -TotalTests $totalTests -PassedTests $passedTests -FailedTests $failedTests -TestedProperty $TestedProperty } else { Write-Output $results } } }
Set-365ACDefaultOutputPath.ps1
365AutomatedCheck-0.0.11
<# .SYNOPSIS Sets the default output path for the 365ACReports. .DESCRIPTION This function sets the default output path for the 365ACReports. If a specific path is provided, it checks if it is an absolute path. If not, it appends it to the base reports path. If no path is provided, it creates a new path based on the current date and the default path. .PARAMETER Path The specific path to set as the default output path. If not provided, a new path will be created based on the current date and the default path. .PARAMETER DefaultPath The default path to use when creating a new path based on the current date. .EXAMPLE Set-365ACDefaultOutputPath -Path "C:\Reports\" -DefaultPath "Output" This example sets the default output path to "C:\Reports". .OUTPUTS The function returns the final output path. .NOTES This function requires the Write-PSFMessage function from the PowerShell Framework module. .LINK https://github.com/DevClate/365AutomatedCheck #> function Set-365ACDefaultOutputPath { param ( [string] $Path, [ValidateNotNullOrEmpty()] [string] $DefaultPath ) # Initialize the base reports path $reportsPath = Join-Path -Path (Get-Location) -ChildPath "365ACReports" if (-not $Path) { $todaysDate = (Get-Date).ToString("yyyyMMdd-HHmm") $datePath = "$todaysDate-$DefaultPath" $Path = Join-Path -Path $reportsPath -ChildPath $datePath } else { # Check if the provided Path is an absolute path if ([System.IO.Path]::IsPathRooted($Path)) { # If it's an absolute path, use it directly } else { # If it's not an absolute path, append it to the $reportsPath $Path = Join-Path -Path $reportsPath -ChildPath $Path } } $folderPath = [System.IO.Path]::GetDirectoryName($Path) try { if (-not (Test-Path -Path $folderPath)) { Write-PSFMessage -Level Host -Message "Creating directory: $folderPath" New-Item -ItemType Directory -Path $folderPath -Force | Out-Null } else { Write-PSFMessage -Level Host -Message "Using existing directory: $folderPath" } } catch { Write-PSFMessage -Level Error -Message "Failed to create or access directory: $folderPath. Error: $_" throw } return $Path }
Get-365ACPesterConfiguration.ps1
365AutomatedCheck-0.0.11
<# .SYNOPSIS Retrieves the Pester configuration for the 365AutomatedCheck module. .DESCRIPTION The Get-365ACPesterConfiguration function retrieves the Pester configuration for the 365AutomatedCheck module. It allows you to customize the configuration by specifying various parameters such as the path to run the tests, tags to include or exclude, XML output path, Pester configuration hashtable, verbosity level, and whether to pass through the configuration object. .PARAMETER Path The path where the Pester tests should be run. .PARAMETER Tag An array of tags to include when running the tests. .PARAMETER ExcludeTag An array of tags to exclude when running the tests. .PARAMETER XmlPath The path where the XML test results should be saved. .PARAMETER PesterConfiguration A hashtable containing additional Pester configuration settings. .PARAMETER Verbosity The verbosity level for the Pester output. .PARAMETER PassThru Specifies whether to return the Pester configuration object. .OUTPUTS PesterConfiguration The Pester configuration object. .EXAMPLE PS> Get-365ACPesterConfiguration -Path "C:\Tests" -Tag "Unit" -XmlPath "C:\TestResults.xml" -Verbosity "Detailed" This example retrieves the Pester configuration for the 365AutomatedCheck module. It sets the path to run the tests to "C:\Tests", includes only tests with the "Unit" tag, saves the XML test results to "C:\TestResults.xml", and sets the verbosity level to "Detailed". #> function Get-365ACPesterConfiguration { param ( [string] $Path, [string[]] $Tag, [string[]] $ExcludeTag, [string] $XmlPath, [hashtable] $PesterConfiguration, [string] $Verbosity, [bool] $PassThru ) $config = [PesterConfiguration]::Default $config.Run.Path = $Path $config.Run.PassThru = $PassThru $config.Output.Verbosity = $Verbosity $config.TestResult.Enabled = $true $config.TestResult.OutputPath = $XmlPath $config.TestResult.OutputFormat = 'NUnitXml' if ($Tag) { $config.Filter.Tag = $Tag } if ($ExcludeTag) { $config.Filter.ExcludeTag = $ExcludeTag } return $config }
Test-365ACState.ps1
365AutomatedCheck-0.0.11
<# .SYNOPSIS Tests if users have a state assigned in their Microsoft 365 profiles. .DESCRIPTION The Test-365ACState function checks each user retrieved from Microsoft 365 for a state value. It processes a list of users, determining whether each user has a state assigned. The results can be exported to an Excel file, an HTML file, or output directly. .PARAMETER Users An array of users to be tested. This can be piped in or specified directly. Each user should have DisplayName and State properties. .PARAMETER TenantID The ID of the tenant to connect to. Required if using app-only authentication. .PARAMETER ClientID The ID of the client to use for app-only authentication. Required if using app-only authentication. .PARAMETER CertificateThumbprint The thumbprint of the certificate to use for app-only authentication. Required if using app-only authentication. .PARAMETER AccessToken The access token to use for authentication. Required if using app-only authentication. .PARAMETER InteractiveLogin Specifies whether to use interactive login. If this switch is present, interactive login will be used. Otherwise, app-only authentication will be used. .PARAMETER OutputExcelFilePath The file path where the Excel report will be saved. The file must have an .xlsx extension. .PARAMETER OutputHtmlFilePath The file path where the HTML report will be saved. The file must have an .html extension. .PARAMETER TestedProperty The property being tested. This is set to 'Has State' by default. .EXAMPLE PS> $users = Get-MgUser -All -Property DisplayName, State | Select-Object DisplayName, State PS> Test-365ACState -Users $users -OutputExcelFilePath "C:\Reports\StateReport.xlsx" This example retrieves all users with their DisplayName and State, then tests each user to see if they have a state assigned. The results are exported to an Excel file. .EXAMPLE PS> Get-MgUser -All -Property DisplayName, State | Select-Object DisplayName, State | Test-365ACState -OutputHtmlFilePath "C:\Reports\StateReport.html" This example pipes a list of users directly into Test-365ACState, which then checks if each user has a state assigned. The results are exported to an HTML file. .NOTES This function requires the Microsoft Graph PowerShell SDK to retrieve user information from Microsoft 365. .LINK https://docs.microsoft.com/powershell/module/microsoft.graph.users/get-mguser #> Function Test-365ACState { [CmdletBinding()] param ( [Parameter(ValueFromPipeline = $true)] [array]$Users = (Get-MgUser -All -Property DisplayName, State | Select-Object DisplayName, State), [Parameter(Mandatory = $false)] [string]$TenantID, [Parameter(Mandatory = $false)] [string]$ClientID, [Parameter(Mandatory = $false)] [string]$CertificateThumbprint, [Parameter(Mandatory = $false)] [string]$AccessToken, [Parameter(Mandatory = $false)] [switch]$InteractiveLogin, [ValidatePattern('\.xlsx$')] [string]$OutputExcelFilePath, [ValidatePattern('\.html$')] [string]$OutputHtmlFilePath, [string]$TestedProperty = 'Has State' ) BEGIN { if ($InteractiveLogin) { Write-PSFMessage "Using interactive login..." -Level Host Connect-MgGraph -Scopes "User.Read.All", "AuditLog.read.All" -NoWelcome } else { Write-PSFMessage "Using app-only authentication..." -Level Host Connect-MgGraph -ClientId $ClientID -TenantId $TenantID -CertificateThumbprint $CertificateThumbprint -Scopes "User.Read.All", "AuditLog.Read.All" } $results = @() } PROCESS { foreach ($user in $Users) { $hasState = [bool]($user.State) $result = [PSCustomObject]@{ 'User Display Name' = $user.DisplayName $TestedProperty = $hasState } $results += $result } } END { $totalTests = $results.Count $passedTests = ($results | Where-Object { $_.$TestedProperty }).Count $failedTests = $totalTests - $passedTests if ($OutputExcelFilePath) { Export-365ACResultToExcel -Results $results -OutputExcelFilePath $OutputExcelFilePath -TotalTests $totalTests -PassedTests $passedTests -FailedTests $failedTests -TestedProperty $TestedProperty } elseif ($OutputHtmlFilePath) { Export-365ACResultToHtml -Results $results -OutputHtmlFilePath $OutputHtmlFilePath -TotalTests $totalTests -PassedTests $passedTests -FailedTests $failedTests -TestedProperty $TestedProperty } else { Write-Output $results } } }
Test-365ACMobilePhone.ps1
365AutomatedCheck-0.0.11
<# .SYNOPSIS Tests whether users in Microsoft 365 have a valid mobile phone number. .DESCRIPTION The Test-365ACMobilePhone function checks if users in Microsoft 365 have a mobile phone number and optionally validates these numbers against a provided list of valid numbers. It supports outputting the results to an Excel file, an HTML file, or the console. .PARAMETER Users Specifies an array of users to test. If not provided, the function retrieves all users in Microsoft 365 with their DisplayName and MobilePhone properties. .PARAMETER TenantID The ID of the tenant to connect to. Required if using app-only authentication. .PARAMETER ClientID The ID of the client to use for app-only authentication. Required if using app-only authentication. .PARAMETER CertificateThumbprint The thumbprint of the certificate to use for app-only authentication. Required if using app-only authentication. .PARAMETER AccessToken The access token to use for authentication. Required if using app-only authentication. .PARAMETER InteractiveLogin Specifies whether to use interactive login. If this switch is present, interactive login will be used. Otherwise, app-only authentication will be used. .PARAMETER ValidationExcelFilePath Specifies the path to an Excel file containing a list of valid mobile phone numbers. If provided, the function validates the users' mobile phone numbers against this list. .PARAMETER OutputExcelFilePath Specifies the path to an Excel file where the results will be exported. Requires the ImportExcel module. .PARAMETER OutputHtmlFilePath Specifies the path to an HTML file where the results will be exported. Requires the Export-365ACResultToHtml function to be defined. .PARAMETER TestedProperty Specifies the property that is being tested. Defaults to 'Has Valid Mobile Phone' when validating against a list, otherwise 'Has Mobile Phone'. .EXAMPLE Test-365ACMobilePhone -Users (Get-MgUser -All) -OutputExcelFilePath "C:\Results.xlsx" Retrieves all users in Microsoft 365 and exports the validation results to an Excel file. .EXAMPLE Test-365ACMobilePhone -Users (Get-MgUser -All) -OutputHtmlFilePath "C:\Results.html" Retrieves all users in Microsoft 365 and exports the validation results to an HTML file. .EXAMPLE Test-365ACMobilePhone -Users (Get-MgUser -All) Retrieves all users in Microsoft 365 and outputs the validation results to the console. .NOTES - Requires the ImportExcel module for exporting results to Excel. If not installed, an error will be displayed. - The Export-365ACResultToExcel and Export-365ACResultToHtml functions must be defined for exporting results to Excel or HTML, respectively. .LINK https://github.com/DevClate/365AutomatedCheck #> function Test-365ACMobilePhone { [CmdletBinding()] param ( [Parameter(ValueFromPipeline = $true)] [array]$Users = (Get-MgUser -All -Property DisplayName, MobilePhone | Select-Object DisplayName, MobilePhone), [Parameter(Mandatory = $false)] [string]$TenantID, [Parameter(Mandatory = $false)] [string]$ClientID, [Parameter(Mandatory = $false)] [string]$CertificateThumbprint, [Parameter(Mandatory = $false)] [string]$AccessToken, [Parameter(Mandatory = $false)] [switch]$InteractiveLogin, [ValidatePattern('\.xlsx$')] [string]$ValidationExcelFilePath, [ValidatePattern('\.xlsx$')] [string]$OutputExcelFilePath, [ValidatePattern('\.html$')] [string]$OutputHtmlFilePath, [string]$TestedProperty = 'Has Valid Mobile Phone' ) BEGIN { $validMobilePhones = @() if ($ValidationExcelFilePath) { if (!(Get-Command Import-Excel -ErrorAction SilentlyContinue)) { Stop-PSFFunction -Message "Import-Excel cmdlet not found. Please install the ImportExcel module." -ErrorRecord $_ -Tag 'MissingModule' return } # Import the Excel file to get valid mobile phone numbers $validMobilePhones = Import-Excel -Path $ValidationExcelFilePath | Select-Object -ExpandProperty MobilePhone -Unique } if ($InteractiveLogin) { Write-PSFMessage "Using interactive login..." -Level Host Connect-MgGraph -Scopes "User.Read.All", "AuditLog.read.All" -NoWelcome } else { Write-PSFMessage "Using app-only authentication..." -Level Host Connect-MgGraph -ClientId $ClientID -TenantId $TenantID -CertificateThumbprint $CertificateThumbprint -Scopes "User.Read.All", "AuditLog.Read.All" } $results = @() } PROCESS { $columnName = $ValidationExcelFilePath ? 'Has Valid Mobile Phone' : 'Has Mobile Phone' foreach ($user in $Users) { $hasMobilePhone = [bool]($user.MobilePhone) if ($ValidationExcelFilePath) { $hasMobilePhone = $user.MobilePhone -in $validMobilePhones } $result = [PSCustomObject]@{ 'User Display Name' = $user.DisplayName $columnName = $hasMobilePhone } $results += $result } } END { $totalTests = $results.Count $passedTests = ($results | Where-Object { $_.$columnName }).Count $failedTests = $totalTests - $passedTests if ($OutputExcelFilePath) { Export-365ACResultToExcel -Results $results -OutputExcelFilePath $OutputExcelFilePath -TotalTests $totalTests -PassedTests $passedTests -FailedTests $failedTests -TestedProperty $columnName } elseif ($OutputHtmlFilePath) { Export-365ACResultToHtml -Results $results -OutputHtmlFilePath $OutputHtmlFilePath -TotalTests $totalTests -PassedTests $passedTests -FailedTests $failedTests -TestedProperty $columnName } else { Write-PSFMessage -Level Output -Message ($results | Out-String) } } }
Test-365ACCompanyName.ps1
365AutomatedCheck-0.0.11
<# .SYNOPSIS Tests whether users in Microsoft 365 have a company name assigned and optionally validates against a list of valid company names. .DESCRIPTION The Test-365ACCompanyName function checks if users in Microsoft 365 have a company name assigned to their profile. It can also validate these company names against a provided list of valid company names. The results of this test can be exported to an Excel file, an HTML file, or displayed in the console. .PARAMETER Users Specifies the users to be tested. If not specified, the function will test all users in the organization by retrieving their DisplayName and CompanyName properties. .PARAMETER TenantID The ID of the tenant to connect to. Required if using app-only authentication. .PARAMETER ClientID The ID of the client to use for app-only authentication. Required if using app-only authentication. .PARAMETER CertificateThumbprint The thumbprint of the certificate to use for app-only authentication. Required if using app-only authentication. .PARAMETER AccessToken The access token to use for authentication. Required if using app-only authentication. .PARAMETER InteractiveLogin Specifies whether to use interactive login. If this switch is present, interactive login will be used. Otherwise, app-only authentication will be used. .PARAMETER ValidationExcelFilePath Specifies the path to an Excel file containing a list of valid company names. If specified, the function will validate the company names of the users against this list. .PARAMETER OutputExcelFilePath Specifies the path to save the test results as an Excel file. If not specified, the test results will be displayed in the console. The path must end with '.xlsx'. .PARAMETER OutputHtmlFilePath Specifies the path to save the test results as an HTML file. If not specified, the test results will be displayed in the console. The path must end with '.html'. .PARAMETER TestedProperty Specifies the name of the tested property. This will be used as the column name in the test results. Defaults to 'Has Company Name' but changes to 'Has Valid Company Name' if a validation list is provided. .EXAMPLE Test-365ACCompanyName -Users (Get-MgUser -All) -ValidationExcelFilePath "C:\Validation.xlsx" -OutputExcelFilePath "C:\Results.xlsx" Tests all users in the organization, validates their company names against the list of valid company names in "Validation.xlsx", and saves the test results to "Results.xlsx". .EXAMPLE Test-365ACCompanyName -Users (Get-MgUser -All) -OutputHtmlFilePath "C:\Results.html" Tests all users in the organization and saves the test results as an HTML file named "Results.html". .NOTES Requires the ImportExcel module for exporting results to Excel. If not installed, an error will be displayed. The Export-365ACResultToExcel and Export-365ACResultToHtml functions must be defined for exporting results to Excel or HTML, respectively. .LINK https://github.com/DevClate/365AutomatedCheck #> Function Test-365ACCompanyName { [CmdletBinding()] param ( [Parameter(ValueFromPipeline = $true)] [array]$Users = (Get-MgUser -All -Property DisplayName, CompanyName | Select-Object DisplayName, CompanyName), [Parameter(Mandatory = $false)] [string]$TenantID, [Parameter(Mandatory = $false)] [string]$ClientID, [Parameter(Mandatory = $false)] [string]$CertificateThumbprint, [Parameter(Mandatory = $false)] [string]$AccessToken, [Parameter(Mandatory = $false)] [switch]$InteractiveLogin, [ValidatePattern('\.xlsx$')] [string]$ValidationExcelFilePath, [ValidatePattern('\.xlsx$')] [string]$OutputExcelFilePath, [ValidatePattern('\.html$')] [string]$OutputHtmlFilePath, [string]$TestedProperty = 'Has Company Name' ) BEGIN { $validCompanyNames = @() if ($ValidationExcelFilePath) { if (!(Get-Command Import-Excel -ErrorAction SilentlyContinue)) { Stop-PSFFunction -Message "Import-Excel cmdlet not found. Please install the ImportExcel module." -ErrorRecord $_ -Tag 'MissingModule' return@ } # Import the Excel file to get valid company names $validCompanyNames = Import-Excel -Path $ValidationExcelFilePath | Select-Object -ExpandProperty CompanyName -Unique } if ($InteractiveLogin) { Write-PSFMessage "Using interactive login..." -Level Host Connect-MgGraph -Scopes "User.Read.All", "AuditLog.read.All" -NoWelcome } else { Write-PSFMessage "Using app-only authentication..." -Level Host Connect-MgGraph -ClientId $ClientID -TenantId $TenantID -CertificateThumbprint $CertificateThumbprint -Scopes "User.Read.All", "AuditLog.Read.All" } $results = @() } PROCESS { $columnName = $ValidationExcelFilePath ? 'Has Valid Company Name' : 'Has Company Name' foreach ($user in $Users) { $hasCompanyName = [bool]($user.CompanyName) if ($ValidationExcelFilePath) { $hasCompanyName = $user.CompanyName -in $validCompanyNames } $result = [PSCustomObject]@{ 'User Display Name' = $user.DisplayName $columnName = $hasCompanyName } $results += $result } } END { $totalTests = $results.Count $passedTests = ($results | Where-Object { $_.$columnName }).Count $failedTests = $totalTests - $passedTests if ($OutputExcelFilePath) { Export-365ACResultToExcel -Results $results -OutputExcelFilePath $OutputExcelFilePath -TotalTests $totalTests -PassedTests $passedTests -FailedTests $failedTests -TestedProperty $columnName } elseif ($OutputHtmlFilePath) { Export-365ACResultToHtml -Results $results -OutputHtmlFilePath $OutputHtmlFilePath -TotalTests $totalTests -PassedTests $passedTests -FailedTests $failedTests -TestedProperty $columnName } else { Write-PSFMessage -Level Output -Message ($results | Out-String) } } }
365AutomatedCheck.psm1
365AutomatedCheck-0.0.11
$RootPath = Split-Path $MyInvocation.MyCommand.Path $FunctionFiles = $("$PSScriptRoot\functions\public\","$PSScriptRoot\functions\private\") | Get-Childitem -file -Recurse -Include "*.ps1" -ErrorAction SilentlyContinue $functions = @() foreach($FunctionFile in $FunctionFiles){ try { . $FunctionFile.FullName $functions += Get-Command -Module $MyInvocation.MyCommand.ModuleName -CommandType Function } catch { Write-Error -Message "Failed to import function: '$($FunctionFile.FullName)': $_" } } Export-ModuleMember -Function ($functions.Name)
Test-365ACFaxNumber.ps1
365AutomatedCheck-0.0.11
<# .SYNOPSIS Tests whether users in Microsoft 365 have a fax number assigned and exports the results. .DESCRIPTION The Test-365ACFaxNumber function checks if users in Microsoft 365 have a fax number by examining the FaxNumber property. It can validate fax numbers against a provided list of valid numbers. The results can be exported to Excel, HTML, or output to the console. .PARAMETER Users Specifies an array of users to test. If not provided, the function retrieves all users in Microsoft 365. .PARAMETER TenantID The ID of the tenant to connect to. Required if using app-only authentication. .PARAMETER ClientID The ID of the client to use for app-only authentication. Required if using app-only authentication. .PARAMETER CertificateThumbprint The thumbprint of the certificate to use for app-only authentication. Required if using app-only authentication. .PARAMETER AccessToken The access token to use for authentication. Required if using app-only authentication. .PARAMETER InteractiveLogin Specifies whether to use interactive login. If this switch is present, interactive login will be used. Otherwise, app-only authentication will be used. .PARAMETER ValidationExcelFilePath Specifies the path to an Excel file containing a list of valid fax numbers. If provided, the function validates the users' fax numbers against this list. .PARAMETER OutputExcelFilePath Specifies the path to export the results to an Excel file. If specified, the function exports the results using the Export-365ACResultToExcel function. .PARAMETER OutputHtmlFilePath Specifies the path to export the results to an HTML file. If specified, the function exports the results using the Export-365ACResultToHtml function. .PARAMETER TestedProperty Specifies the property being tested. Defaults to 'Has Fax Number' but changes to 'Has Valid Fax Number' if a validation list is provided. .EXAMPLE Test-365ACFaxNumber -Users (Get-MgUser -All) -OutputExcelFilePath "C:\Results.xlsx" Tests all users for a fax number and exports the results to an Excel file. .EXAMPLE Test-365ACFaxNumber -Users $users -OutputHtmlFilePath "C:\Results.html" Tests the specified users for a fax number and exports the results to an HTML file. .NOTES - Requires the ImportExcel module for exporting results to Excel. If not installed, an error will be displayed. - The Export-365ACResultToExcel and Export-365ACResultToHtml functions must be defined for exporting results. .LINK https://github.com/DevClate/365AutomatedCheck #> Function Test-365ACFaxNumber { [CmdletBinding()] param ( [Parameter(ValueFromPipeline = $true)] [array]$Users = (get-mguser -all -Property DisplayName, FaxNumber | Select-Object DisplayName, FaxNumber), [Parameter(Mandatory = $false)] [string]$TenantID, [Parameter(Mandatory = $false)] [string]$ClientID, [Parameter(Mandatory = $false)] [string]$CertificateThumbprint, [Parameter(Mandatory = $false)] [string]$AccessToken, [Parameter(Mandatory = $false)] [switch]$InteractiveLogin, [ValidatePattern('\.xlsx$')] [string]$ValidationExcelFilePath, [ValidatePattern('\.xlsx$')] [string]$OutputExcelFilePath, [ValidatePattern('\.html$')] [string]$OutputHtmlFilePath, [string]$TestedProperty = 'Has Fax Number' ) BEGIN { $validFaxNumbers = @() if ($ValidationExcelFilePath) { if (!(Get-Command Import-Excel -ErrorAction SilentlyContinue)) { Stop-PSFFunction -Message "Import-Excel cmdlet not found. Please install the ImportExcel module." -ErrorRecord $_ -Tag 'MissingModule' return } # Import the Excel file to get valid fax numbers $validFaxNumbers = Import-Excel -Path $ValidationExcelFilePath | Select-Object -ExpandProperty FaxNumber -Unique } if ($InteractiveLogin) { Write-PSFMessage "Using interactive login..." -Level Host Connect-MgGraph -Scopes "User.Read.All", "AuditLog.read.All" -NoWelcome } else { Write-PSFMessage "Using app-only authentication..." -Level Host Connect-MgGraph -ClientId $ClientID -TenantId $TenantID -CertificateThumbprint $CertificateThumbprint -Scopes "User.Read.All", "AuditLog.Read.All" } $results = @() } PROCESS { $columnName = $ValidationExcelFilePath ? 'Has Valid Fax Number' : 'Has Fax Number' foreach ($user in $Users) { $hasFaxNumber = [bool]($user.FaxNumber) if ($ValidationExcelFilePath) { $hasFaxNumber = $user.FaxNumber -in $validFaxNumbers } $result = [PSCustomObject]@{ 'User Display Name' = $user.DisplayName $columnName = $hasFaxNumber } $results += $result } } END { $totalTests = $results.Count $passedTests = ($results | Where-Object { $_.$columnName }).Count $failedTests = $totalTests - $passedTests if ($OutputExcelFilePath) { Export-365ACResultToExcel -Results $results -OutputExcelFilePath $OutputExcelFilePath -TotalTests $totalTests -PassedTests $passedTests -FailedTests $failedTests -TestedProperty $columnName } elseif ($OutputHtmlFilePath) { Export-365ACResultToHtml -Results $results -OutputHtmlFilePath $OutputHtmlFilePath -TotalTests $totalTests -PassedTests $passedTests -FailedTests $failedTests -TestedProperty $columnName } else { Write-PSFMessage -Level Output -Message ($results | Out-String) } } }
Test-365ACEmployeeID.ps1
365AutomatedCheck-0.0.11
<# .SYNOPSIS Tests if users have an Employee ID assigned in their Microsoft 365 profiles. .DESCRIPTION The Test-365ACEmployeeID function checks each user retrieved from Microsoft 365 for an Employee ID value. It processes a list of users, determining whether each user has an Employee ID assigned. The results can be exported to an Excel file, an HTML file, or output directly. .PARAMETER Users An array of users to be tested. This can be piped in or specified directly. Each user should have DisplayName and EmployeeId properties. .PARAMETER TenantID The ID of the tenant to connect to. Required if using app-only authentication. .PARAMETER ClientID The ID of the client to use for app-only authentication. Required if using app-only authentication. .PARAMETER CertificateThumbprint The thumbprint of the certificate to use for app-only authentication. Required if using app-only authentication. .PARAMETER AccessToken The access token to use for authentication. Required if using app-only authentication. .PARAMETER InteractiveLogin Specifies whether to use interactive login. If this switch is present, interactive login will be used. Otherwise, app-only authentication will be used. .PARAMETER OutputExcelFilePath The file path where the Excel report will be saved. The file must have an .xlsx extension. .PARAMETER OutputHtmlFilePath The file path where the HTML report will be saved. The file must have an .html extension. .PARAMETER TestedProperty The property being tested. This is set to 'Has Employee ID' by default. .EXAMPLE $users = Get-MgUser -All -Property DisplayName, EmployeeId | Select-Object DisplayName, EmployeeId Test-365ACEmployeeID -Users $users -OutputExcelFilePath "C:\Reports\EmployeeIDReport.xlsx" This example retrieves all users with their DisplayName and EmployeeId, then tests each user to see if they have an Employee ID assigned. The results are exported to an Excel file. .EXAMPLE Get-MgUser -All -Property DisplayName, EmployeeId | Select-Object DisplayName, EmployeeId | Test-365ACEmployeeID -OutputHtmlFilePath "C:\Reports\EmployeeIDReport.html" This example pipes a list of users directly into Test-365ACEmployeeID, which then checks if each user has an Employee ID assigned. The results are exported to an HTML file. .NOTES This function requires the Microsoft Graph PowerShell SDK to retrieve user information from Microsoft 365. .LINK https://docs.microsoft.com/powershell/module/microsoft.graph.users/get-mguser #> Function Test-365ACEmployeeID { [CmdletBinding()] param ( [Parameter(ValueFromPipeline = $true)] [array]$Users = (Get-MgUser -All -Property DisplayName, EmployeeId | Select-Object DisplayName, EmployeeId), [Parameter(Mandatory = $false)] [string]$TenantID, [Parameter(Mandatory = $false)] [string]$ClientID, [Parameter(Mandatory = $false)] [string]$CertificateThumbprint, [Parameter(Mandatory = $false)] [string]$AccessToken, [Parameter(Mandatory = $false)] [switch]$InteractiveLogin, [ValidatePattern('\.xlsx$')] [string]$OutputExcelFilePath, [ValidatePattern('\.html$')] [string]$OutputHtmlFilePath, [string]$TestedProperty = 'Has Employee ID' ) BEGIN { if ($InteractiveLogin) { Write-PSFMessage "Using interactive login..." -Level Host Connect-MgGraph -Scopes "User.Read.All", "AuditLog.read.All" -NoWelcome } else { Write-PSFMessage "Using app-only authentication..." -Level Host Connect-MgGraph -ClientId $ClientID -TenantId $TenantID -CertificateThumbprint $CertificateThumbprint -Scopes "User.Read.All", "AuditLog.Read.All" } $results = @() } PROCESS { foreach ($user in $Users) { $hasEmployeeId = [bool]($user.EmployeeId) $result = [PSCustomObject]@{ 'User Display Name' = $user.DisplayName $TestedProperty = $hasEmployeeId } $results += $result } } END { $totalTests = $results.Count $passedTests = ($results | Where-Object { $_.$TestedProperty }).Count $failedTests = $totalTests - $passedTests if ($OutputExcelFilePath) { Export-365ACResultToExcel -Results $results -OutputExcelFilePath $OutputExcelFilePath -TotalTests $totalTests -PassedTests $passedTests -FailedTests $failedTests -TestedProperty $TestedProperty } elseif ($OutputHtmlFilePath) { Export-365ACResultToHtml -Results $results -OutputHtmlFilePath $OutputHtmlFilePath -TotalTests $totalTests -PassedTests $passedTests -FailedTests $failedTests -TestedProperty $TestedProperty } else { Write-Output $results } } }
Test-365ACJobTitle.ps1
365AutomatedCheck-0.0.11
<# .SYNOPSIS Tests if users have a job title assigned and exports the results. .DESCRIPTION The Test-365ACJobTitle function checks if users in Microsoft 365 have a job title assigned. It can validate job titles against a list of valid titles if provided. The results can be exported to Excel, HTML, or output to the console. .PARAMETER Users Specifies an array of users to test. If not provided, the function tests all users in Microsoft 365. .PARAMETER TenantID The ID of the tenant to connect to. Required if using app-only authentication. .PARAMETER ClientID The ID of the client to use for app-only authentication. Required if using app-only authentication. .PARAMETER CertificateThumbprint The thumbprint of the certificate to use for app-only authentication. Required if using app-only authentication. .PARAMETER AccessToken The access token to use for authentication. Required if using app-only authentication. .PARAMETER InteractiveLogin Specifies whether to use interactive login. If this switch is present, interactive login will be used. Otherwise, app-only authentication will be used. .PARAMETER ValidationExcelFilePath Specifies the path to an Excel file containing a list of valid job titles. If provided, the function validates each user's job title against this list. .PARAMETER OutputExcelFilePath Specifies the path to export the results to an Excel file. If specified, the function exports the results using the Export-365ACResultToExcel function. .PARAMETER OutputHtmlFilePath Specifies the path to export the results to an HTML file. If specified, the function exports the results using the Export-365ACResultToHtml function. .PARAMETER TestedProperty Specifies the property being tested. Defaults to 'Has Job Title'. .EXAMPLE Test-365ACJobTitle -Users (Get-MgUser -All) -OutputExcelFilePath "C:\Results.xlsx" Tests all users for a job title and exports the results to an Excel file. .EXAMPLE Test-365ACJobTitle -Users $users -OutputHtmlFilePath "C:\Results.html" Tests the specified users for a job title and exports the results to an HTML file. .NOTES - Requires the ImportExcel module for exporting results to Excel. If not installed, an error will be displayed. - The Export-365ACResultToExcel and Export-365ACResultToHtml functions must be defined for exporting results. .LINK https://github.com/DevClate/365AutomatedCheck #> function Test-365ACJobTitle { [CmdletBinding()] param ( [Parameter(ValueFromPipeline=$true)] [array]$Users = (Get-MgUser -All -Property DisplayName, JobTitle), [Parameter(Mandatory = $false)] [string]$TenantID, [Parameter(Mandatory = $false)] [string]$ClientID, [Parameter(Mandatory = $false)] [string]$CertificateThumbprint, [Parameter(Mandatory = $false)] [string]$AccessToken, [Parameter(Mandatory = $false)] [switch]$InteractiveLogin, [ValidatePattern('\.xlsx$')] [string]$ValidationExcelFilePath, [ValidatePattern('\.xlsx$')] [string]$OutputExcelFilePath, [ValidatePattern('\.html$')] [string]$OutputHtmlFilePath, [string]$TestedProperty = 'Has Job Title' ) BEGIN { $validJobTitles = @() if ($ValidationExcelFilePath) { if (!(Get-Command Import-Excel -ErrorAction SilentlyContinue)) { Stop-PSFFunction -Message "Import-Excel cmdlet not found. Please install the ImportExcel module." -ErrorRecord $_ -Tag 'MissingModule' return } # Import the Excel file to get valid job titles $validJobTitles = Import-Excel -Path $ValidationExcelFilePath | Select-Object -ExpandProperty Title -Unique } if ($InteractiveLogin) { Write-PSFMessage "Using interactive login..." -Level Host Connect-MgGraph -Scopes "User.Read.All", "AuditLog.read.All" -NoWelcome } else { Write-PSFMessage "Using app-only authentication..." -Level Host Connect-MgGraph -ClientId $ClientID -TenantId $TenantID -CertificateThumbprint $CertificateThumbprint -Scopes "User.Read.All", "AuditLog.Read.All" } $results = @() } PROCESS { $columnName = $ValidationExcelFilePath ? 'Has Valid Job Title' : 'Has Job Title' foreach ($user in $Users) { $hasJobTitle = [bool]($user.JobTitle) if ($ValidationExcelFilePath) { $hasJobTitle = $user.JobTitle -in $validJobTitles } $result = [PSCustomObject]@{ 'User Display Name' = $user.DisplayName $columnName = $hasJobTitle } $results += $result } } END { $totalTests = $results.Count $passedTests = ($results | Where-Object { $_.$columnName }).Count $failedTests = $totalTests - $passedTests if ($OutputExcelFilePath) { Export-365ACResultToExcel -Results $results -OutputExcelFilePath $OutputExcelFilePath -TotalTests $totalTests -PassedTests $passedTests -FailedTests $failedTests -TestedProperty $columnName } elseif ($OutputHtmlFilePath) { Export-365ACResultToHtml -Results $results -OutputHtmlFilePath $OutputHtmlFilePath -TotalTests $totalTests -PassedTests $passedTests -FailedTests $failedTests -TestedProperty $columnName } else { Write-PSFMessage -Level Output -Message ($results | Out-String) } } }
Test-365ACAccountEnabled.ps1
365AutomatedCheck-0.0.11
<# .SYNOPSIS Tests if users' accounts are enabled in their Microsoft 365 profiles. .DESCRIPTION The Test-365ACAccountEnabled function checks each user retrieved from Microsoft 365 to determine if their account is enabled. It processes a list of users, determining the enabled status of each user's account. The results can be exported to an Excel file, an HTML file, or output directly. .PARAMETER Users An array of users to be tested. This can be piped in or specified directly. Each user should have DisplayName and AccountEnabled properties. .PARAMETER TenantID The ID of the tenant to connect to. Required if using app-only authentication. .PARAMETER ClientID The ID of the client to use for app-only authentication. Required if using app-only authentication. .PARAMETER CertificateThumbprint The thumbprint of the certificate to use for app-only authentication. Required if using app-only authentication. .PARAMETER AccessToken The access token to use for authentication. Required if using app-only authentication. .PARAMETER InteractiveLogin Specifies whether to use interactive login. If this switch is present, interactive login will be used. Otherwise, app-only authentication will be used. .PARAMETER OutputExcelFilePath The file path where the Excel report will be saved. The file must have an .xlsx extension. .PARAMETER OutputHtmlFilePath The file path where the HTML report will be saved. The file must have an .html extension. .PARAMETER TestedProperty The property being tested. This is set to 'Is Account Enabled' by default. .EXAMPLE PS> $users = Get-MgUser -All -Property DisplayName, AccountEnabled | Select-Object DisplayName, AccountEnabled PS> Test-365ACAccountEnabled -Users $users -OutputExcelFilePath "C:\Reports\AccountEnabledReport.xlsx" This example retrieves all users with their DisplayName and AccountEnabled status, then tests each user to see if their account is enabled. The results are exported to an Excel file. .EXAMPLE PS> Get-MgUser -All -Property DisplayName, AccountEnabled | Select-Object DisplayName, AccountEnabled | Test-365ACAccountEnabled -OutputHtmlFilePath "C:\Reports\AccountEnabledReport.html" This example pipes a list of users directly into Test-365ACAccountEnabled, which then checks if each user's account is enabled. The results are exported to an HTML file. .NOTES This function requires the Microsoft Graph PowerShell SDK to retrieve user information from Microsoft 365. .LINK https://docs.microsoft.com/powershell/module/microsoft.graph.users/get-mguser #> Function Test-365ACAccountEnabled { [CmdletBinding()] param ( [Parameter(ValueFromPipeline = $true)] [array]$Users = (Get-MgUser -All -Property DisplayName, AccountEnabled | Select-Object DisplayName, AccountEnabled), [Parameter(Mandatory = $false)] [string]$TenantID, [Parameter(Mandatory = $false)] [string]$ClientID, [Parameter(Mandatory = $false)] [string]$CertificateThumbprint, [Parameter(Mandatory = $false)] [string]$AccessToken, [Parameter(Mandatory = $false)] [switch]$InteractiveLogin, [ValidatePattern('\.xlsx$')] [string]$OutputExcelFilePath, [ValidatePattern('\.html$')] [string]$OutputHtmlFilePath, [string]$TestedProperty = 'Is Account Enabled' ) BEGIN { if ($InteractiveLogin) { Write-PSFMessage "Using interactive login..." -Level Host Connect-MgGraph -Scopes "User.Read.All", "AuditLog.read.All" -NoWelcome } else { Write-PSFMessage "Using app-only authentication..." -Level Host Connect-MgGraph -ClientId $ClientID -TenantId $TenantID -CertificateThumbprint $CertificateThumbprint -Scopes "User.Read.All", "AuditLog.Read.All" } $results = @() } PROCESS { foreach ($user in $Users) { $isAccountEnabled = [bool]($user.AccountEnabled) $result = [PSCustomObject]@{ 'User Display Name' = $user.DisplayName $TestedProperty = $isAccountEnabled } $results += $result } } END { $totalTests = $results.Count $passedTests = ($results | Where-Object { $_.$TestedProperty }).Count $failedTests = $totalTests - $passedTests if ($OutputExcelFilePath) { Export-365ACResultToExcel -Results $results -OutputExcelFilePath $OutputExcelFilePath -TotalTests $totalTests -PassedTests $passedTests -FailedTests $failedTests -TestedProperty $TestedProperty } elseif ($OutputHtmlFilePath) { Export-365ACResultToHtml -Results $results -OutputHtmlFilePath $OutputHtmlFilePath -TotalTests $totalTests -PassedTests $passedTests -FailedTests $failedTests -TestedProperty $TestedProperty } else { Write-Output $results } } }
Test-365ACCity.ps1
365AutomatedCheck-0.0.11
<# .SYNOPSIS Tests if users have a city property and generates test results. .DESCRIPTION The Test-365ACCity function tests if users have a city property and generates test results. It takes an array of users as input and checks if each user has a city property. The test results are stored in an array of custom objects, which include the user's display name and the result of the test. .PARAMETER Users Specifies the array of users to test. Each user should have a DisplayName and City property. .PARAMETER TenantID The ID of the tenant to connect to. Required if using app-only authentication. .PARAMETER ClientID The ID of the client to use for app-only authentication. Required if using app-only authentication. .PARAMETER CertificateThumbprint The thumbprint of the certificate to use for app-only authentication. Required if using app-only authentication. .PARAMETER AccessToken The access token to use for authentication. Required if using app-only authentication. .PARAMETER InteractiveLogin Specifies whether to use interactive login. If this switch is present, interactive login will be used. Otherwise, app-only authentication will be used. .PARAMETER OutputExcelFilePath Specifies the path to the output Excel file. If provided, the test results will be exported to an Excel file. .PARAMETER OutputHtmlFilePath Specifies the path to the output HTML file. If provided, the test results will be exported to an HTML file. .PARAMETER TestedProperty Specifies the name of the tested property. Default value is 'Has City'. .INPUTS An array of users with DisplayName and City properties. .OUTPUTS If OutputExcelFilePath or OutputHtmlFilePath is not provided, the function outputs an array of custom objects with the user's display name and the result of the test. .EXAMPLE $users = Get-MgUser -All -Property DisplayName, City | Select-Object DisplayName, City Test-365ACCity -Users $users -OutputExcelFilePath 'C:\TestResults.xlsx' This example tests if the users have a city property and exports the test results to an Excel file. #> Function Test-365ACCity { [CmdletBinding()] param ( [Parameter(ValueFromPipeline = $true)] [array]$Users = (Get-MgUser -All -Property DisplayName, City | Select-Object DisplayName, City), [Parameter(Mandatory = $false)] [string]$TenantID, [Parameter(Mandatory = $false)] [string]$ClientID, [Parameter(Mandatory = $false)] [string]$CertificateThumbprint, [Parameter(Mandatory = $false)] [string]$AccessToken, [Parameter(Mandatory = $false)] [switch]$InteractiveLogin, [ValidatePattern('\.xlsx$')] [string]$OutputExcelFilePath, [ValidatePattern('\.html$')] [string]$OutputHtmlFilePath, [string]$TestedProperty = 'Has City' ) BEGIN { if ($InteractiveLogin) { Write-PSFMessage "Using interactive login..." -Level Host Connect-MgGraph -Scopes "User.Read.All", "AuditLog.read.All" -NoWelcome } else { Write-PSFMessage "Using app-only authentication..." -Level Host Connect-MgGraph -ClientId $ClientID -TenantId $TenantID -CertificateThumbprint $CertificateThumbprint -Scopes "User.Read.All", "AuditLog.Read.All" } $results = @() } PROCESS { foreach ($user in $Users) { $hasCity = [bool]($user.City) $result = [PSCustomObject]@{ 'User Display Name' = $user.DisplayName $TestedProperty = $hasCity } $results += $result } } END { $totalTests = $results.Count $passedTests = ($results | Where-Object { $_.$TestedProperty }).Count $failedTests = $totalTests - $passedTests if ($OutputExcelFilePath) { Export-365ACResultToExcel -Results $results -OutputExcelFilePath $OutputExcelFilePath -TotalTests $totalTests -PassedTests $passedTests -FailedTests $failedTests -TestedProperty $TestedProperty } elseif ($OutputHtmlFilePath) { Export-365ACResultToHtml -Results $results -OutputHtmlFilePath $OutputHtmlFilePath -TotalTests $totalTests -PassedTests $passedTests -FailedTests $failedTests -TestedProperty $TestedProperty } else { Write-Output $results } } }
Test-365ACPostalCode.ps1
365AutomatedCheck-0.0.11
<# .SYNOPSIS Tests if users have a postal code assigned in their Microsoft 365 profiles. .DESCRIPTION The Test-365ACPostalCode function checks each user retrieved from Microsoft 365 for a postal code value. It processes a list of users, determining whether each user has a postal code assigned. The results can be exported to an Excel file, an HTML file, or output directly. .PARAMETER Users An array of users to be tested. This can be piped in or specified directly. Each user should have DisplayName and PostalCode properties. .PARAMETER TenantID The ID of the tenant to connect to. Required if using app-only authentication. .PARAMETER ClientID The ID of the client to use for app-only authentication. Required if using app-only authentication. .PARAMETER CertificateThumbprint The thumbprint of the certificate to use for app-only authentication. Required if using app-only authentication. .PARAMETER AccessToken The access token to use for authentication. Required if using app-only authentication. .PARAMETER InteractiveLogin Specifies whether to use interactive login. If this switch is present, interactive login will be used. Otherwise, app-only authentication will be used. .PARAMETER OutputExcelFilePath The file path where the Excel report will be saved. The file must have an .xlsx extension. .PARAMETER OutputHtmlFilePath The file path where the HTML report will be saved. The file must have an .html extension. .PARAMETER TestedProperty The property being tested. This is set to 'Has Postal Code' by default. .EXAMPLE PS> $users = Get-MgUser -All -Property DisplayName, PostalCode | Select-Object DisplayName, PostalCode PS> Test-365ACPostalCode -Users $users -OutputExcelFilePath "C:\Reports\PostalCodeReport.xlsx" This example retrieves all users with their DisplayName and PostalCode, then tests each user to see if they have a postal code assigned. The results are exported to an Excel file. .EXAMPLE PS> Get-MgUser -All -Property DisplayName, PostalCode | Select-Object DisplayName, PostalCode | Test-365ACPostalCode -OutputHtmlFilePath "C:\Reports\PostalCodeReport.html" This example pipes a list of users directly into Test-365ACPostalCode, which then checks if each user has a postal code assigned. The results are exported to an HTML file. .NOTES This function requires the Microsoft Graph PowerShell SDK to retrieve user information from Microsoft 365. .LINK https://github.com/DevClate/365AutomatedCheck #> Function Test-365ACPostalCode { [CmdletBinding()] param ( [Parameter(ValueFromPipeline = $true)] [array]$Users = (Get-MgUser -All -Property DisplayName, PostalCode | Select-Object DisplayName, PostalCode), [Parameter(Mandatory = $false)] [string]$TenantID, [Parameter(Mandatory = $false)] [string]$ClientID, [Parameter(Mandatory = $false)] [string]$CertificateThumbprint, [Parameter(Mandatory = $false)] [string]$AccessToken, [Parameter(Mandatory = $false)] [switch]$InteractiveLogin, [ValidatePattern('\.xlsx$')] [string]$OutputExcelFilePath, [ValidatePattern('\.html$')] [string]$OutputHtmlFilePath, [string]$TestedProperty = 'Has Postal Code' ) BEGIN { if ($InteractiveLogin) { Write-PSFMessage "Using interactive login..." -Level Host Connect-MgGraph -Scopes "User.Read.All", "AuditLog.read.All" -NoWelcome } else { Write-PSFMessage "Using app-only authentication..." -Level Host Connect-MgGraph -ClientId $ClientID -TenantId $TenantID -CertificateThumbprint $CertificateThumbprint -Scopes "User.Read.All", "AuditLog.Read.All" } $results = @() } PROCESS { foreach ($user in $Users) { $hasPostalCode = [bool]($user.PostalCode) $result = [PSCustomObject]@{ 'User Display Name' = $user.DisplayName $TestedProperty = $hasPostalCode } $results += $result } } END { $totalTests = $results.Count $passedTests = ($results | Where-Object { $_.$TestedProperty }).Count $failedTests = $totalTests - $passedTests if ($OutputExcelFilePath) { Export-365ACResultToExcel -Results $results -OutputExcelFilePath $OutputExcelFilePath -TotalTests $totalTests -PassedTests $passedTests -FailedTests $failedTests -TestedProperty $TestedProperty } elseif ($OutputHtmlFilePath) { Export-365ACResultToHtml -Results $results -OutputHtmlFilePath $OutputHtmlFilePath -TotalTests $totalTests -PassedTests $passedTests -FailedTests $failedTests -TestedProperty $TestedProperty } else { Write-Output $results } } }
Test-365ACLastLogin.ps1
365AutomatedCheck-0.0.11
<# .SYNOPSIS Tests the last login activity of users in Microsoft 365. .DESCRIPTION The Test-365ACLastLogin function tests the last login activity of users in Microsoft 365. It retrieves the required properties of users, calculates the number of inactive days, and determines if a user has logged in within a specified number of days. The function then generates a report of the test results. .PARAMETER TenantID The ID of the tenant to connect to. This parameter is optional. .PARAMETER ClientID The ID of the client to use for app-only authentication. This parameter is optional. .PARAMETER CertificateThumbprint The thumbprint of the certificate to use for app-only authentication. This parameter is optional. .PARAMETER AccessToken The access token to use for authentication. This parameter is optional. .PARAMETER InteractiveLogin Specifies whether to use interactive login. If this switch is present, interactive login will be used. Otherwise, app-only authentication will be used. .PARAMETER Days The number of days to consider a user as inactive. The default value is 30. .PARAMETER TestedProperty The name of the tested property. The default value is "Has Logged In Last <Days> Days". .PARAMETER OutputExcelFilePath The path to the output Excel file. The file should have a .xlsx extension. This parameter is optional. .PARAMETER HtmlFilePath The path to the output HTML file. The file should have a .html extension. This parameter is optional. .EXAMPLE Test-365ACLastLogin -TenantID "contoso.onmicrosoft.com" -ClientID "12345678-1234-1234-1234-1234567890ab" -CertificateThumbprint "AB12AB34AB56AB78AB90AB12AB34AB56AB78AB90" -Days 60 -OutputExcelFilePath "C:\Reports\LastLoginReport.xlsx" Tests the last login activity of users in the "contoso.onmicrosoft.com" tenant using app-only authentication with the specified client ID and certificate thumbprint. Users who have not logged in within the last 60 days will be considered inactive. The test results will be exported to an Excel file located at "C:\Reports\LastLoginReport.xlsx". .EXAMPLE Test-365ACLastLogin -InteractiveLogin -Days 90 -OutputHtmlFilePath "C:\Reports\LastLoginReport.html" Tests the last login activity of users using interactive login. Users who have not logged in within the last 90 days will be considered inactive. The test results will be exported to an HTML file located at "C:\Reports\LastLoginReport.html". #> Function Test-365ACLastLogin { [CmdletBinding()] param ( [Parameter(Mandatory = $false)] [string]$TenantID, [Parameter(Mandatory = $false)] [string]$ClientID, [Parameter(Mandatory = $false)] [string]$CertificateThumbprint, [Parameter(Mandatory = $false)] [string]$AccessToken, [Parameter(Mandatory = $false)] [switch]$InteractiveLogin, [int]$Days = 30, [string]$TestedProperty = "Has Logged In Last $($Days) Days", [ValidatePattern('\.xlsx$')] [string]$OutputExcelFilePath, [ValidatePattern('\.html$')] [string]$OutputHtmlFilePath ) BEGIN { if ($InteractiveLogin) { Write-PSFMessage "Using interactive login..." -Level Host Connect-MgGraph -Scopes "User.Read.All", "AuditLog.read.All" -NoWelcome } else { Write-PSFMessage "Using app-only authentication..." -Level Host Connect-MgGraph -ClientId $ClientID -TenantId $TenantID -CertificateThumbprint $CertificateThumbprint -Scopes "User.Read.All", "AuditLog.Read.All" } $results = @() } PROCESS { $Count = 0 $PrintedUser = 0 $columnName = $TestedProperty #Retrieve users $RequiredProperties = @('UserPrincipalName', 'DisplayName', 'CreatedDateTime', 'AccountEnabled', 'Department', 'JobTitle', 'SigninActivity') Get-MgBetaUser -All -Property $RequiredProperties | Select-Object $RequiredProperties | ForEach-Object { $Print = 1 # Initialize $Print to 1 at the start of each iteration $Count++ # $UPN = $_.UserPrincipalName - use in future $LastSuccessfulSigninDate = $_.SignInActivity.lastSuccessfulSignInDateTime # $AccountEnabled = $_.AccountEnabled - use in future $DisplayName = $_.DisplayName #Calculate Inactive days if ($null -eq $LastSuccessfulSigninDate) { $hasLoggedIn = $false } else { $InactiveUserDays = (New-TimeSpan -Start $LastSuccessfulSigninDate).Days $hasLoggedIn = $InactiveUserDays -le $Days } if ($Print -eq 1) { $PrintedUser++ $result = [PSCustomObject]@{ "User Display Name" = $DisplayName $columnName = $hasLoggedIn } $results += $result } } } END { $TotalTests = $results.Count $PassedTests = ($results | Where-Object { $_.$columnName -eq $true }).Count $FailedTests = $TotalTests - $PassedTests if ($OutputExcelFilePath) { Export-365ACResultToExcel -Results $results -OutputExcelFilePath $OutputExcelFilePath -TotalTests $TotalTests -PassedTests $PassedTests -FailedTests $FailedTests -TestedProperty $columnName } elseif ($OutputHtmlFilePath) { Export-365ACResultToHtml -Results $results -OutputHtmlFilePath $OutputHtmlFilePath -TotalTests $TotalTests -PassedTests $PassedTests -FailedTests $FailedTests -TestedProperty $columnName } else { Write-PSFMessage -Level Output -Message ($results | Out-String) } Disconnect-MgGraph } }
Convert-365ACXmlToHtml.ps1
365AutomatedCheck-0.0.11
<# .SYNOPSIS Converts an XML file to an HTML file using an XSLT transformation. .DESCRIPTION The Convert-365ACXmlToHtml function takes an XML file, an XSLT file, and an output HTML file path as input parameters. It performs an XSLT transformation on the XML file using the specified XSLT file and generates an HTML report at the specified output path. .PARAMETER XmlPath The path to the XML file that needs to be transformed. .PARAMETER XsltPath The path to the XSLT file that defines the transformation rules. .PARAMETER OutputHtmlPath The path to the output HTML file that will be generated. .EXAMPLE Convert-365ACXmlToHtml -XmlPath "C:\Path\To\Input.xml" -XsltPath "C:\Path\To\Transform.xslt" -OutputHtmlPath "C:\Path\To\Output.html" This example demonstrates how to use the Convert-365ACXmlToHtml function to convert an XML file to an HTML file using a specified XSLT transformation. .NOTES This function requires the System.Xml.Xsl.XslCompiledTransform and System.Xml.XmlDocument classes from the .NET Framework. .LINK https://docs.microsoft.com/en-us/dotnet/api/system.xml.xsl.xslcompiledtransform?view=net-5.0 #> function Convert-365ACXmlToHtml { param ( [string] $XmlPath, [string] $XsltPath, [string] $OutputHtmlPath ) if (Test-Path -Path $XmlPath) { Write-PSFMessage -Level Host -Message "XML file generated: $XmlPath" $xslt = New-Object System.Xml.Xsl.XslCompiledTransform $xslt.Load($XsltPath) $xml = New-Object System.Xml.XmlDocument $xml.Load($XmlPath) $writer = New-Object System.IO.StringWriter $xslt.Transform($xml, $null, $writer) # Ensure the directory for $OutputHtmlPath exists $directoryPath = [System.IO.Path]::GetDirectoryName($OutputHtmlPath) if (-not (Test-Path -Path $directoryPath)) { $null = New-Item -ItemType Directory -Path $directoryPath -Force Write-Output "New folder path created: $directoryPath" } $writer.ToString() | Out-File $OutputHtmlPath Write-PSFMessage -Level Host -Message "HTML report generated: $OutputHtmlPath" } else { Write-PSFMessage -Level Warning -Message "The XML file '$XmlPath' does not exist." } }
365AutomatedCheck.psd1
365AutomatedCheck-0.0.11
# # Module manifest for module '365AutomatedCheck' # # Generated by: Clayton Tyger # # Generated on: 6/14/2024 # @{ # Script module or binary module file associated with this manifest. RootModule = '365AutomatedCheck.psm1' # Version number of this module. ModuleVersion = '0.0.11' # Supported PSEditions CompatiblePSEditions = 'Core' # ID used to uniquely identify this module GUID = 'a745cd66-f76c-4767-8b3c-69993a604b80' # Author of this module Author = 'Clayton Tyger' # Company or vendor of this module CompanyName = 'Clayton Tyger' # Copyright statement for this module Copyright = '(c) Clayton Tyger. All rights reserved.' # Description of the functionality provided by this module Description = 'This module checks for your fields in your Office 365 tenant to see if they meet company standards.' # Minimum version of the PowerShell engine required by this module PowerShellVersion = '7.1' # Name of the PowerShell host required by this module # PowerShellHostName = '' # Minimum version of the PowerShell host required by this module # PowerShellHostVersion = '' # Minimum version of Microsoft .NET Framework required by this module. This prerequisite is valid for the PowerShell Desktop edition only. # DotNetFrameworkVersion = '' # Minimum version of the common language runtime (CLR) required by this module. This prerequisite is valid for the PowerShell Desktop edition only. # ClrVersion = '' # Processor architecture (None, X86, Amd64) required by this module # ProcessorArchitecture = '' # Modules that must be imported into the global environment prior to importing this module RequiredModules = @( @{ ModuleName='ImportExcel'; ModuleVersion='7.8.2' } @{ ModuleName='ExchangeOnlineManagement'; ModuleVersion='2.0.6' } @{ ModuleName='Microsoft.Graph.Users'; ModuleVersion='1.17.0' } @{ ModuleName='Microsoft.Graph.Groups'; ModuleVersion='1.17.0' } @{ ModuleName='Microsoft.Graph.Identity.DirectoryManagement'; ModuleVersion='1.17.0' } @{ ModuleName='Microsoft.Graph.Users.Actions'; ModuleVersion='1.17.0' } @{ ModuleName='PSFramework'; ModuleVersion='1.8.289' } @{ ModuleName='Pester'; ModuleVersion='5.3.0' } ) # Assemblies that must be loaded prior to importing this module # RequiredAssemblies = @() # Script files (.ps1) that are run in the caller's environment prior to importing this module. # ScriptsToProcess = @() # Type files (.ps1xml) to be loaded when importing this module # TypesToProcess = @() # Format files (.ps1xml) to be loaded when importing this module # FormatsToProcess = @() # Modules to import as nested modules of the module specified in RootModule/ModuleToProcess # NestedModules = @() # Functions to export from this module, for best performance, do not use wildcards and do not delete the entry, use an empty array if there are no functions to export. FunctionsToExport = @( 'Invoke-365AutomatedCheck', 'Test-365ACMobilePhone', 'Export-365ACResultToHtml', 'Test-365ACCompanyName', 'Export-365ACResultToExcel', 'Test-365ACDepartment', 'Test-365ACFaxNumber', 'Test-365ACJobTitle', 'Convert-365ACXmlToHtml', 'Get-365ACPesterConfiguration', 'Set-365ACDefaultOutputPath', 'Test-365ACCountry', 'Test-365ACStreetAddress', 'Test-365ACCity', 'Test-365ACState', 'Test-365ACPostalCode', 'Test-365ACMailNickName', 'Test-365ACAccountEnabled', 'Test-365ACEmployeeID', 'Test-365ACAddressBook', 'Test-365ACLastLogin' ) # Cmdlets to export from this module, for best performance, do not use wildcards and do not delete the entry, use an empty array if there are no cmdlets to export. CmdletsToExport = @() # Variables to export from this module VariablesToExport = '*' # Aliases to export from this module, for best performance, do not use wildcards and do not delete the entry, use an empty array if there are no aliases to export. AliasesToExport = @() # DSC resources to export from this module # DscResourcesToExport = @() # List of all modules packaged with this module # ModuleList = @() # List of all files packaged with this module # FileList = @() # Private data to pass to the module specified in RootModule/ModuleToProcess. This may also contain a PSData hashtable with additional module metadata used by PowerShell. PrivateData = @{ PSData = @{ # Tags applied to this module. These help with module discovery in online galleries. Tags = @('Office365', 'Automation', 'MSGraph', 'Cloud', 'Teams', 'Configuration', 'Excel', 'Exchange', 'MacOS', 'Windows', 'PSEdition_Core') # A URL to the license for this module. # LicenseUri = '' # A URL to the main website for this project. ProjectUri = 'https://github.com/DevClate/365AutomatedCheck' # A URL to an icon representing this module. IconUri = 'https://raw.githubusercontent.com/DevClate/365AutomatedCheck/main/assets/images/365AutomatedCheckCircle-200x200.png' # ReleaseNotes of this module ReleaseNotes = 'https://github.com/DevClate/365AutomatedCheck/blob/main/changelog.md' # Prerelease string of this module # Prerelease = '' # Flag to indicate whether the module requires explicit user acceptance for install/update/save # RequireLicenseAcceptance = $false # External dependent modules of this module # ExternalModuleDependencies = @() } # End of PSData hashtable } # End of PrivateData hashtable # HelpInfo URI of this module # HelpInfoURI = '' # Default prefix for commands exported from this module. Override the default prefix using Import-Module -Prefix. # DefaultCommandPrefix = '' }
Test-UserValidation.tests.ps1
365AutomatedCheck-0.0.11
<# .SYNOPSIS Validates user properties in Microsoft 365 using PowerShell Pester tests. .DESCRIPTION This script performs validation of user properties in Microsoft 365 by leveraging the Microsoft Graph API and Pester testing framework. It supports filtering users based on their type (members, guests, etc.), enabling/disabling output to an Excel file, and customizing the domain name and Excel file path through parameters. .PARAMETER DomainName Specifies the domain name to use for user validation. Defaults to the primary domain in Microsoft 365. .PARAMETER ExcelFilePath Specifies the path to an Excel file where the validation results will be saved. If not provided, it defaults to a predefined path. .PARAMETER UserFilter Filters the users to validate based on their type. Valid options are 'all', 'members', 'guests', 'enabled', 'disabled'. Defaults to 'all'. .PARAMETER NoExcel Specifies whether to skip importing the Excel validation file. If set to $true, no Excel file will be imported. .EXAMPLE .\Test-UserValidation.tests.ps1 -NoExcel $true Validates all users in the default domain and does not generate an Excel report. .EXAMPLE .\Test-UserValidation.tests.ps1 -DomainName 'contoso.com' -ExcelFilePath 'C:\Reports\UserValidation.xlsx' Validates all users in the 'contoso.com' domain and saves the report to the specified Excel file. .NOTES Requires the Pester, ImportExcel, and Microsoft.Graph.Identity.DirectoryManagement modules. Ensure you have the necessary permissions to access user data via Microsoft Graph. #> param ( [Parameter(ValueFromPipeline = $true, ValueFromPipelineByPropertyName = $true)] [string] $DomainName = (Get-MgDomain | Where-Object { $_.IsDefault -eq $true }).Id, [Parameter(ValueFromPipeline = $true, ValueFromPipelineByPropertyName = $true)] [string] $ExcelFilePath = $env:ExcelFilePath, [Parameter(ValueFromPipeline = $true, ValueFromPipelineByPropertyName = $true)] [ValidateSet('all', 'members', 'guests', 'enabled', 'disabled')] [string] $UserFilter = 'all', [Parameter(ValueFromPipeline = $true, ValueFromPipelineByPropertyName = $true)] [bool] $NoExcel = [bool]::Parse($env:NoExcel) ) #Requires -Module Pester, ImportExcel, Microsoft.Graph.Identity.DirectoryManagement, PSFramework $properties = @( 'UserPrincipalName', 'ID', 'MobilePhone', 'JobTitle', 'StreetAddress', 'City', 'State', 'PostalCode', 'GivenName', 'Surname', 'DisplayName', 'Country', 'AssignedLicenses', 'AccountEnabled', 'CompanyName', 'Department', 'BusinessPhones', 'FaxNumber', 'UserType', 'Mail', 'EmployeeHireDate', 'EmployeeID', 'ShowInAddressList', 'SignInActivity', 'LastPasswordChangeDateTime', 'MailNickName' ) BeforeAll { # Define the default Excel file path $defaultPath = "$RootPath/assets/365ValidationParameters.xlsx" if ($NoExcel) { Write-PSFMessage -Level Output -Message "Skipping Excel file loading due to NoExcel parameter." return # } else { if (-not [string]::IsNullOrEmpty($ExcelFilePath) -and (Test-Path -Path $ExcelFilePath)) { Write-PSFMessage -Level Output -Message "Using provided Excel file path: $ExcelFilePath" } else { $ExcelFilePath = $defaultPath Write-PSFMessage -Level Output -Message "Default Excel file being used: $ExcelFilePath" } try { $excelData = Import-Excel -Path $ExcelFilePath | ForEach-Object { $_.PSObject.Properties | ForEach-Object { if ([string]::IsNullOrEmpty($_.Value)) { $_.Value = "NA" # Replace with your desired default value } } $_ # Output the modified object } } catch { Write-PSFMessage -Level Warning -Message "Error importing Excel file: $($_.Exception.Message). Using default Excel file path: $defaultPath" } } } BeforeDiscovery { # Connect to the Graph SDK with the correct permissions Connect-MgGraph -NoWelcome -Scopes AuditLog.Read.All, Directory.Read.All # Set up filter query based on the user filter parameter $filterQuery = switch ($UserFilter) { 'members' { "userType eq 'Member'" } 'guests' { "userType eq 'Guest'" } 'enabled' { "accountEnabled eq true" } 'disabled' { "accountEnabled eq false" } default { '' } } # Construct the URI with the appropriate filter $Headers = @{ConsistencyLevel = "Eventual" } $Uri = "https://graph.microsoft.com/beta/users?`$count=true&`$top=999&`$select=" + ($properties -join ',') if ($filterQuery) { $Uri += "&`$filter=$filterQuery" } [array]$Data = Invoke-MgGraphRequest -Uri $Uri -Headers $Headers [array]$Users = $Data.Value If (!($Users)) { Write-PSFMessage -Level Output -Message "Can't find any users... exiting!" ; break } # Paginate until we have all the user accounts While ($Null -ne $Data.'@odata.nextLink') { Write-PSFMessage -Level Output ("Fetching more user accounts - currently at {0}" -f $Users.count) $Uri = $Data.'@odata.nextLink' [array]$Data = Invoke-MgGraphRequest -Uri $Uri -Headers $Headers $Users = $Users + $Data.Value } Write-PSFMessage -Level Output -Message ("All available user accounts fetched ({0}) - now processing" -f $Users.count) } #Region User Fields Describe "Validating User Fields" -Tag "Entra", "Users", "All" { Context "Job Title" -Tag "Basic" -ForEach @( $Users ) { It "User $($_.DisplayName) should have a Job Title" { $_.JobTitle | Should -BeTrue -Because "Job Title is required for all users" } } Context "Street Address" -Tag "Basic", "Location" -ForEach @( $Users ) { It "User $($_.DisplayName) should have a Street Address" { $_.StreetAddress | Should -BeTrue -Because "Street Address is required for all users" } } Context "City" -Tag "Basic", "Location" -ForEach @( $Users ) { It "User $($_.DisplayName) should have a City" { $_.city | Should -BeTrue -Because "City is required for all users" } } Context "State" -Tag "Basic", "Location" -ForEach @( $Users ) { It "User $($_.DisplayName) should have a State" { $_.State | Should -BeTrue -Because "State is required for all users" } } Context "Postal Code" -Tag "Basic", "Location" -ForEach @( $Users ) { It "User $($_.DisplayName) should have a Postal Code" { $_.PostalCode | Should -BeTrue -Because "Postal Code is required for all users" } } Context "Country" -Tag "Basic", "Location" -ForEach @( $Users ) { It "User $($_.DisplayName) should have a Country" { $_.Country | Should -BeTrue -Because "Country is required for all users" } } Context "Department" -Tag "Basic" -ForEach @( $Users ) { It "User $($_.DisplayName) should have a Department" { $_.Department | Should -BeTrue -Because "Department is required for all users" } } Context "Office Location" -Tag "Basic" -ForEach @( $Users ) { It "User $($_.DisplayName) should have an Office Location" { $_.OfficeLocation | Should -BeTrue -Because "Office Location is required for all users" } } Context "Assigned Licenses" -Tag "Basic" -ForEach @( $Users ) { It "User $($_.DisplayName) should have an Assigned License" { $_.AssignedLicenses | Should -BeTrue -Because "Assigned Licenses are required for all users" } } Context "Account Enabled" -Tag "Basic" -ForEach @( $Users ) { It "User $($_.DisplayName) should have an Account Enabled" { $_.AccountEnabled | Should -BeTrue -Because "Account Enabled is required for all users" } } Context "Company Name" -Tag "Basic" -ForEach @( $Users ) { It "User $($_.DisplayName) should have a Company Name" { $_.CompanyName | Should -BeTrue -Because "Company Name is required for all users" } } Context "Mobile Phone" -Tag "Basic", "Communication" -ForEach @( $Users ) { It "User $($_.DisplayName) should have a Mobile Phone Number" { $_.MobilePhone | Should -BeTrue -Because "Mobile Phone is required for all users" } } Context "Business Phone" -Tag "Basic", "Communication" -ForEach @( $Users ) { It "User $($_.DisplayName) should have a Business Phone Number" { $_.BusinessPhones | Should -BeTrue -Because "Business Phone is required for all users" } } Context "Fax Number" -Tag "Basic", "Communication" -ForEach @( $Users ) { It "User $($_.DisplayName) should have a Fax Number" { $_.FaxNumber | Should -BeTrue -Because "Fax Number is required for all users" } } Context "Manager" -Tag "Basic", "Manager" -ForEach @( $Users ) { It "User $($_.DisplayName) should have a Manager" { $_.Manager | Should -BeTrue -Because "Manager is required for all users" } } Context "Sponsors" -Tag "Basic", "Sponsor" -ForEach @( $Users ) { It "User $($_.DisplayName) should have a Sponsor" { $_.Sponsor | Should -BeTrue -Because "Sponsor is required for all users" } } Context "UPN Formatting" -Tag "Custom" -ForEach @( $Users ) { It "User $($_.DisplayName) UPN should have a first initial last name all lower case" { $firstName = $_.DisplayName $lastName = $_.Surname $expectedUPN = $firstName.Substring(0, 1).ToLower() + $lastName.ToLower() + "@$DomainName" $hascorrectformat = $_.UserPrincipalName -eq $expectedUPN $hascorrectformat | Should -BeTrue -Because "UPN should be in the format of first initial last name all lower case" } } Context "User Type" -Tag "User" -ForEach @( $Users ) { It "User $($_.DisplayName) should have a User Type" { $_.UserType | Should -Be "Member" -Because "User Type should be 'Member'" } } Context "Employee Hire Date" -Tag "HR" -ForEach @( $Users ) { It "User $($_.DisplayName) should have a Hire Date" { $_.EmployeeHireDate | Should -Not -BeNullOrEmpty -Because "Employee Hire Date should not be empty" } } Context "Employee ID" -Tag "HR" -ForEach @( $Users ) { It "User $($_.DisplayName) should have an Employee ID" { $_.EmployeeID | Should -Not -BeNullOrEmpty -Because "Employee ID should not be empty" } } } #EndRegion #Region User Sign Ins Describe "Validating User Sign Ins" -Tag "Entra", "Users", "All" { Context "7 Days" -Tag "SignIns" -ForEach @( $Users ) { It "User $($_.DisplayName) should have logged in within the last 7 days" { $signInActivity = $_.SignInActivity ($signInActivity.LastSignInDateTime -gt (Get-Date).AddDays(-7)) -or ($signInActivity.LastSuccessfulSignInDateTime -gt (Get-Date).AddDays(-7)) | Should -BeTrue -Because "User should have logged in within the last 7 days" } } Context "14 Days" -Tag "SignIns" -ForEach @( $Users ) { It "User $($_.DisplayName) should have logged in within the last 14 days" { $signInActivity = $_.SignInActivity ($signInActivity.LastSignInDateTime -gt (Get-Date).AddDays(-14)) -or ($signInActivity.LastSuccessfulSignInDateTime -gt (Get-Date).AddDays(-14)) | Should -BeTrue -Because "User should have logged in within the last 14 days" } } Context "30 Days" -Tag "SignIns" -ForEach @( $Users ) { It "User $($_.DisplayName) should have logged in within the last 30 days" { $signInActivity = $_.SignInActivity ($signInActivity.LastSignInDateTime -gt (Get-Date).AddDays(-30)) -or ($signInActivity.LastSuccessfulSignInDateTime -gt (Get-Date).AddDays(-30)) | Should -BeTrue -Because "User should have logged in within the last 30 days" } } Context "60 Days" -Tag "SignIns" -ForEach @( $Users ) { It "User $($_.DisplayName) should have logged in within the last 60 days" { $signInActivity = $_.SignInActivity ($signInActivity.LastSignInDateTime -gt (Get-Date).AddDays(-60)) -or ($signInActivity.LastSuccessfulSignInDateTime -gt (Get-Date).AddDays(-60)) | Should -BeTrue -Because "User should have logged in within the last 60 days" } } Context "90 Days" -Tag "SignIns" -ForEach @( $Users ) { It "User $($_.DisplayName) should have logged in within the last 90 days" { $signInActivity = $_.SignInActivity ($signInActivity.LastSignInDateTime -gt (Get-Date).AddDays(-90)) -or ($signInActivity.LastSuccessfulSignInDateTime -gt (Get-Date).AddDays(-90)) | Should -BeTrue -Because "User should have logged in within the last 90 days" } } } #EndRegion #Region Custom User Standards Describe "Validating Custom User Standards" -Tag "Entra", "Users", "All", "Custom", "CompanyStandard" { Context "Company Name Standard Verification" -Tag "CompanyStandard" -ForEach @( $Users ) { It "User $($_.DisplayName) should have a matching Company Name in Excel data" { $user = $_ $validCompanyName = $excelData | Select-Object -ExpandProperty CompanyName -Unique try { $user.CompanyName | Should -BeIn $validCompanyName -Because "Company Name should be in the list of valid company names" } catch { if (![string]::IsNullOrEmpty($user.Id)) { $selectedCompanyName = Read-Host "The company name of $($user.DisplayName) is not valid. Please enter a valid company name from the list: $($validCompanyName -join ', '), or just press ENTER to skip this update" if ([string]::IsNullOrEmpty($selectedCompanyName) -or $selectedCompanyName -eq 'SKIP') { Write-PSFMessage -Level Output -Message "Skipping update for $($user.DisplayName)" throw "Update skipped for $($user.DisplayName). Test failed." } elseif ($selectedCompanyName -in $validCompanyName) { Update-MgUser -UserId $user.Id -CompanyName $selectedCompanyName Write-PSFMessage -Level Output -Message "Updated the company name of $($user.DisplayName) to $selectedCompanyName" } else { throw "Invalid company name selected. Test failed." } } else { throw "Cannot update company name because user ID is null or empty. Test failed." } } } } Context "Street Standard Verification" -Tag "CompanyStandard" -ForEach @( $Users ) { It "User $($_.DisplayName) should have a matching Street in Excel data" { $user = $_ $validStreetName = $excelData | Select-Object -ExpandProperty StreetAddress -Unique try { $user.StreetAddress | Should -BeIn $validStreetName -Because "Street Address should be in the list of valid street names" } catch { if (![string]::IsNullOrEmpty($user.Id)) { $selectedStreet = Read-Host "The street address of $($user.DisplayName) is not valid. Please enter a valid street address from the list: $($validStreetName -join ', '), or just press ENTER to skip this update" if ([string]::IsNullOrEmpty($selectedStreet) -or $selectedStreet -eq 'SKIP') { Write-PSFMessage -Level Output -Message "Skipping update for $($user.DisplayName)" throw "Update skipped for $($user.DisplayName). Test failed." } elseif ($selectedStreet -in $validStreetName) { Update-MgUser -UserId $user.Id -StreetAddress $selectedStreet Write-PSFMessage -Level Output -Message "Updated the street address of $($user.DisplayName) to $selectedStreet" } else { throw "Invalid street address selected. Test failed." } } else { throw "Cannot update street address because user ID is null or empty. Test failed." } } } } Context "City Standard Verification" -Tag "CompanyStandard" -ForEach @( $Users ) { It "User $($_.DisplayName) should have a matching City in Excel data" { $user = $_ $validCityName = $excelData | Select-Object -ExpandProperty City -Unique try { $user.City | Should -BeIn $validCityName -Because "City should be in the list of valid city names" } catch { if (![string]::IsNullOrEmpty($user.Id)) { $selectedCity = Read-Host "The city of $($user.DisplayName) is not valid. Please enter a valid city from the list: $($validCityName -join ', '), or just press ENTER to skip this update" if ([string]::IsNullOrEmpty($selectedCity) -or $selectedCity -eq 'SKIP') { Write-PSFMessage -Level Output -Message "Skipping update for $($user.DisplayName)" throw "Update skipped for $($user.DisplayName). Test failed." } elseif ($selectedCity -in $validCityName) { Update-MgUser -UserId $user.Id -City $selectedCity Write-PSFMessage -Level Output -Message "Updated the city of $($user.DisplayName) to $selectedCity" } else { throw "Invalid city selected. Test failed." } } else { throw "Cannot update city because user ID is null or empty. Test failed." } } } } Context "State Standard Verification" -Tag "CompanyStandard" -ForEach @( $Users ) { It "User $($_.DisplayName) should have a matching State in Excel data" { $user = $_ $validStates = $excelData | Select-Object -ExpandProperty State -Unique try { $user.State | Should -BeIn $validStates -Because "State should be in the list of valid states" } catch { if (![string]::IsNullOrEmpty($user.Id)) { $selectedState = Read-Host "The state of $($user.DisplayName) is not valid. Please enter a valid state from the list: $($validStates -join ', '), or just press ENTER to skip this update" if ([string]::IsNullOrEmpty($selectedState) -or $selectedState -eq 'SKIP') { Write-PSFMessage -Level Output -Message "Skipping update for $($user.DisplayName)" throw "Update skipped for $($user.DisplayName). Test failed." } elseif ($selectedState -in $validStates) { Update-MgUser -UserId $user.Id -State $selectedState Write-PSFMessage -Level Output -Message "Updated the state of $($user.DisplayName) to $selectedState" } else { throw "Invalid state selected. Test failed." } } else { throw "Cannot update state because user ID is null or empty. Test failed." } } } } Context "Zip Code Standard Verification" -Tag "CompanyStandard" -ForEach @( $Users ) { It "User $($_.DisplayName) should have a matching Zip Code in Excel data" { $user = $_ $validPostalCode = $excelData | Select-Object -ExpandProperty PostalCode -Unique try { $user.PostalCode | Should -BeIn $validPostalCode -Because "Postal Code should be in the list of valid postal codes" } catch { if (![string]::IsNullOrEmpty($user.Id)) { $selectedPostalCode = Read-Host "The postal code of $($user.DisplayName) is not valid. Please enter a valid postal code from the list: $($validPostalCode -join ', '), or just press ENTER to skip this update" if ([string]::IsNullOrEmpty($selectedPostalCode) -or $selectedPostalCode -eq 'SKIP') { Write-PSFMessage -Level Output -Message "Skipping update for $($user.DisplayName)" throw "Update skipped for $($user.DisplayName). Test failed." } elseif ($selectedPostalCode -in $validPostalCode) { Update-MgUser -UserId $user.Id -PostalCode $selectedPostalCode Write-PSFMessage -Level Output -Message "Updated the postal code of $($user.DisplayName) to $selectedPostalCode" } else { throw "Invalid postal code selected. Test failed." } } else { throw "Cannot update postal code because user ID is null or empty. Test failed." } } } } Context "Country Standard Verification" -Tag "CompanyStandard" -ForEach @( $Users ) { It "User $($_.DisplayName) should have a matching Country in Excel data" { $user = $_ $validCountry = $excelData | Select-Object -ExpandProperty Country -Unique try { $user.Country | Should -BeIn $validCountry -Because "Country should be in the list of valid countries" } catch { if (![string]::IsNullOrEmpty($user.Id)) { $selectedCountry = Read-Host "The country of $($user.DisplayName) is not valid. Please enter a valid country from the list: $($validCountry -join ', '), or just press ENTER to skip this update" if ([string]::IsNullOrEmpty($selectedCountry) -or $selectedCountry -eq 'SKIP') { Write-PSFMessage -Level Output -Message "Skipping update for $($user.DisplayName)" throw "Update skipped for $($user.DisplayName). Test failed." } elseif ($selectedCountry -in $validCountry) { Update-MgUser -UserId $user.Id -Country $selectedCountry Write-PSFMessage -Level Output -Message "Updated the country of $($user.DisplayName) to $selectedCountry" } else { throw "Invalid country selected. Test failed." } } else { throw "Cannot update country because user ID is null or empty. Test failed." } } } } Context "Department Standard Verification" -Tag "CompanyStandard" -ForEach @( $Users ) { It "User $($_.DisplayName) should have a matching Department in Excel data" { $user = $_ $validDepartments = $excelData | Select-Object -ExpandProperty Department -Unique try { $user.Department | Should -BeIn $validDepartments -Because "Department should be in the list of valid departments" } catch { if (![string]::IsNullOrEmpty($user.Id)) { $selectedDepartment = Read-Host "The department of $($user.DisplayName) is not valid. Please enter a valid department from the list: $($validDepartments -join ', '), or just press ENTER to skip this update" if ([string]::IsNullOrEmpty($selectedDepartment) -or $selectedDepartment -eq 'SKIP') { Write-PSFMessage -Level Output -Message "Skipping update for $($user.DisplayName)" throw "Update skipped for $($user.DisplayName). Test failed." } elseif ($selectedDepartment -in $validDepartments) { Update-MgUser -UserId $user.Id -Department $selectedDepartment Write-PSFMessage -Level Output -Message "Updated the department of $($user.DisplayName) to $selectedDepartment" } else { throw "Invalid department selected. Test failed." } } else { throw "Cannot update department because user ID is null or empty. Test failed." } } } } Context "Job Title Standard Verification" -Tag "CompanyStandard" -ForEach @( $Users ) { It "User $($_.DisplayName) should have a matching Job Title in Excel data" { $user = $_ $validJobTitles = $excelData | Select-Object -ExpandProperty Title -Unique try { $user.JobTitle | Should -BeIn $validJobTitles -Because "Job Title should be in the list of valid job titles" } catch { if (![string]::IsNullOrEmpty($user.Id)) { $selectedJobTitle = Read-Host "The job title of $($user.DisplayName) is not valid. Please enter a valid job title from the list: $($validJobTitles -join ', '), or just press ENTER to skip this update" if ([string]::IsNullOrEmpty($selectedJobTitle) -or $selectedJobTitle -eq 'SKIP') { Write-PSFMessage -Level Output -Message "Skipping update for $($user.DisplayName)" throw "Update skipped for $($user.DisplayName). Test failed." } elseif ($selectedJobTitle -in $validJobTitles) { Update-MgUser -UserId $user.Id -JobTitle $selectedJobTitle Write-PSFMessage -Level Output -Message "Updated the job title of $($user.DisplayName) to $selectedJobTitle" } else { throw "Invalid job title selected. Test failed." } } else { throw "Cannot update job title because user ID is null or empty. Test failed." } } } } } #EndRegion
Export-365ACResultToHtml.ps1
365AutomatedCheck-0.0.11
<# .SYNOPSIS Exports 365AutomatedCheck results to an HTML file. .DESCRIPTION The Export-365ACResultToHtml function takes an array of results, along with other parameters, and generates an HTML file that displays the results in a table format. The function calculates the total number of tests, the number of passed tests, the number of failed tests, and the number of tests that were not tested. It also provides filter buttons to toggle the visibility of different types of test results. .PARAMETER Results The array of results containing the test data. Each element in the array should be an object with properties representing the test results. .PARAMETER OutputHtmlFilePath The path to the HTML file where the results will be exported. .PARAMETER TotalTests The total number of tests. .PARAMETER PassedTests The number of tests that passed. .PARAMETER FailedTests The number of tests that failed. .PARAMETER TestedProperty The name of the property in the test results object that indicates whether a test was passed or failed. .EXAMPLE $Results = @( [PSCustomObject]@{ 'User Display Name' = 'John Doe' 'Test Property' = 'Yes' }, [PSCustomObject]@{ 'User Display Name' = 'Jane Smith' 'Test Property' = 'No' } ) $OutputHtmlFilePath = '/path/to/results.html' $TotalTests = $Results.Count $PassedTests = ($Results | Where-Object { $_.'Test Property' -eq 'Yes' }).Count $FailedTests = ($Results | Where-Object { $_.'Test Property' -eq 'No' }).Count $TestedProperty = 'Test Property' Export-365ACResultToHtml -Results $Results -OutputHtmlFilePath $OutputHtmlFilePath -TotalTests $TotalTests -PassedTests $PassedTests -FailedTests $FailedTests -TestedProperty $TestedProperty .NOTES This function requires PowerShell version 5.1 or above. #> function Export-365ACResultToHtml { param ( [array]$Results, [string]$OutputHtmlFilePath, [int]$TotalTests, [int]$PassedTests, [int]$FailedTests, [string]$TestedProperty ) $html = @" <!DOCTYPE html> <html> <head> <title>365AutomatedCheck Results</title> <style> body { font-family: Arial, sans-serif; margin: 0; padding: 0; background-color: #1e1e1e; color: #fff; } .container { width: 90%; margin: auto; overflow: hidden; } header { background: #000000; color: white; padding-top: 30px; min-height: 70px; border-bottom: #e8491d 3px solid; } header h1 { padding: 5px 0; text-align: center; } .summary-box { display: flex; justify-content: space-around; padding: 20px; background-color: #2c2c2c; margin-bottom: 20px; } .summary-item { text-align: center; flex: 1; margin: 10px; } .summary-item h2 { margin: 0; font-size: 2em; } .summary-item p { margin: 5px 0 0 0; font-size: 1.2em; } table { width: 100%; border-collapse: collapse; margin: 20px 0; background-color: #333; color: #fff; } th, td { padding: 15px; text-align: left; border-bottom: 1px solid #444; } .success { background-color: #4CAF50; color: white; } .failure { background-color: #f44336; color: white; } .not-tested { background-color: #777; color: white; } .filter-buttons { text-align: center; margin-bottom: 20px; } .filter-buttons button { padding: 10px 20px; margin: 0 5px; background-color: #444; color: #fff; border: none; cursor: pointer; } .filter-buttons button:hover { background-color: #666; } .nowrap { white-space: nowrap; } </style> <script> function filterTests(filter) { var rows = document.querySelectorAll('table tr.test-row'); rows.forEach(function(row) { if (filter === 'all' || row.classList.contains(filter)) { row.style.display = ''; } else { row.style.display = 'none'; } var failedMessageCell = row.querySelector('.failure-message'); if (failedMessageCell) { if (filter === 'Success') { failedMessageCell.classList.add('nowrap'); } else { failedMessageCell.classList.remove('nowrap'); } } }); } </script> </head> <body> <header> <div class="container"> <h1>365AutomatedCheck Results</h1> </div> </header> <div class="container"> <div class="summary-box"> <div class="summary-item"> <h2>$TotalTests</h2> <p>Total tests</p> </div> <div class="summary-item"> <h2>$PassedTests</h2> <p>Passed</p> </div> <div class="summary-item"> <h2>$FailedTests</h2> <p>Failed</p> </div> <div class="summary-item"> <h2>0</h2> <p>Not tested</p> </div> </div> <div class="filter-buttons"> <button onclick="filterTests('all')">All</button> <button onclick="filterTests('success')">Passed</button> <button onclick="filterTests('failure')">Failed</button> </div> <table> <tr> <th>User Display Name</th> <th>$TestedProperty</th> </tr> "@ foreach ($result in $Results) { $html += "<tr class='test-row " $html += if ($result.$TestedProperty -eq 'Yes') { 'success' } else { 'failure' } $html += "'>" $html += "<td>$($result.'User Display Name')</td>" if ($result.$TestedProperty -eq 'Yes') { $html += "<td class='success'>$($result.$TestedProperty)</td>" } else { $html += "<td class='failure'>$($result.$TestedProperty)</td>" } $html += "</tr>" } $html += @" </table> </div> </body> </html> "@ Set-Content -Path $OutputHtmlFilePath -Value $html }
Test-365ACDepartment.ps1
365AutomatedCheck-0.0.11
<# .SYNOPSIS Tests whether users in Microsoft 365 have a department assigned and optionally validates against a list of valid departments. .DESCRIPTION The Test-365ACDepartment function checks if users in Microsoft 365 have a department assigned and can validate these departments against a provided list of valid departments. It supports exporting the results to an Excel file, an HTML file, or outputting directly to the console. .PARAMETER Users Specifies an array of users to test. If not provided, the function retrieves all users in Microsoft 365 with their DisplayName and Department properties. .PARAMETER TenantID The ID of the tenant to connect to. Required if using app-only authentication. .PARAMETER ClientID The ID of the client to use for app-only authentication. Required if using app-only authentication. .PARAMETER CertificateThumbprint The thumbprint of the certificate to use for app-only authentication. Required if using app-only authentication. .PARAMETER AccessToken The access token to use for authentication. Required if using app-only authentication. .PARAMETER InteractiveLogin Specifies whether to use interactive login. If this switch is present, interactive login will be used. Otherwise, app-only authentication will be used. .PARAMETER ValidationExcelFilePath Specifies the path to an Excel file containing a list of valid departments. If provided, the function validates the users' departments against this list. .PARAMETER OutputExcelFilePath Specifies the path to an Excel file where the results will be exported. Requires the ImportExcel module. .PARAMETER OutputHtmlFilePath Specifies the path to an HTML file where the results will be exported. Requires the Export-365ACResultToHtml function to be defined. .PARAMETER TestedProperty Specifies the property that is being tested. Defaults to 'Has Department' but changes to 'Has Valid Department' if a validation list is provided. .EXAMPLE Test-365ACDepartment -Users (Get-MgUser -All) -OutputExcelFilePath "C:\Results.xlsx" Retrieves all users in Microsoft 365 and exports the validation results to an Excel file. .EXAMPLE Test-365ACDepartment -Users (Get-MgUser -All) -OutputHtmlFilePath "C:\Results.html" Retrieves all users in Microsoft 365 and exports the validation results to an HTML file. .EXAMPLE Test-365ACDepartment -Users (Get-MgUser -All) Retrieves all users in Microsoft 365 and outputs the validation results to the console. .NOTES - Requires the ImportExcel module for exporting results to Excel. If not installed, an error will be displayed. - The Export-365ACResultToExcel and Export-365ACResultToHtml functions must be defined for exporting results to Excel or HTML, respectively. .LINK https://github.com/DevClate/365AutomatedCheck #> Function Test-365ACDepartment { [CmdletBinding()] param ( [Parameter(ValueFromPipeline = $true)] [array]$Users = (get-mguser -all -Property DisplayName, Department | Select-Object DisplayName, Department), [Parameter(Mandatory = $false)] [string]$TenantID, [Parameter(Mandatory = $false)] [string]$ClientID, [Parameter(Mandatory = $false)] [string]$CertificateThumbprint, [Parameter(Mandatory = $false)] [string]$AccessToken, [Parameter(Mandatory = $false)] [switch]$InteractiveLogin, [ValidatePattern('\.xlsx$')] [string]$ValidationExcelFilePath, [ValidatePattern('\.xlsx$')] [string]$OutputExcelFilePath, [ValidatePattern('\.html$')] [string]$OutputHtmlFilePath, [string]$TestedProperty = 'Has Department' ) BEGIN { $validDepartments = @() if ($ValidationExcelFilePath) { if (!(Get-Command Import-Excel -ErrorAction SilentlyContinue)) { Stop-PSFFunction -Message "Import-Excel cmdlet not found. Please install the ImportExcel module." -ErrorRecord $_ -Tag 'MissingModule' return } # Import the Excel file to get valid department names $validDepartments = Import-Excel -Path $ValidationExcelFilePath | Select-Object -ExpandProperty Department -Unique } if ($InteractiveLogin) { Write-PSFMessage "Using interactive login..." -Level Host Connect-MgGraph -Scopes "User.Read.All", "AuditLog.read.All" -NoWelcome } else { Write-PSFMessage "Using app-only authentication..." -Level Host Connect-MgGraph -ClientId $ClientID -TenantId $TenantID -CertificateThumbprint $CertificateThumbprint -Scopes "User.Read.All", "AuditLog.Read.All" } $results = @() } PROCESS { $columnName = $ValidationExcelFilePath ? 'Has Valid Department' : 'Has Department' foreach ($user in $Users) { $hasDepartment = [bool]($user.Department) if ($ValidationExcelFilePath) { $hasDepartment = $user.Department -in $validDepartments } $result = [PSCustomObject]@{ 'User Display Name' = $user.DisplayName $columnName = $hasDepartment } $results += $result } } END { $totalTests = $results.Count $passedTests = ($results | Where-Object { $_.$columnName }).Count $failedTests = $totalTests - $passedTests if ($OutputExcelFilePath) { Export-365ACResultToExcel -Results $results -OutputExcelFilePath $OutputExcelFilePath -TotalTests $totalTests -PassedTests $passedTests -FailedTests $failedTests -TestedProperty $columnName } elseif ($OutputHtmlFilePath) { Export-365ACResultToHtml -Results $results -OutputHtmlFilePath $OutputHtmlFilePath -TotalTests $totalTests -PassedTests $passedTests -FailedTests $failedTests -TestedProperty $columnName } else { Write-PSFMessage -Level Output -Message ($results | Out-String) } } }
Export-365ACResultToExcel.ps1
365AutomatedCheck-0.0.11
<# .SYNOPSIS Exports the 365AutomatedCheck results to an Excel file. .DESCRIPTION The Export-365ACResultToExcel function takes an array of results, along with other parameters, and exports the results to an Excel file. It applies formatting, adds summary information, and applies conditional formatting based on the tested property. .PARAMETER Results The array of results to be exported to the Excel file. .PARAMETER OutputExcelFilePath The path of the output Excel file. .PARAMETER TotalTests The total number of tests. .PARAMETER PassedTests The number of tests that passed. .PARAMETER FailedTests The number of tests that failed. .PARAMETER TestedProperty The name of the property that was tested. .EXAMPLE $Results = @( [PSCustomObject]@{ "UserDisplayName" = "John Doe" "TestedProperty" = $true }, [PSCustomObject]@{ "UserDisplayName" = "Jane Smith" "TestedProperty" = $false } ) $OutputExcelFilePath = "C:\Results.xlsx" $TotalTests = $Results.Count $PassedTests = ($Results | Where-Object { $_.TestedProperty }).Count $FailedTests = ($Results | Where-Object { -not $_.TestedProperty }).Count $TestedProperty = "TestedProperty" Export-365ACResultToExcel -Results $Results -OutputExcelFilePath $OutputExcelFilePath -TotalTests $TotalTests -PassedTests $PassedTests -FailedTests $FailedTests -TestedProperty $TestedProperty This example exports the results to an Excel file named "Results.xlsx" and applies formatting and conditional formatting based on the "TestedProperty" property. .NOTES Author: Clayton Tyger Date: 06/20/2024 #> function Export-365ACResultToExcel { param ( [array]$Results, [string]$OutputExcelFilePath, [int]$TotalTests, [int]$PassedTests, [int]$FailedTests, [string]$TestedProperty ) $results | Export-Excel -Path $OutputExcelFilePath -WorkSheetname 'Results' -AutoSize -FreezePane 7, 1 -NoHeader -StartRow 7 -ConditionalText (New-ConditionalText -Text 'Yes' -BackgroundColor Green -ForegroundColor White), (New-ConditionalText -Text 'No' -BackgroundColor Red -ForegroundColor White) $excelPackage = Open-ExcelPackage -Path $OutputExcelFilePath $resultSheet = $excelPackage.Workbook.Worksheets['Results'] # Adding title to the Results Sheet $resultSheet.InsertRow(1, 0) $resultSheet.Cells["A1"].Value = "365AutomatedCheck Results" $resultSheet.Cells["A1:B1"].Merge = $true $resultSheet.Cells["A1:B1"].Style.Font.Size = 20 $resultSheet.Cells["A1:B1"].Style.Font.Bold = $true $resultSheet.Cells["A1:B1"].Style.HorizontalAlignment = [OfficeOpenXml.Style.ExcelHorizontalAlignment]::Center $resultSheet.Cells["A1:B1"].Style.Fill.PatternType = [OfficeOpenXml.Style.ExcelFillStyle]::Solid $resultSheet.Cells["A1:B1"].Style.Fill.BackgroundColor.SetColor([System.Drawing.Color]::Black) $resultSheet.Cells["A1:B1"].Style.Font.Color.SetColor([System.Drawing.Color]::White) # Centering text in column B $resultSheet.Column(2).Style.HorizontalAlignment = [OfficeOpenXml.Style.ExcelHorizontalAlignment]::Center # Adding summary information to the Results Sheet $resultSheet.Cells["A2"].Value = "Total tests" $resultSheet.Cells["B2"].Value = $TotalTests $resultSheet.Cells["A3"].Value = "Passed" $resultSheet.Cells["B3"].Value = $PassedTests $resultSheet.Cells["A4"].Value = "Failed" $resultSheet.Cells["B4"].Value = $FailedTests $resultSheet.Cells["A5"].Value = "Not tested" $resultSheet.Cells["B5"].Value = 0 $resultSheet.Cells["A2:A5"].Style.Font.Size = 16 $resultSheet.Cells["A2:A5"].Style.Font.Bold = $true $resultSheet.Cells["A2:A5"].Style.Fill.PatternType = [OfficeOpenXml.Style.ExcelFillStyle]::Solid $resultSheet.Cells["A2:A5"].Style.Fill.BackgroundColor.SetColor([System.Drawing.Color]::Gray) $resultSheet.Cells["A2:A5"].Style.Font.Color.SetColor([System.Drawing.Color]::White) $resultSheet.Cells["B2:B5"].Style.Fill.PatternType = [OfficeOpenXml.Style.ExcelFillStyle]::Solid $resultSheet.Cells["B2"].Style.Fill.BackgroundColor.SetColor([System.Drawing.Color]::Orange) $resultSheet.Cells["B3"].Style.Fill.BackgroundColor.SetColor([System.Drawing.Color]::Green) $resultSheet.Cells["B4"].Style.Fill.BackgroundColor.SetColor([System.Drawing.Color]::Red) $resultSheet.Cells["B5"].Style.Fill.BackgroundColor.SetColor([System.Drawing.Color]::Gray) $resultSheet.Cells["B2:B5"].Style.Font.Color.SetColor([System.Drawing.Color]::White) $resultSheet.Cells["B2:B5"].Style.Font.Size = 16 $resultSheet.Cells["B2:B5"].Style.Font.Bold = $true # Formatting the Results Sheet headers $resultSheet.Cells["A6:B6"].Style.Fill.PatternType = [OfficeOpenXml.Style.ExcelFillStyle]::Solid $resultSheet.Cells["A6:B6"].Style.Fill.BackgroundColor.SetColor([System.Drawing.Color]::Black) $resultSheet.Cells["A6"].Value = "User Display Name" $resultSheet.Cells["B6"].Value = $TestedProperty $resultSheet.Cells["A6:B6"].Style.Font.Bold = $true $resultSheet.Cells["A6:B6"].Style.Font.Color.SetColor([System.Drawing.Color]::White) # Applying conditional formatting to the results $startRow = 7 for ($i = 0; $i -lt $Results.Count; $i++) { $row = $i + $startRow if ($Results[$i].$TestedProperty -eq 'TRUE') { $resultSheet.Cells["A$row"].Style.Fill.PatternType = [OfficeOpenXml.Style.ExcelFillStyle]::Solid $resultSheet.Cells["A$row"].Style.Fill.BackgroundColor.SetColor([System.Drawing.Color]::Green) $resultSheet.Cells["A$row"].Style.Font.Color.SetColor([System.Drawing.Color]::White) $resultSheet.Cells["B$row"].Style.Fill.PatternType = [OfficeOpenXml.Style.ExcelFillStyle]::Solid $resultSheet.Cells["B$row"].Style.Fill.BackgroundColor.SetColor([System.Drawing.Color]::Green) $resultSheet.Cells["B$row"].Style.Font.Color.SetColor([System.Drawing.Color]::White) } else { $resultSheet.Cells["A$row"].Style.Fill.PatternType = [OfficeOpenXml.Style.ExcelFillStyle]::Solid $resultSheet.Cells["A$row"].Style.Fill.BackgroundColor.SetColor([System.Drawing.Color]::Red) $resultSheet.Cells["A$row"].Style.Font.Color.SetColor([System.Drawing.Color]::White) $resultSheet.Cells["B$row"].Style.Fill.PatternType = [OfficeOpenXml.Style.ExcelFillStyle]::Solid $resultSheet.Cells["B$row"].Style.Fill.BackgroundColor.SetColor([System.Drawing.Color]::Red) $resultSheet.Cells["B$row"].Style.Font.Color.SetColor([System.Drawing.Color]::White) } } Close-ExcelPackage $excelPackage }
New-CT365SharePointSite.ps1
365AutomatedLab-2.11.0
<# .SYNOPSIS Creates new SharePoint Online sites based on the data from an Excel file. .DESCRIPTION The `New-365CTSharePointSite` function connects to SharePoint Online(PnP) using the provided admin URL and imports site data from the specified Excel file. It then attempts to create each site based on the data. .PARAMETER FilePath The path to the Excel file containing the SharePoint site data. The file must exist and have an .xlsx extension. .PARAMETER AdminUrl The SharePoint Online admin URL. .PARAMETER Domain The domain information required for the SharePoint site creation. .EXAMPLE New-CT365SharePointSite -FilePath "C:\path\to\file.xlsx" -AdminUrl "admin.sharepoint.com" -Domain "contoso.com" This example creates SharePoint sites using the data from the "file.xlsx" and connects to SharePoint Online using the provided admin URL. .NOTES Make sure you have the necessary modules installed: ImportExcel, PnP.PowerShell, and PSFramework. .LINK https://docs.microsoft.com/powershell/module/sharepoint-pnp/new-pnpsite #> function New-CT365SharePointSite { [CmdletBinding()] param ( [Parameter(Mandatory, ValueFromPipeline, ValueFromPipelineByPropertyName)] [ValidateScript({ # First, check if the file has a valid Excel extension (.xlsx) if (-not(([System.IO.Path]::GetExtension($psitem)) -match "\.(xlsx)$")) { throw "The file path '$PSitem' does not have a valid Excel format. Please make sure to specify a valid file with a .xlsx extension and try again." } # Then, check if the file exists if (-not([System.IO.File]::Exists($psitem))) { throw "The file path '$PSitem' does not lead to an existing file. Please verify the 'FilePath' parameter and ensure that it points to a valid file (folders are not allowed)." } # Return true if both conditions are met $true })] [string]$FilePath, [Parameter(Mandatory)] [ValidateScript({ if ($_ -match '^[a-zA-Z0-9]+\.sharepoint\.[a-zA-Z0-9]+$') { $true } else { throw "The URL $_ does not match the required format." } })] [string]$AdminUrl, [Parameter(Mandatory, ValueFromPipeline, ValueFromPipelineByPropertyName)] [ValidateScript({ # Check if the domain fits the pattern switch ($psitem) { { $psitem -notmatch '^(((?!-))(xn--|_)?[a-z0-9-]{0,61}[a-z0-9]{1,1}\.)*(xn--)?[a-z]{2,}(?:\.[a-z]{2,})+$' } { throw "The provided domain is not in the correct format." } Default { $true } } })] [string]$Domain ) begin { $PSDefaultParameterValues = @{ "Write-PSFMessage:Level" = "OutPut" "Write-PSFMessage:Target" = "Preperation" } # Import the required modules $ModulesToImport = "ImportExcel", "PnP.PowerShell", "PSFramework" Import-Module $ModulesToImport try { $SiteData = Import-Excel -Path $FilePath -WorksheetName "Sites" } catch { Write-PSFMessage -Message "Failed to import Sharepoint Site data from Excel file." -Level Error return } } process { foreach ($site in $siteData) { $siteurl = "https://$AdminUrl/sites/$($site.Url)" $PSDefaultParameterValues["Write-PSFMessage:Target"] = $site.Title Write-PSFMessage -Message "Creating Sharepoint Site: '$($site.Title)'" $newPnPSiteSplat = @{ Type = $null TimeZone = $site.Timezone Title = $site.Title ErrorAction = "Stop" } switch -Regex ($site.SiteType) { "^TeamSite$" { $newPnPSiteSplat.Type = $PSItem $newPnPSiteSplat.add("Alias", $site.Alias) } "^(CommunicationSite|TeamSiteWithoutMicrosoft365Group)$" { $newPnPSiteSplat.Type = $PSItem $newPnPSiteSplat.add("Url", $siteurl) } default { Write-PSFMessage "Unknown site type: $($site.SiteType) for site $($site.Title). Skipping." -Level Error continue } } try { New-PnPSite @newPnPSiteSplat Write-PSFMessage -Message "Created Sharepoint Site: '$($site.Title)'" } catch { Write-PSFMessage -Message "Could not create Sharepoint Site: '$($site.Title)' Skipping" -Level Error Write-PSFMessage -Message $Psitem.Exception.Message -Level Error Continue } } } end { Write-PSFMessage "SharePoint site creation process completed." # Disconnect from SharePoint Online Disconnect-PnPOnline } }
Remove-CT365SharePointSite.ps1
365AutomatedLab-2.11.0
<# .SYNOPSIS Deletes SharePoint Online sites based on the data from an Excel file. .DESCRIPTION The `Remove-365CTSharePointSite` function connects to SharePoint Online(PnP) using the provided admin URL and imports site data from the specified Excel file. It then attempts to delete each site based on the data. .PARAMETER FilePath The path to the Excel file containing the SharePoint site data. The file must exist and have an .xlsx extension. .PARAMETER AdminUrl The SharePoint Online admin URL. .PARAMETER Domain The domain information required for the SharePoint site creation. .PARAMETER PermanentlyDelete This will completely delete the SharePoint site so you can reuse that site address again. .EXAMPLE Remove-CT365SharePointSite -FilePath "C:\path\to\file.xlsx" -AdminUrl "domainname.sharepoint.com" -Domain "contoso.com" This example removes SharePoint sites using the data from the "file.xlsx" and connects to SharePoint Online using the provided admin URL. .NOTES To use this, please make sure that you the sites have been created at least 6 minutes prior, or it won't work. Also it will say "Group not found" but still works as of 10/23/2023. Open issue in GitHub for more information. Make sure you have the necessary modules installed: ImportExcel, PnP.PowerShell, and PSFramework. .LINK https://docs.microsoft.com/powershell/module/sharepoint-pnp/new-pnpsite #> function Remove-CT365SharePointSite { [CmdletBinding()] param ( [Parameter(Mandatory, ValueFromPipeline, ValueFromPipelineByPropertyName)] [ValidateScript({ # First, check if the file has a valid Excel extension (.xlsx) if (-not(([System.IO.Path]::GetExtension($psitem)) -match "\.(xlsx)$")) { throw "The file path '$PSitem' does not have a valid Excel format. Please make sure to specify a valid file with a .xlsx extension and try again." } # Then, check if the file exists if (-not([System.IO.File]::Exists($psitem))) { throw "The file path '$PSitem' does not lead to an existing file. Please verify the 'FilePath' parameter and ensure that it points to a valid file (folders are not allowed)." } # Return true if both conditions are met $true })] [string]$FilePath, [Parameter(Mandatory = $false)] [ValidateScript({ if ($_ -match '^[a-zA-Z0-9]+\.sharepoint\.[a-zA-Z0-9]+$') { $true } else { throw "The URL $_ does not match the required format." } })] [string]$AdminUrl, [Parameter(Mandatory, ValueFromPipeline, ValueFromPipelineByPropertyName)] [ValidateScript({ switch ($psitem) { { $psitem -notmatch '^(((?!-))(xn--|_)?[a-z0-9-]{0,61}[a-z0-9]{1,1}\.)*(xn--)?[a-z]{2,}(?:\.[a-z]{2,})+$' } { throw "The provided domain is not in the correct format." } Default { $true } } })] [string]$Domain, [switch]$PermanentlyDelete ) begin { # Set default message parameters. $PSDefaultParameterValues = @{ "Write-PSFMessage:Level" = "OutPut" "Write-PSFMessage:Target" = "Preparation" } # Import required modules. $ModulesToImport = "ImportExcel", "PnP.PowerShell", "PSFramework" Import-Module $ModulesToImport try { # Import site data from Excel. $SiteData = Import-Excel -Path $FilePath -WorksheetName "Sites" } catch { # Log an error and exit if importing site data fails. Write-PSFMessage -Message "Failed to import SharePoint Site data from Excel file." -Level Error return } } process { foreach ($site in $siteData) { # Join Admin URL and Site Url $siteUrl = "https://$AdminUrl/sites/$($site.Url)" try { # Set the message target to the site's title. $PSDefaultParameterValues["Write-PSFMessage:Target"] = $site.Title # Log a message indicating site deletion. Write-PSFMessage -Message "Deleting SharePoint Site: '$($site.Title)'" # If PermanentlyDelete switch is set, prioritize those actions if ($PermanentlyDelete) { switch -Regex ($site.SiteType) { "^TeamSite$" { $removePnPM365GroupPermSplat = @{ Identity = $site.Title ErrorAction = 'Stop' } $removePnPTenantSiteSplat = @{ Url = $siteUrl ErrorAction = 'Stop' Force = $true FromRecycleBin = $true } Remove-PnPDeletedMicrosoft365Group @removePnPM365GroupPermSplat Write-PSFMessage -Message "Group'$($Site.Title)' Deleted from Recycle Bin Successfully!" Remove-PnPTenantSite @removePnPTenantSiteSplat Write-PSFMessage -Message "Permanently deleted SharePoint Site: '$($siteUrl)'" continue } "^(CommunicationSite|TeamSiteWithoutMicrosoft365Group)$" { $removePnPTenantSiteSplat = @{ Url = $siteUrl ErrorAction = 'Stop' Force = $true } Remove-PnPTenantDeletedSite @removePnPTenantSiteSplat Write-PSFMessage -Message "Permanently deleted SharePoint Site: '$($siteUrl)'" continue } default { Write-PSFMessage "Unknown site type: $($site.SiteType) for site $($site.Title). Skipping." -Level Error continue } } } else { # If not permanently deleting, proceed with regular deletion switch -Regex ($site.SiteType) { "^TeamSite$" { $removePnPM365GroupSplat = @{ Identity = $site.Title ErrorAction = 'Stop' } Remove-PnPMicrosoft365Group @removePnPM365GroupSplat Write-PSFMessage -Message "Successfully deleted Group Site: '$($site.Title)'" } "^(CommunicationSite|TeamSiteWithoutMicrosoft365Group)$" { $removePnPSiteSplat = @{ Url = $siteUrl ErrorAction = "Stop" Force = $true } remove-PnPTenantSite @removePnPSiteSplat Write-PSFMessage -Message "Successfully deleted SharePoint Site: '$($siteUrl)'" } default { Write-PSFMessage "Unknown site type: $($site.SiteType) for site $($site.Title). Skipping." -Level Error continue } } } } catch [System.Net.WebException], [Microsoft.SharePoint.Client.ClientRequestException] { Write-PSFMessage -Message "Network or SharePoint client error occurred for site: '$($site.Title)'" -Level Error Write-PSFMessage -Message "Error details: $($_.Exception.Message)" -Level Error } catch { Write-PSFMessage -Message "An unexpected error occurred for site: '$($site.Title)'" -Level Error Write-PSFMessage -Message "Error details: $($_.Exception.Message)" -Level Error Write-PSFMessage -Message "Stack Trace: $($_.Exception.StackTrace)" -Level Error } } } end { Write-PSFMessage "SharePoint site deletion process completed." Disconnect-PnPOnline } }
New-CT365SharePointSite.Tests.ps1
365AutomatedLab-2.11.0
BeforeAll { # Call Cmdlet $commandScriptPath = Join-Path -Path $PSScriptRoot -ChildPath '..\functions\public\New-CT365SharePointSite.ps1' . $commandScriptPath } Describe 'New-CT365SharePointSite Function' { Context 'When provided invalid parameters' { It 'Should throw an error for invalid domain format' { $filePath = $commandScriptPath $domain = "invalid_domain" { New-CT365SharePointSite -FilePath $filePath -Domain $domain } | Should -Throw } It 'Should throw an error for invalid file path' { $filePath = "C:\Invalid\Path\file.xlsx" $domain = "contoso.com" { New-CT365SharePointSite -FilePath $filePath -Domain $domain } | Should -Throw } } }
Set-CT365SPDistinctNumber.Tests.ps1
365AutomatedLab-2.11.0
BeforeAll { # Call Cmdlet $commandScriptPath = Join-Path -Path $PSScriptRoot -ChildPath '..\functions\public\Set-CT365SPDistinctNumber.ps1' . $commandScriptPath } Describe 'Set-CT365SPDistinctNumber Function' { Context 'When provided invalid parameters' { It 'Should throw an error for invalid file path' { $filePath = "C:\Invalid\Path\file.xlsx" { Set-CT365SPDistinctNumber -FilePath $filePath -WorksheetName $WorksheetName -FindNumber 37 -ReplaceNumber 38 } | Should -Throw } } }
New-CT365Group.Tests.ps1
365AutomatedLab-2.11.0
BeforeAll { # Call Cmdlet $commandScriptPath = Join-Path -Path $PSScriptRoot -ChildPath '..\functions\public\New-CT365Group.ps1' . $commandScriptPath } Describe 'New-CT365Group Function' { Context 'When provided invalid parameters' { It 'Should throw an error for invalid domain format' { $filePath = $commandScriptPath $domain = "invalid_domain" { New-CT365Group -FilePath $filePath -Domain $domain } | Should -Throw } It 'Should throw an error for invalid file path' { $filePath = "C:\Invalid\Path\file.xlsx" $domain = "contoso.com" { New-CT365Group -FilePath $filePath -Domain $domain } | Should -Throw } } }
Remove-CT365Teams.ps1
365AutomatedLab-2.11.0
<# .SYNOPSIS Removes Microsoft 365 Teams based on the provided Excel data. .DESCRIPTION The Remove-CT365Teams function connects to SharePoint Online, reads a list of Teams from an Excel file, and then removes each team. The function provides feedback on the process using the Write-PSFMessage cmdlet. .PARAMETER FilePath The path to the Excel file containing the list of Teams to remove. The file should have a worksheet named "Teams" and must be in .xlsx format. .PARAMETER AdminUrl The URL of the SharePoint Online admin center. This is used for connecting to SharePoint Online. .PARAMETER ChannelColumns Array of channel column names. The default values are "Channel1Name" and "Channel2Name". .EXAMPLE Remove-CT365Teams -FilePath "C:\Path\To\File.xlsx" -AdminUrl "yourtenant-admin.sharepoint.com" This example will connect to the SharePoint Online admin center using the provided AdminUrl, read the Teams from the specified Excel file, and proceed to remove each team. .NOTES - Ensure you have the necessary modules ("ImportExcel","PnP.PowerShell","PSFramework","Microsoft.Identity.Client") installed before running this function. - Always backup your Teams data before using this function to avoid unintended data loss. - This function has a built-in delay of 5 seconds between team removals to ensure proper deletion. #> function Remove-CT365Teams { [CmdletBinding()] param ( # Validate the Excel file path. [Parameter(Mandatory, ValueFromPipeline, ValueFromPipelineByPropertyName)] [ValidateScript({ # First, check if the file has a valid Excel extension (.xlsx) if (-not(([System.IO.Path]::GetExtension($psitem)) -match "\.(xlsx)$")) { throw "The file path '$PSitem' does not have a valid Excel format. Please make sure to specify a valid file with a .xlsx extension and try again." } # Then, check if the file exists if (-not([System.IO.File]::Exists($psitem))) { throw "The file path '$PSitem' does not lead to an existing file. Please verify the 'FilePath' parameter and ensure that it points to a valid file (folders are not allowed)." } # Return true if both conditions are met $true })] [string]$FilePath, [Parameter(Mandatory = $false)] [ValidateScript({ if ($_ -match '^[a-zA-Z0-9]+\.sharepoint\.[a-zA-Z0-9]+$') { $true } else { throw "The URL $_ does not match the required format." } })] [string]$AdminUrl, [Parameter(Mandatory = $false)] [string[]]$ChannelColumns = @("Channel1Name", "Channel2Name") ) begin { # Import required modules. $ModulesToImport = "ImportExcel", "PnP.PowerShell", "PSFramework", "Microsoft.Identity.Client" Import-Module $ModulesToImport try { # Import site data from Excel. $SiteData = Import-Excel -Path $FilePath -WorksheetName "Teams" } catch { # Log an error and exit if importing site data fails. Write-PSFMessage -Message "Failed to import SharePoint Site data from Excel file." -Level Error return } } process { foreach ($team in $SiteData) { # Get the GroupId for the Team based on its name $teamObj = Get-PnPTeamsTeam | Where-Object { $_.DisplayName -eq $team.TeamName } # Continue to the next iteration if no matching team is found if (-not $teamObj) { continue } $teamGroupId = $teamObj.GroupId # Display the team name that's being removed using Write-PSFMessage Write-PSFMessage -Message "Removing team: $($team.TeamName) with GroupId: $teamGroupId" -Level Host # Remove the Team using the GroupId Remove-PnPTeamsTeam -Identity $teamGroupId -Force # Introduce a delay of 5 seconds Start-Sleep -Seconds 5 # Check if the team still exists $teamCheck = Get-PnPTeamsTeam | Where-Object { $_.GroupId -eq $teamGroupId } # Provide feedback based on team removal status $messageLevel = if ($teamCheck) { "Warning" } else { "Host" } $messageContent = if ($teamCheck) { "Failed to remove team: $($team.TeamName)" } else { "Successfully removed team: $($team.TeamName)" } Write-PSFMessage -Message $messageContent -Level $messageLevel } } end { # Disconnect from PnP Disconnect-PnPOnline Write-PSFMessage -Message "Teams removal completed." } }
New-CT365User.ps1
365AutomatedLab-2.11.0
<# .SYNOPSIS Creates a new user in Office 365. .DESCRIPTION The New-CT365User function creates a new user in Office 365 using the Microsoft Graph API. It imports user data from an Excel file and assigns licenses based on the user data. If the UseDeveloperPackE5 switch is set, it assigns the DEVELOPERPACK_E5 license to all users. .PARAMETER FilePath The path to the Excel file that contains the user data. This parameter is mandatory. .PARAMETER Domain The domain for the new users. This parameter is mandatory. .PARAMETER UseDeveloperPackE5 A switch that, if set, assigns the DEVELOPERPACK_E5 license to all users. .PARAMETER Password The password for the new users. If not provided, the function will prompt for the password. .EXAMPLE New-CT365User -FilePath "C:\Users\admin\Documents\user_data.xlsx" -Domain "contoso.com" -UseDeveloperPackE5 This command creates new users in Office 365 using the user data in the "user_data.xlsx" file, assigns the DEVELOPERPACK_E5 license to all users, and prompts for the password. .EXAMPLE New-CT365User -FilePath "C:\Users\admin\Documents\user_data.xlsx" -Domain "contoso.com" This command creates new users in Office 365 using the user data in the "user_data.xlsx" file, assigns named license from excel worksheet, and prompts for the password. .NOTES You need to have the necessary permissions to create users and assign licenses in Office 365. #> function New-CT365User { [CmdletBinding()] param ( [Parameter(Mandatory, ValueFromPipeline=$true, ValueFromPipelineByPropertyName=$true)] [string]$FilePath, [Parameter(Mandatory, ValueFromPipeline=$true, ValueFromPipelineByPropertyName=$true)] [string]$Domain, [Parameter()] [switch]$UseDeveloperPackE5, [Parameter(ValueFromPipeline=$true, ValueFromPipelineByPropertyName=$true)] [Security.SecureString]$Password = $(Read-Host -Prompt "Enter the password" -AsSecureString) ) # Import Required Modules $ModulesToImport = "ImportExcel", "Microsoft.Graph.Users", "Microsoft.Graph.Groups", "Microsoft.Graph.Identity.DirectoryManagement", "Microsoft.Graph.Users.Actions", "PSFramework" Import-Module $ModulesToImport # Scopes $Scopes = @("Directory.ReadWrite.All") $Context = Get-MgContext if ([string]::IsNullOrEmpty($Context) -or ($Context.Scopes -notmatch [string]::Join('|', $Scopes))) { Connect-MGGraph -Scopes $Scopes } # Import user data from Excel file $userData = $null try { $userData = Import-Excel -Path $FilePath -WorksheetName Users } catch { Write-PSFMessage -Level Error -Message "Failed to import user data from Excel file." return } foreach ($user in $userData) { # Prepare user parameters for creation $userParams = @{ UserPrincipalName = "$($user.UserName)@$Domain" GivenName = $user.FirstName Surname = $user.LastName DisplayName = "$($user.FirstName) $($user.LastName)" MailNickname = $user.UserName JobTitle = $user.Title Department = $user.Department StreetAddress = $user.StreetAddress City = $user.City State = $user.State PostalCode = $user.PostalCode Country = $user.Country UsageLocation = $user.UsageLocation CompanyName = $user.CompanyName AccountEnabled = $true PasswordProfile = @{ ForceChangePasswordNextSignIn = $false Password = $Password | ConvertFrom-SecureString -AsPlainText } } # Add optional properties if they exist foreach ($prop in @('MobilePhone', 'FaxNumber', 'EmployeeHireDate', 'EmployeeId', 'EmployeeType')) { if (-not [string]::IsNullOrEmpty($user.$prop)) { $userParams[$prop] = $user.$prop } } if (-not [string]::IsNullOrEmpty($user.PhoneNumber)) { $UserParams.BusinessPhones = @($user.PhoneNumber) } # Create the new user $createdUser = New-MgUser @userParams if ($null -ne $createdUser) { Write-PSFMessage -Level Host -Message "User created: $($userParams.UserPrincipalName)" -Target $user.UserName } else { Write-PSFMessage -Level Warning -Message "Failed to create user: $($userParams.UserPrincipalName)" -Target $user.UserName continue } # License assignment logic $licenseType = $UseDeveloperPackE5 ? 'DEVELOPERPACK_E5' : $user.License $licenses = Get-MgSubscribedSku | Where-Object { $_.SkuPartNumber -eq $licenseType } if ($licenses) { Set-MgUserLicense -UserId $createdUser.Id -AddLicenses @{ SkuId = $licenses.SkuId } -RemoveLicenses @() Write-PSFMessage -Level Host -Message "License assigned: $($licenses.SkuPartNumber) to user: $($userParams.UserPrincipalName)" -Target $user.UserName } else { Write-PSFMessage -Level Warning -Message "Failed to assign license: $licenseType to user: $($userParams.UserPrincipalName)" -Target $user.UserName } # Manager assignment if applicable if ($null -ne $user.ManagerUPN) { $managerUPNData = "$($user.ManagerUPN)@$Domain" $manager = @{ "@odata.id" = "https://graph.microsoft.com/v1.0/users/$($managerUPNData)" } $assigningManagerMessage = "Assigning manager $($managerUPNData) to user: '$($UserParams.UserPrincipalName)'" Write-PSFMessage -Level Host -Message $assigningManagerMessage -Target $user.UserName Set-MgUserManagerByRef -UserId $createdUser.Id -BodyParameter $manager # Confirm manager assignment $managerDirectoryObject = Get-MgUserManager -UserId $createdUser.Id if ($null -ne $managerDirectoryObject) { $managerUser = Get-MgUser -UserId $managerDirectoryObject.Id $assignedManagerMessage = "Assigned manager $($managerUser.UserPrincipalName) to user: '$($UserParams.UserPrincipalName)'" Write-PSFMessage -Level Host -Message $assignedManagerMessage -Target $user.UserName } else { $failedToAssignManagerMessage = "Failed to assign manager $($user.Manager) to user: '$($UserParams.UserPrincipalName)'" Write-PSFMessage -Level Warning -Message $failedToAssignManagerMessage -Target $user.UserName } } } # Close the Microsoft Graph connection Disconnect-MgGraph }
New-CT365GroupByUserRole.Tests.ps1
365AutomatedLab-2.11.0
BeforeAll { # Call Cmdlet $commandScriptPath = Join-Path -Path $PSScriptRoot -ChildPath '..\functions\public\New-CT365GroupByUserRole.ps1' . $commandScriptPath } Describe 'New-CT365GroupByUserRole Function' { Context 'When provided invalid parameters' { It 'Should throw an error for invalid domain format' { $filePath = $commandScriptPath $domain = "invalid_domain" { New-CT365GroupByUserRole -FilePath $filePath -Domain $domain } | Should -Throw } It 'Should throw an error for invalid file path' { $filePath = "C:\Invalid\Path\file.xlsx" $domain = "contoso.com" { New-CT365GroupByUserRole -FilePath $filePath -Domain $domain } | Should -Throw } } }
Remove-CT365AllDeletedM365Groups.Tests.ps1
365AutomatedLab-2.11.0
BeforeAll { # Call Cmdlet $commandScriptPath = Join-Path -Path $PSScriptRoot -ChildPath '..\functions\public\Remove-CT365AllDeletedM365Groups.ps1' . $commandScriptPath } Describe 'Remove-CT365AllDeletedM365Groups Function' { Context 'When provided invalid parameters' { It 'Should throw an error for invalid url format' { $AdminUrl = "invalid_url" { Remove-CT365AllDeletedM365Groups -AdminUrl $AdminUrl } | Should -Throw } } }
Set-CT365SPDistinctNumber.ps1
365AutomatedLab-2.11.0
<# .SYNOPSIS Replaces specified numbers in an Excel worksheet, excluding certain columns. .DESCRIPTION The Set-CT365SPDistinctNumber function opens an Excel file and replaces occurrences of a specified number in a given worksheet. It excludes specific columns ("Template" and "TimeZone") from this operation. The primary reason for this is to be able to create new Sharepoint Team sites while the others are deleting. .PARAMETER FilePath The path to the Excel file that contains the worksheet to be modified. .PARAMETER WorksheetName The name of the worksheet within the Excel file where the replacements will be made. .PARAMETER FindNumber The number to find in the worksheet. This number will be replaced wherever it is found, except in the excluded columns. .PARAMETER ReplaceNumber The number that will replace the FindNumber in the worksheet. .EXAMPLE Set-CT365SPDistinctNumber -FilePath "C:\Documents\example.xlsx" -WorksheetName "Sheet1" -FindNumber "36" -ReplaceNumber "37" This command replaces all occurrences of the number 36 with 37 in the worksheet named "Sheet1" of the Excel file located at "C:\Documents\example.xlsx", excluding the "Template" and "TimeZone" columns. .INPUTS None. You cannot pipe objects to Set-CT365SPDistinctNumber. .OUTPUTS None. This function does not generate any output. .NOTES This function requires the ImportExcel module to be installed. .LINK https://github.com/dfinke/ImportExcel - The ImportExcel PowerShell module #> function Set-CT365SPDistinctNumber { [CmdletBinding()] param ( [Parameter(Mandatory)] [string]$FilePath, [Parameter(Mandatory)] [string]$WorksheetName, [Parameter(Mandatory)] [string]$FindNumber, [Parameter(Mandatory)] [string]$ReplaceNumber ) # Import the ImportExcel module Import-Module ImportExcel # Open the Excel package $excelPackage = Open-ExcelPackage -Path $FilePath try { $worksheet = $excelPackage.Workbook.Worksheets[$WorksheetName] if ($null -eq $worksheet) { throw "Worksheet '$WorksheetName' not found." } # Get the indices of the columns to exclude $excludedColumns = @("Template", "TimeZone").ForEach({ $worksheet.Dimension.Start.Column..$worksheet.Dimension.End.Column | Where-Object { $worksheet.Cells[1, $_].Text -eq $_ } | ForEach-Object { [OfficeOpenXml.ExcelCellAddress]::GetColumnLetter($_) } }) # Initialize a counter for replacements $replacementCount = 0 # Find and replace the numbers, skipping the excluded columns $worksheet.Cells.Where({ $_.Value -like "*$FindNumber*" -and -not ($excludedColumns -contains [OfficeOpenXml.ExcelCellAddress]::GetColumnLetter($_.Start.Column)) }).ForEach({ if ($_ -ne $null -and $null -ne $_.Value -and $_.Value -like "*$FindNumber*") { $_.Value = $_.Value -replace $FindNumber, $ReplaceNumber $replacementCount++ } }) # Check if the number of replacements is as expected if ($replacementCount -eq 0) { throw "No replacements were made for the number '$FindNumber'." } elseif ($replacementCount -ne 12) { Write-PSFMessage -Message "Unexpected number of replacements: $replacementCount. Expected 12." -Level Error } else { Write-PSFMessage -Message "Exactly 12 replacements were made for the number '$FindNumber'." -Level Host } # Save and close the Excel package Close-ExcelPackage $excelPackage } catch { $excelPackage.Dispose() throw } }
Remove-CT365Teams.Tests.ps1
365AutomatedLab-2.11.0
BeforeAll { # Call Cmdlet $commandScriptPath = Join-Path -Path $PSScriptRoot -ChildPath '..\functions\public\Remove-CT365Teams.ps1' . $commandScriptPath } Describe 'Remove-CT365Teams Function' { Context 'When provided invalid parameters' { It 'Should throw an error for invalid domain format' { $filePath = $commandScriptPath $AdminUrl = "invalid_domain" { Remove-CT365Teams -FilePath $filePath -AdminUrl $AdminUrl } | Should -Throw } It 'Should throw an error for invalid file path' { $filePath = "C:\Invalid\Path\file.xlsx" $AdminUrl = "contoso.com" { Remove-CT365Teams -FilePath $filePath -AdminUrl $AdminUrl } | Should -Throw } } }
Remove-CT365AllSitesFromRecycleBin.ps1
365AutomatedLab-2.11.0
<# .SYNOPSIS Removes all sites from the SharePoint Online recycle bin. .DESCRIPTION The Remove-CT365AllSitesFromRecycleBin function connects to SharePoint Online using the provided admin URL and then removes all sites from the SharePoint Online recycle bin. This function requires the PSFramework and PnP.PowerShell modules. .PARAMETER AdminUrl Specifies the URL of the SharePoint Online admin center. The URL must follow the format 'tenantname.sharepoint.com'. .EXAMPLE Remove-CT365AllSitesFromRecycleBin -AdminUrl "contoso-admin.sharepoint.com" Connects to the SharePoint Online admin center at 'https://contoso-admin.sharepoint.com' and removes all sites from the recycle bin. .INPUTS None .OUTPUTS None .NOTES Please add any suggestions or issues to GitHub Issues #> function Remove-CT365AllSitesFromRecycleBin { [CmdletBinding()] Param ( [Parameter(Mandatory)] [ValidateScript({ if ($_ -match '^[a-zA-Z0-9]+\.sharepoint\.[a-zA-Z0-9]+$') { $true } else { throw "The URL $_ does not match the required format." } })] [string]$AdminUrl ) Begin { # Check if required modules are available, otherwise install them foreach ($module in @('PSFramework', 'PnP.PowerShell')) { if (-not (Get-Module -ListAvailable -Name $module)) { Install-Module $module -Scope CurrentUser } } } Process { try { # Retrieve sites from recycle bin $recycleBinItems = Get-PnPTenantRecycleBinItem # Delete sites from recycle bin foreach ($item in $recycleBinItems) { Remove-PnPTenantDeletedSite -Identity $item.Url -Force Write-PSFMessage -Message "Site removed from recycle bin: $($item.Url)" -Level Host } if ($recycleBinItems.Count -eq 0) { Write-PSFMessage -Message "No sites found in the recycle bin." -Level Host } else { Write-PSFMessage -Message "All sites have been removed from the recycle bin." -Level Host } } catch { Write-PSFMessage -Message "An error occurred: $_" -Level Error } } End { Disconnect-PnPOnline -ErrorAction SilentlyContinue } }
365AutomatedLab.psm1
365AutomatedLab-2.11.0
$FunctionFiles = $("$PSScriptRoot\Functions\Public\","$PSScriptRoot\Functions\Private\")| Get-Childitem -file -Recurse -Include "*.ps1" -ErrorAction SilentlyContinue foreach($FunctionFile in $FunctionFiles){ try { . $FunctionFile.FullName } catch { Write-Error -Message "Failed to import function: '$($FunctionFile.FullName)': $_" } } Export-ModuleMember -Function $FunctionFiles.BaseName
Remove-CT365Group.ps1
365AutomatedLab-2.11.0
<# .SYNOPSIS This function removes Office 365 groups based on information provided in an Excel file. .DESCRIPTION The Remove-CT365Group function is used to remove Office 365 groups. The function imports data from an Excel file and uses it to remove the Office 365 groups. The Excel file should contain a list of groups with their display names and types. The function supports four types of groups: - 365Group - 365Distribution - 365MailEnabledSecurity - 365Security .PARAMETER FilePath The full path to the Excel file that contains information about the groups that should be removed. The file should contain a worksheet named 'Groups'. The 'Groups' worksheet should contain the display names and types of the groups. .PARAMETER UserPrincipalName The User Principal Name (UPN) of the account to connect to Exchange Online and Microsoft Graph. .EXAMPLE Remove-CT365Group -FilePath "C:\Path\to\file.xlsx" -UserPrincipalName "admin@contoso.com" This example removes the Office 365 groups listed in the 'Groups' worksheet of the 'file.xlsx' file, using the 'admin@contoso.com' UPN to connect to Exchange Online and Microsoft Graph. .NOTES This function requires modules ExchangeOnlineManagement, Microsoft.Graph.Groups, Microsoft.Graph.Users, PSFramework, and ImportExcel. #> function Remove-CT365Group { [CmdletBinding()] param ( [Parameter(Mandatory, ValueFromPipeline, ValueFromPipelineByPropertyName)] [ValidateScript({ # First, check if the file has a valid Excel extension (.xlsx) if (-not(([System.IO.Path]::GetExtension($psitem)) -match "\.(xlsx)$")) { throw "The file path '$PSitem' does not have a valid Excel format. Please make sure to specify a valid file with a .xlsx extension and try again." } # Then, check if the file exists if (-not([System.IO.File]::Exists($psitem))) { throw "The file path '$PSitem' does not lead to an existing file. Please verify the 'FilePath' parameter and ensure that it points to a valid file (folders are not allowed)." } # Return true if both conditions are met $true })] [string]$FilePath, [Parameter(Mandatory, ValueFromPipeline, ValueFromPipelineByPropertyName)] [string]$UserPrincipalName ) # Import the required modules $ModulesToImport = "ImportExcel", "Microsoft.Graph.Groups", "PSFramework", "ExchangeOnlineManagement", "Microsoft.Graph.Users" Import-Module $ModulesToImport # Connect to Exchange Online Connect-ExchangeOnline -UserPrincipalName $UserPrincipalName -ShowProgress $true # Connect to Microsoft Graph Connect-MgGraph -Scopes "Group.ReadWrite.All" # Import data from Excel $Groups = Import-Excel -Path $FilePath -WorksheetName Groups foreach ($Group in $Groups) { switch ($Group.Type) { "365Group" { try { Write-PSFMessage -Level Output -Message "Removing 365 Group: $($Group.DisplayName)" -Target $Group.DisplayName Get-UnifiedGroup -Identity $Group.DisplayName -ErrorAction Stop Remove-UnifiedGroup -Identity $Group.DisplayName -Confirm:$false Write-PSFMessage -Level Output -Message "Removed 365 Group: $($Group.DisplayName)" -Target $Group.DisplayName } catch { Write-PSFMessage -Level Warning -Message "365 Group $($Group.DisplayName) does not exist" -Target $Group.DisplayName -ErrorRecord $_ Continue } } "365Distribution" { try { Write-PSFMessage -Level Output "Removing 365 Distribution Group: $($Group.DisplayName)" -Target $Group.DisplayName Get-DistributionGroup -Identity $Group.DisplayName -ErrorAction Stop Remove-DistributionGroup -Identity $Group.DisplayName -Confirm:$false Write-PSFMessage -Level Output -Message "Removed Distribution Group: $($Group.DisplayName)" -Target $Group.DisplayName } catch { Write-PSFMessage -Level Warning -Message "Distribution Group $($Group.DisplayName) does not exist" -Target $Group.DisplayName -ErrorRecord $_ Continue } } "365MailEnabledSecurity" { try { Write-PSFMessage -Level Output -Message "Removing 365 Mail-Enabled Security Group: $($Group.DisplayName)" -Target $Group.DisplayName Get-DistributionGroup -Identity $Group.DisplayName -ErrorAction Stop Remove-DistributionGroup -Identity $Group.DisplayName -Confirm:$false Write-PSFMessage -Level Output -Message "Removed Mail-Enabled Security Group $($Group.DisplayName)" -Target $Group.DisplayName } catch { Write-PSFMessage -Level Warning -Message "Mail-Enabled Security Group $($Group.DisplayName) does not exist" -Target $Group.DisplayName -ErrorRecord $_ Continue } } "365Security" { Write-PSFMessage -Level Output -Message "Removing 365 Security Group $($Group.DisplayName)" -Target $Group.DisplayName $existingGroup = Get-MgGroup -Filter "DisplayName eq '$($Group.DisplayName)'" if ($existingGroup) { Remove-MgGroup -GroupId $existingGroup.Id -Confirm:$false Write-PSFMessage -Level Output -Message "Removed Security Group $($Group.DisplayName)" -Target $Group.DisplayName } else { Write-PSFMessage -Level Warning -Message "Security Group $($Group.DisplayName) does not exist" -Target $Group.DisplayName } } default { Write-PSFMessage -Level Warning -Message "Invalid group type for $($Group.DisplayName)" -Target $Group.DisplayName } } } # Disconnect Exchange Online and Microsoft Graph sessions Disconnect-ExchangeOnline -Confirm:$false Disconnect-MgGraph }
Export-CT365ProdGroupToExcel.ps1
365AutomatedLab-2.11.0
<# .SYNOPSIS Exports Office 365 group data to an Excel file. .DESCRIPTION The Export-CT365ProdGroupToExcel function connects to Microsoft Graph, retrieves Office 365 group data based on specified filters, and exports the data to an Excel file. It supports limiting the number of groups to be retrieved. .PARAMETER FilePath Specifies the path to the Excel file (.xlsx) where the group data will be exported. The directory must exist, and the file must have a .xlsx extension. .PARAMETER GroupLimit Limits the number of groups to retrieve. If set to 0 (default), there is no limit. .EXAMPLE Export-CT365ProdGroupToExcel -FilePath "C:\Groups\Groups.xlsx" Exports all Office 365 groups to the specified Excel file. .EXAMPLE Export-CT365ProdGroupToExcel -FilePath "C:\Groups\LimitedGroups.xlsx" -GroupLimit 50 Exports the first 50 Office 365 groups to the specified Excel file. .NOTES Requires the Microsoft.Graph.Authentication, Microsoft.Graph.Groups, ImportExcel, and PSFramework modules. The user executing this script must have permissions to access group data via Microsoft Graph. .LINK https://docs.microsoft.com/en-us/graph/api/resources/groups-overview?view=graph-rest-1.0 #> function Export-CT365ProdGroupToExcel { [CmdletBinding()] param ( [Parameter(Mandatory, ValueFromPipeline, ValueFromPipelineByPropertyName)] [ValidateScript({ $isValid = $false $extension = [System.IO.Path]::GetExtension($_) $directory = [System.IO.Path]::GetDirectoryName($_) if ($extension -ne '.xlsx') { throw "The file $_ is not an Excel file (.xlsx). Please specify a file with the .xlsx extension." } elseif (-not (Test-Path -Path $directory -PathType Container)) { throw "The directory $directory does not exist. Please specify a valid directory." } else { $isValid = $true } return $isValid })] [string]$FilePath, [Parameter()] [int]$GroupLimit = 0 ) begin { Import-Module Microsoft.Graph.Authentication, Microsoft.Graph.Groups, ImportExcel, PSFramework Write-PSFMessage -Level Output -Message "Preparing to export to $FilePath" -Target $FilePath } process { # Authenticate to Microsoft Graph $Scopes = @("Group.Read.All") $Context = Get-MgContext if ([string]::IsNullOrEmpty($Context) -or ($Context.Scopes -notmatch [string]::Join('|', $Scopes))) { Connect-MGGraph -Scopes $Scopes } $groupTypeFilters = @( "groupTypes/any(c:c eq 'Unified')", "(mailEnabled eq true and securityEnabled eq false)", "(mailEnabled eq true and securityEnabled eq true)", "(mailEnabled eq false and securityEnabled eq true)" ) $filterQuery = $groupTypeFilters -join " or " $getMgGroupSplat = @{ Filter = $filterQuery Select = 'DisplayName', 'MailNickname', 'Description', 'GroupTypes', 'MailEnabled', 'SecurityEnabled' } if ($GroupLimit -gt 0) { $getMgGroupSplat.Add("Top", $GroupLimit) } else { $getMgGroupSplat.Add("All", $true) } $selectProperties = @{ Property = @( 'DisplayName', @{Name = 'PrimarySMTP'; Expression = { $_.MailNickname } }, 'Description', @{Name = 'Type'; Expression = { if ($_.GroupTypes -contains "Unified") { "365Group" } elseif ($_.MailEnabled -and -not $_.SecurityEnabled) { "365Distribution" } elseif ($_.MailEnabled -and $_.SecurityEnabled) { "365MailEnabledSecurity" } else { "365Security" } } } ) } Get-MgGroup @getMgGroupSplat | Select-Object @selectProperties | Export-Excel -Path $FilePath -WorksheetName "Groups" -AutoSize Disconnect-MgGraph -ErrorAction SilentlyContinue } end { Write-PSFMessage -Level Output -Message "Export completed. Check the file at $FilePath for the group details." } }
Remove-CT365GroupByUserRole.Tests.ps1
365AutomatedLab-2.11.0
BeforeAll { # Call Cmdlet $commandScriptPath = Join-Path -Path $PSScriptRoot -ChildPath '..\functions\public\Remove-CT365GroupByUserRole.ps1' . $commandScriptPath } Describe 'Remove-CT365GroupByUserRole Function' { Context 'When provided invalid parameters' { It 'Should throw an error for invalid domain format' { $filePath = $commandScriptPath $domain = "invalid_domain" { Remove-CT365GroupByUserRole -FilePath $filePath -Domain $domain } | Should -Throw } It 'Should throw an error for invalid file path' { $filePath = "C:\Invalid\Path\file.xlsx" $domain = "contoso.com" { Remove-CT365GroupByUserRole -FilePath $filePath -Domain $domain } | Should -Throw } } }
Remove-CT365User.Tests.ps1
365AutomatedLab-2.11.0
BeforeAll { # Call Cmdlet $commandScriptPath = Join-Path -Path $PSScriptRoot -ChildPath '..\functions\public\Remove-CT365User.ps1' . $commandScriptPath } Describe 'Remove-CT365User Function' { Context 'When provided invalid parameters' { It 'Should throw an error for invalid domain format' { $filePath = $commandScriptPath $domain = "invalid_domain" { Remove-CT365User -FilePath $filePath -Domain $domain } | Should -Throw } It 'Should throw an error for invalid file path' { $filePath = "C:\Invalid\Path\file.xlsx" $domain = "contoso.com" { Remove-CT365User -FilePath $filePath -Domain $domain } | Should -Throw } } }
Verify-CT365TeamsCreation.ps1
365AutomatedLab-2.11.0
function Verify-CT365TeamsCreation { param( [string]$teamName, [int]$retryCount = 5, [int]$delayInSeconds = 10 ) for ($i = 0; $i -lt $retryCount; $i++) { $existingTeam = Get-PnPTeamsTeam | Where-Object { $_.DisplayName -eq $teamName } if ($existingTeam) { return $true } Start-Sleep -Seconds $delayInSeconds } return $false }
365AutomatedLab.psd1
365AutomatedLab-2.11.0
# # Module manifest for module '365AutomatedLab' # # Generated by: Clayton Tyger # # Generated on: 6/1/2023 # @{ # Script module or binary module file associated with this manifest. RootModule = '365AutomatedLab.psm1' # Version number of this module. ModuleVersion = '2.11.0' # Supported PSEditions CompatiblePSEditions = 'Core' # ID used to uniquely identify this module GUID = 'd2cf0a82-aeab-4c4c-83fc-764cf4c23ffb' # Author of this module Author = 'Clayton Tyger' # Company or vendor of this module CompanyName = 'Clayton Tyger' # Copyright statement for this module Copyright = '(c) Clayton Tyger. All rights reserved.' # Description of the functionality provided by this module Description = 'This module will allow you to create a 365 Development Environment from an Excel workbook' # Minimum version of the PowerShell engine required by this module PowerShellVersion = '7.1' # Name of the PowerShell host required by this module # PowerShellHostName = '' # Minimum version of the PowerShell host required by this module # PowerShellHostVersion = '' # Minimum version of Microsoft .NET Framework required by this module. This prerequisite is valid for the PowerShell Desktop edition only. # DotNetFrameworkVersion = '' # Minimum version of the common language runtime (CLR) required by this module. This prerequisite is valid for the PowerShell Desktop edition only. # ClrVersion = '' # Processor architecture (None, X86, Amd64) required by this module # ProcessorArchitecture = '' # Modules that must be imported into the global environment prior to importing this module RequiredModules = @( @{ ModuleName='ImportExcel'; ModuleVersion='7.8.2' } @{ ModuleName='ExchangeOnlineManagement'; ModuleVersion='2.0.6' } @{ ModuleName='Microsoft.Graph.Users'; ModuleVersion='1.17.0' } @{ ModuleName='Microsoft.Graph.Groups'; ModuleVersion='1.17.0' } @{ ModuleName='Microsoft.Graph.Identity.DirectoryManagement'; ModuleVersion='1.17.0' } @{ ModuleName='Microsoft.Graph.Users.Actions'; ModuleVersion='1.17.0' } @{ ModuleName='PSFramework'; ModuleVersion='1.8.289' } @{ ModuleName='PnP.PowerShell'; ModuleVersion='2.2.0' } #@{ ModuleName='Microsoft.Identity.Client'; RequiredVersion='4.50.0' } ) # Assemblies that must be loaded prior to importing this module # RequiredAssemblies = @() # Script files (.ps1) that are run in the caller's environment prior to importing this module. # ScriptsToProcess = @() # Type files (.ps1xml) to be loaded when importing this module # TypesToProcess = @() # Format files (.ps1xml) to be loaded when importing this module # FormatsToProcess = @() # Modules to import as nested modules of the module specified in RootModule/ModuleToProcess # NestedModules = @() # Functions to export from this module, for best performance, do not use wildcards and do not delete the entry, use an empty array if there are no functions to export. FunctionsToExport = @( 'New-CT365Group', 'New-CT365User', 'New-CT365GroupByUserRole', 'Remove-CT365Group', 'Remove-CT365User', 'Remove-CT365GroupByUserRole', 'Copy-WorksheetName', 'New-CT365DataEnvironment', 'Export-CT365ProdUserToExcel', 'New-CT365SharePointSite', 'New-CT365Teams', 'Remove-CT365Teams', 'Remove-CT365SharePointSite', 'Set-CT365SPDistinctNumber', 'Remove-CT365AllDeletedM365Groups', 'Export-CT365ProdGroupToExcel', 'Export-CT365ProdTeamsToExcel', 'Verify-CT365TeamsCreation', 'Remove-CT365AllSitesFromRecycleBin' ) # Cmdlets to export from this module, for best performance, do not use wildcards and do not delete the entry, use an empty array if there are no cmdlets to export. CmdletsToExport = @() # Variables to export from this module VariablesToExport = @() # Aliases to export from this module, for best performance, do not use wildcards and do not delete the entry, use an empty array if there are no aliases to export. AliasesToExport = @() # DSC resources to export from this module # DscResourcesToExport = @() # List of all modules packaged with this module # ModuleList = @() # List of all files packaged with this module # FileList = @() # Private data to pass to the module specified in RootModule/ModuleToProcess. This may also contain a PSData hashtable with additional module metadata used by PowerShell. PrivateData = @{ PSData = @{ # Tags applied to this module. These help with module discovery in online galleries. Tags = @('Office365', 'Automation', 'MSGraph', 'Cloud', 'Teams', 'Configuration', 'Sharepoint', 'Excel', 'Exchange', 'MacOS', 'Windows', 'PSEdition_Core') # A URL to the license for this module. # LicenseUri = '' # A URL to the main website for this project. ProjectUri = 'https://github.com/DevClate/365AutomatedLab' # A URL to an icon representing this module. IconUri = 'https://raw.githubusercontent.com/DevClate/365AutomatedLab/78573608de64cefec833d808939fb95edaa456ad/Static/365automatedlabIcon.png' # ReleaseNotes of this module ReleaseNotes = 'https://github.com/DevClate/365AutomatedLab/blob/78573608de64cefec833d808939fb95edaa456ad/CHANGELOG.md' # Prerelease string of this module # Prerelease = '' # Flag to indicate whether the module requires explicit user acceptance for install/update/save # RequireLicenseAcceptance = $false # External dependent modules of this module # ExternalModuleDependencies = @() } # End of PSData hashtable } # End of PrivateData hashtable # HelpInfo URI of this module # HelpInfoURI = '' # Default prefix for commands exported from this module. Override the default prefix using Import-Module -Prefix. # DefaultCommandPrefix = '' }
Remove-CT365Group.Tests.ps1
365AutomatedLab-2.11.0
BeforeAll { # Call Cmdlet $commandScriptPath = Join-Path -Path $PSScriptRoot -ChildPath '..\functions\public\Remove-CT365Group.ps1' . $commandScriptPath } Describe 'Remove-CT365Group Function' { Context 'When provided invalid parameters' { It 'Should throw an error for invalid domain format' { $filePath = $commandScriptPath $domain = "invalid_domain" { Remove-CT365Group -FilePath $filePath -Domain $domain } | Should -Throw } It 'Should throw an error for invalid file path' { $filePath = "C:\Invalid\Path\file.xlsx" $domain = "contoso.com" { Remove-CT365Group -FilePath $filePath -Domain $domain } | Should -Throw } } }
New-CT365Teams.Tests.ps1
365AutomatedLab-2.11.0
BeforeAll { # Call Cmdlet $commandScriptPath = Join-Path -Path $PSScriptRoot -ChildPath '..\functions\public\New-CT365Teams.ps1' . $commandScriptPath } Describe 'New-CT365Teams Function' { Context 'When provided invalid parameters' { It 'Should throw an error for invalid domain format' { $filePath = $commandScriptPath $AdminUrl = "invalid_domain" { New-CT365Teams -FilePath $filePath -AdminUrl $AdminUrl } | Should -Throw } It 'Should throw an error for invalid file path' { $filePath = "C:\Invalid\Path\file.xlsx" $AdminUrl = "contoso.com" { New-CT365Teams -FilePath $filePath -AdminUrl $AdminUrl } | Should -Throw } } }
Remove-CT365User.ps1
365AutomatedLab-2.11.0
<# .SYNOPSIS Removes a user from Microsoft 365 based on the provided Excel data. .DESCRIPTION The Remove-CT365User function connects to the Microsoft Graph, reads user data from the provided Excel file, and attempts to remove each user listed in the file from Microsoft 365. .PARAMETER FilePath Specifies the full path to the Excel file that contains the user data. This parameter is mandatory. .PARAMETER Domain Specifies the domain that will be concatenated with the UserPrincipalName to form a valid email address. This parameter is mandatory. .EXAMPLE Remove-CT365User -FilePath "C:\Path\to\file.xlsx" -Domain "example.com" This command attempts to remove the users listed in the "file.xlsx" Excel file from the "example.com" domain. .INPUTS System.String. You can pipe a string that contains the file path and domain to Remove-CT365User. .OUTPUTS System.String. Outputs a message for each attempted user removal, indicating success or failure. .NOTES This function requires the Microsoft.Graph.Users, ImportExcel, and PSFramework modules. Make sure to install them using Install-Module before running this function. .LINK https://docs.microsoft.com/en-us/powershell/module/microsoft.graph.users/?view=graph-powershell-1.0 .LINK https://www.powershellgallery.com/packages/ImportExcel .LINK https://psframework.org/documentation/commands/PSFramework.html #> function Remove-CT365User { [CmdletBinding()] param ( [Parameter(Mandatory, ValueFromPipeline, ValueFromPipelineByPropertyName)] [ValidateScript({ # First, check if the file has a valid Excel extension (.xlsx) if (-not(([System.IO.Path]::GetExtension($psitem)) -match "\.(xlsx)$")) { throw "The file path '$PSitem' does not have a valid Excel format. Please make sure to specify a valid file with a .xlsx extension and try again." } # Then, check if the file exists if (-not([System.IO.File]::Exists($psitem))) { throw "The file path '$PSitem' does not lead to an existing file. Please verify the 'FilePath' parameter and ensure that it points to a valid file (folders are not allowed)." } # Return true if both conditions are met $true })] [string]$FilePath, [Parameter(Mandatory, ValueFromPipeline, ValueFromPipelineByPropertyName)] [ValidateScript({ # Check if the domain fits the pattern switch ($psitem) { { $psitem -notmatch '^(((?!-))(xn--|_)?[a-z0-9-]{0,61}[a-z0-9]{1,1}\.)*(xn--)?[a-z]{2,}(?:\.[a-z]{2,})+$' } { throw "The provided domain is not in the correct format." } Default { $true } } })] [string]$Domain ) # Import Required Modules $ModulesToImport = "ImportExcel", "Microsoft.Graph.Users", "Microsoft.Graph.Groups", "Microsoft.Graph.Identity.DirectoryManagement", "Microsoft.Graph.Users.Actions", "PSFramework" Import-Module $ModulesToImport # Connect to Microsoft Graph $Scopes = @("User.ReadWrite.All") $Context = Get-MgContext if ([string]::IsNullOrEmpty($Context) -or ($Context.Scopes -notmatch [string]::Join('|', $Scopes))) { Connect-MGGraph -Scopes $Scopes } # Import user data from Excel file $userData = $null try { $userData = Import-Excel -Path $FilePath -WorksheetName Users } catch { Write-PSFMessage -Level Error -Message "Failed to import user data from Excel file." return } # Iterate through each user in the Excel file and delete them foreach ($user in $userData) { $NewUserParams = @{ UserPrincipalName = "$($user.UserName)@$domain" GivenName = $user.FirstName Surname = $user.LastName DisplayName = "$($user.Firstname) $($user.Lastname)" MailNickname = $user.UserName JobTitle = $user.Title Department = $user.Department } Write-PSFMessage -Level Output -Message "Removing user: '$($NewUserParams.UserPrincipalName)'" -Target $NewUserParams.UserName $userToRemove = Get-MgUser | Where-Object { $_.DisplayName -eq $NewUserParams.DisplayName } # Validate if the user exists if ($userToRemove) { Remove-MgUser -UserId $userToRemove.id # Check the user's existence $removedUser = Get-MgUser | Where-Object { $_.DisplayName -eq $NewUserParams.DisplayName } # Confirm that the user was removed if (-not $removedUser) { Write-PSFMessage -Level Output -Message "User $($NewUserParams.DisplayName) has been successfully removed." -Target $NewUserParams.DisplayName } else { Write-PSFMessage -Level Warning -Message "Failed to remove user $($NewUserParams.DisplayName)." -Target $NewUserParams.DisplayName } } else { Write-PSFMessage -Level Warning -Message "User $($NewUserParams.DisplayName) does not exist." -Target $NewUserParams.DisplayName } } # Disconnect Microsoft Graph Sessions if (-not [string]::IsNullOrEmpty($(Get-MgContext))) { Disconnect-MgGraph } }
Export-CT365ProdTeamstoExcel.ps1
365AutomatedLab-2.11.0
<# .SYNOPSIS Exports Microsoft Teams and their channels to an Excel file. .DESCRIPTION The Export-CT365ProdTeamsToExcel function connects to SharePoint Online and retrieves information about Microsoft Teams and their channels. It then exports this data to an Excel file. The function requires a valid SharePoint admin URL and the path to an Excel file for exporting the data. .PARAMETER FilePath Specifies the path to the Excel file (.xlsx) where the Teams and Channels data will be exported. .PARAMETER AdminUrl Specifies the SharePoint admin URL for connecting to Microsoft Teams. The URL should match the format 'tenant.sharepoint.com'. .EXAMPLE Export-CT365ProdTeamsToExcel -FilePath "C:\Teams\TeamsData.xlsx" -AdminUrl "contoso.sharepoint.com" Exports Microsoft Teams and their channels information to the specified Excel file for the given SharePoint admin URL. .NOTES Requires the PnP.PowerShell, ImportExcel, and PSFramework modules. The user executing this script must have SharePoint Online administration permissions. The function handles multiple channels per team and exports them in a structured format in the Excel file. .LINK https://docs.microsoft.com/en-us/powershell/module/sharepoint-pnp/connect-pnponline?view=sharepoint-ps #> function Export-CT365ProdTeamsToExcel { [CmdletBinding()] param ( [Parameter(Mandatory, ValueFromPipeline, ValueFromPipelineByPropertyName)] [ValidateScript({ $extension = [System.IO.Path]::GetExtension($_) $directory = [System.IO.Path]::GetDirectoryName($_) if ($extension -ne '.xlsx') { throw "The file $_ is not an Excel file (.xlsx). Please specify a file with the .xlsx extension." } if (-not (Test-Path -Path $directory -PathType Container)) { throw "The directory $directory does not exist. Please specify a valid directory." } return $true })] [string]$FilePath, [Parameter(Mandatory)] [ValidateScript({ if ($_ -match '^[a-zA-Z0-9]+\.sharepoint\.[a-zA-Z0-9]+$') { $true } else { throw "The URL $_ does not match the required format." } })] [string]$AdminUrl ) begin { Import-Module PnP.PowerShell, ImportExcel, PSFramework Write-PSFMessage -Level Host -Message "Preparing to export to $(Split-Path -Path $FilePath -Leaf)" } process { # Fetch all teams $teams = Get-PnPTeamsTeam Write-PSFMessage -Level Verbose -Message "Retrieved Microsoft Teams information" $exportData = foreach ($team in $teams) { # Fetch channels for the team, excluding 'General' $channels = Get-PnPTeamsChannel -Team $team.DisplayName | Where-Object { $_.DisplayName -ne 'General' } $teamObject = [PSCustomObject]@{ "TeamName" = $team.DisplayName "TeamDescription" = $team.Description "TeamType" = $team.Visibility } $channelCount = 1 foreach ($channel in $channels) { $channelPropertyName = "Channel${channelCount}Name" $channelDescriptionPropertyName = "Channel${channelCount}Description" $channelTypePropertyName = "Channel${channelCount}Type" # Check if the channel type is 'unknownfuturevalue' and convert it to 'shared' $channelType = if ($channel.MembershipType -eq 'unknownfuturevalue') { 'shared' } else { $channel.MembershipType } $teamObject | Add-Member -NotePropertyName $channelPropertyName -NotePropertyValue $channel.DisplayName $teamObject | Add-Member -NotePropertyName $channelDescriptionPropertyName -NotePropertyValue $channel.Description $teamObject | Add-Member -NotePropertyName $channelTypePropertyName -NotePropertyValue $channelType $channelCount++ } $teamObject } # Export data to Excel $exportData | Export-Excel -Path $FilePath -WorksheetName "Teams" -AutoSize Write-PSFMessage -Level Host -Message "Data exported to Excel successfully" # Disconnect the PnP session Disconnect-PnPOnline Write-PSFMessage -Level Verbose -Message "Disconnected from Microsoft 365" } end { Write-PSFMessage -Level Host -Message "Export completed. Check the file at $FilePath for the Teams and Channels details." } }
Remove-CT365AllDeletedM365Groups.ps1
365AutomatedLab-2.11.0
<# .SYNOPSIS Removes all deleted Microsoft 365 groups from the recycle bin. .DESCRIPTION The Remove-CT365AllDeletedM365Groups function connects to a Microsoft 365 tenant and removes all Microsoft 365 groups that have been deleted and are currently in the recycle bin. It requires the PnP.PowerShell module and uses the Connect-PnPOnline cmdlet to establish the connection. .PARAMETER AdminUrl The URL of the Microsoft 365 admin center. This parameter is mandatory and specifies the tenant to connect to. .EXAMPLE PS C:\> Remove-CT365AllDeletedM365Groups -AdminUrl "contoso-admin.sharepoint.com" This example connects to the Microsoft 365 tenant at contoso-admin.sharepoint.com and removes all deleted Microsoft 365 groups. .INPUTS None. You cannot pipe objects to Remove-CT365AllDeletedM365Groups. .OUTPUTS String. The function outputs messages indicating the status of deletion operations and any errors encountered. .NOTES This function requires the PnP.PowerShell module and PSFramework #> function Remove-CT365AllDeletedM365Groups { [CmdletBinding()] Param ( [Parameter(Mandatory)] [ValidateScript({ if ($_ -match '^[a-zA-Z0-9]+\.sharepoint\.[a-zA-Z0-9]+$') { $true } else { throw "The URL $_ does not match the required format." } })] [string]$AdminUrl ) Begin { foreach ($module in @('PSFramework', 'PnP.PowerShell')) { if (-not (Get-Module -ListAvailable -Name $module)) { Install-Module $module -Scope CurrentUser } } } Process { try { $deletedGroups = Get-PnPDeletedMicrosoft365Group foreach ($group in $deletedGroups) { Remove-PnPDeletedMicrosoft365Group -Identity $group.Id Write-PSFMessage -Message "Deleted group removed: $($group.DisplayName)" -Level Host } if ($deletedGroups.Count -eq 0) { Write-PSFMessage -Message "No deleted groups found." -Level Host } else { Write-PSFMessage -Message "All deleted groups have been removed." -Level Host } } catch { Write-PSFMessage -Message "An error occurred: $_" -Level Error } } End { Disconnect-PnPOnline -ErrorAction SilentlyContinue } }