diff --git a/.openpublishing.build.ps1 b/.openpublishing.build.ps1 index aadef7620..999addd64 100644 --- a/.openpublishing.build.ps1 +++ b/.openpublishing.build.ps1 @@ -1,17 +1,17 @@ param( - [string]$buildCorePowershellUrl = "https://opbuildstorageprod.blob.core.windows.net/opps1container/.openpublishing.buildcore.ps1", + [string]$buildCorePowershellUrl = 'https://opbuildstorageprod.blob.core.windows.net/opps1container/.openpublishing.buildcore.ps1', [string]$parameters ) # Main -$errorActionPreference = 'Stop' +$ErrorActionPreference = 'Stop' # Step-1: Download buildcore script to local -echo "download build core script to local with source url: $buildCorePowershellUrl" +Write-Output "download build core script to local with source url: $buildCorePowershellUrl" $repositoryRoot = Split-Path -Parent $MyInvocation.MyCommand.Definition $buildCorePowershellDestination = "$repositoryRoot\.openpublishing.buildcore.ps1" Invoke-WebRequest $buildCorePowershellUrl -OutFile "$buildCorePowershellDestination" # Step-2: Run build core -echo "run build core script with parameters: $parameters" +Write-Output "run build core script with parameters: $parameters" & "$buildCorePowershellDestination" "$parameters" exit $LASTEXITCODE diff --git a/module/Entra/Microsoft.Entra/DirectoryManagement/Get-EntraDirectoryObjectOnPremisesProvisioningError.ps1 b/module/Entra/Microsoft.Entra/DirectoryManagement/Get-EntraDirectoryObjectOnPremisesProvisioningError.ps1 index abbed13e6..245e90f10 100644 --- a/module/Entra/Microsoft.Entra/DirectoryManagement/Get-EntraDirectoryObjectOnPremisesProvisioningError.ps1 +++ b/module/Entra/Microsoft.Entra/DirectoryManagement/Get-EntraDirectoryObjectOnPremisesProvisioningError.ps1 @@ -1,39 +1,46 @@ -# ------------------------------------------------------------------------------ -# Copyright (c) Microsoft Corporation. All Rights Reserved. -# Licensed under the MIT License. See License in the project root for license information. -# ------------------------------------------------------------------------------ +# ------------------------------------------------------------------------------ +# Copyright (c) Microsoft Corporation. All Rights Reserved. +# Licensed under the MIT License. See License in the project root for license information. +# ------------------------------------------------------------------------------ function Get-EntraDirectoryObjectOnPremisesProvisioningError { [CmdletBinding(DefaultParameterSetName = 'GetById')] + [OutputType([System.Object])] param ( - [Parameter(ParameterSetName = "GetById")][ValidateNotNullOrEmpty()][ValidateScript({if ($_ -is [System.Guid]) { $true } else {throw "TenantId must be of type [System.Guid]."}})][System.Guid] $TenantId + [Parameter(ParameterSetName = 'GetById')] + [ValidateNotNullOrEmpty()] + [ValidateScript({ if ($_ -is [System.Guid]) { $true } else { throw 'TenantId must be of type [System.Guid].' } })] + [System.Guid] $TenantId ) - PROCESS { + begin { } + + process { $params = @{} - $customHeaders = New-EntraCustomHeaders -Command $MyInvocation.MyCommand - if ($null -ne $PSBoundParameters["TenantId"]) { - $params["TenantId"] = $PSBoundParameters["TenantId"] - } - Write-Debug("============================ TRANSFORMATIONS ============================") + $customHeaders = New-EntraCustomHeaders -Command $MyInvocation.MyCommand + if ($null -ne $PSBoundParameters['TenantId']) { + $params['TenantId'] = $PSBoundParameters['TenantId'] + } + Write-Debug('============================ TRANSFORMATIONS ============================') $params.Keys | ForEach-Object { "$_ : $($params[$_])" } | Write-Debug Write-Debug("=========================================================================`n") - $Object = @("users", "groups", "contacts") + $Object = @('users', 'groups', 'contacts') $response = @() - + try { foreach ($obj in $object) { - $obj = ($obj | Out-String).trimend() + $obj = ($obj | Out-String).TrimEnd() $uri = 'https://graph.microsoft.com/v1.0/' + $obj + '?$select=onPremisesProvisioningErrors' $response += ((Invoke-GraphRequest -Headers $customHeaders -Uri $uri -Method GET).value).onPremisesProvisioningErrors } + } catch { + Write-Error $_.Exception.Message } - catch {} + } + + end { if ([string]::IsNullOrWhiteSpace($response)) { - write-host "False" - } - else { + Write-Output 'False' + } else { $response } - } } - diff --git a/module/EntraBeta/Microsoft.Entra.Beta/DirectoryManagement/Get-EntraBetaDirectoryObjectOnPremisesProvisioningError.ps1 b/module/EntraBeta/Microsoft.Entra.Beta/DirectoryManagement/Get-EntraBetaDirectoryObjectOnPremisesProvisioningError.ps1 index f7b7aea15..4916b9566 100644 --- a/module/EntraBeta/Microsoft.Entra.Beta/DirectoryManagement/Get-EntraBetaDirectoryObjectOnPremisesProvisioningError.ps1 +++ b/module/EntraBeta/Microsoft.Entra.Beta/DirectoryManagement/Get-EntraBetaDirectoryObjectOnPremisesProvisioningError.ps1 @@ -1,39 +1,47 @@ -# ------------------------------------------------------------------------------ -# Copyright (c) Microsoft Corporation. All Rights Reserved. -# Licensed under the MIT License. See License in the project root for license information. -# ------------------------------------------------------------------------------ +# ------------------------------------------------------------------------------ +# Copyright (c) Microsoft Corporation. All Rights Reserved. +# Licensed under the MIT License. See License in the project root for license information. +# ------------------------------------------------------------------------------ function Get-EntraBetaDirectoryObjectOnPremisesProvisioningError { [CmdletBinding(DefaultParameterSetName = 'GetById')] + [OutputType([System.Object])] param ( - [Parameter(ParameterSetName = "GetById")][ValidateNotNullOrEmpty()][ValidateScript({if ($_ -is [System.Guid]) { $true } else {throw "TenantId must be of type [System.Guid]."}})][System.Guid] $TenantId + [Parameter(ParameterSetName = 'GetById')] + [ValidateNotNullOrEmpty()] + [ValidateScript({ if ($_ -is [System.Guid]) { $true } else { throw 'TenantId must be of type [System.Guid].' } })] + [System.Guid] $TenantId ) - PROCESS { + + begin { } + + process { $params = @{} $customHeaders = New-EntraBetaCustomHeaders -Command $MyInvocation.MyCommand - if ($null -ne $PSBoundParameters["TenantId"]) { - $params["TenantId"] = $PSBoundParameters["TenantId"] + if ($null -ne $PSBoundParameters['TenantId']) { + $params['TenantId'] = $PSBoundParameters['TenantId'] } - Write-Debug("============================ TRANSFORMATIONS ============================") + Write-Debug('============================ TRANSFORMATIONS ============================') $params.Keys | ForEach-Object { "$_ : $($params[$_])" } | Write-Debug Write-Debug("=========================================================================`n") - $Object = @("users", "groups", "contacts") + $Object = @('users', 'groups', 'contacts') $response = @() try { foreach ($obj in $object) { - $obj = ($obj | Out-String).trimend() + $obj = ($obj | Out-String).TrimEnd() $uri = 'https://graph.microsoft.com/beta/' + $obj + '?$select=onPremisesProvisioningErrors' $response += ((Invoke-GraphRequest -Headers $customHeaders -Uri $uri -Method GET).value).onPremisesProvisioningErrors } + } catch { + Write-Error $_.Exception.Message } - catch {} + } + end { if ([string]::IsNullOrWhiteSpace($response)) { - write-host "False" - } - else { + Write-Host 'False' + } else { $response } } } - diff --git a/module/EntraBeta/Microsoft.Entra.Beta/DirectoryManagement/Set-EntraBetaDirSyncFeature.ps1 b/module/EntraBeta/Microsoft.Entra.Beta/DirectoryManagement/Set-EntraBetaDirSyncFeature.ps1 index 031c46e6e..dec44d534 100644 --- a/module/EntraBeta/Microsoft.Entra.Beta/DirectoryManagement/Set-EntraBetaDirSyncFeature.ps1 +++ b/module/EntraBeta/Microsoft.Entra.Beta/DirectoryManagement/Set-EntraBetaDirSyncFeature.ps1 @@ -1,85 +1,87 @@ -# ------------------------------------------------------------------------------ -# Copyright (c) Microsoft Corporation. All Rights Reserved. -# Licensed under the MIT License. See License in the project root for license information. -# ------------------------------------------------------------------------------ +# ------------------------------------------------------------------------------ +# Copyright (c) Microsoft Corporation. All Rights Reserved. +# Licensed under the MIT License. See License in the project root for license information. +# ------------------------------------------------------------------------------ function Set-EntraBetaDirSyncFeature { - [CmdletBinding(DefaultParameterSetName = 'GetQuery')] - param ( - [Parameter(ParameterSetName = "GetQuery", Mandatory = $true, ValueFromPipelineByPropertyName = $true)][System.String] $Feature, - [Parameter(ParameterSetName = "GetQuery", Mandatory = $true, ValueFromPipelineByPropertyName = $true)][System.Boolean] $Enabled, - [Parameter(ParameterSetName = "GetQuery", ValueFromPipelineByPropertyName = $true)][System.Guid] $TenantId, - [switch] $Force - ) - PROCESS { - - $params = @{} - $customHeaders = New-EntraBetaCustomHeaders -Command $MyInvocation.MyCommand - if ($PSBoundParameters.ContainsKey("Verbose")) { - $params["Verbose"] = $Null - } - if ($null -ne $PSBoundParameters["Feature"]) { - $Feature = $PSBoundParameters["Feature"] + "Enabled" - } - if ($null -ne $PSBoundParameters["Enabled"]) { - $Enabled = $PSBoundParameters["Enabled"] - } - if ($PSBoundParameters.ContainsKey("Debug")) { - $params["Debug"] = $PSBoundParameters["Debug"] - } - if($null -ne $PSBoundParameters["WarningVariable"]) - { - $params["WarningVariable"] = $PSBoundParameters["WarningVariable"] - } - if($null -ne $PSBoundParameters["InformationVariable"]) - { - $params["InformationVariable"] = $PSBoundParameters["InformationVariable"] - } - if($null -ne $PSBoundParameters["InformationAction"]) - { - $params["InformationAction"] = $PSBoundParameters["InformationAction"] - } - if($null -ne $PSBoundParameters["OutVariable"]) - { - $params["OutVariable"] = $PSBoundParameters["OutVariable"] - } - if($null -ne $PSBoundParameters["OutBuffer"]) - { - $params["OutBuffer"] = $PSBoundParameters["OutBuffer"] - } - if($null -ne $PSBoundParameters["ErrorVariable"]) - { - $params["ErrorVariable"] = $PSBoundParameters["ErrorVariable"] - } - if($null -ne $PSBoundParameters["PipelineVariable"]) - { - $params["PipelineVariable"] = $PSBoundParameters["PipelineVariable"] - } - if($null -ne $PSBoundParameters["ErrorAction"]) - { - $params["ErrorAction"] = $PSBoundParameters["ErrorAction"] - } - if($null -ne $PSBoundParameters["WarningAction"]) - { - $params["WarningAction"] = $PSBoundParameters["WarningAction"] - } - - Write-Debug("============================ TRANSFORMATIONS ============================") + [CmdletBinding(DefaultParameterSetName = 'GetQuery')] + [OutputType([System.String])] + param ( + [Parameter(ParameterSetName = 'GetQuery', Mandatory = $true, ValueFromPipelineByPropertyName = $true)] + [System.String] + $Feature, + + [Parameter(ParameterSetName = 'GetQuery', Mandatory = $true, ValueFromPipelineByPropertyName = $true)] + [System.Boolean] + $Enabled, + + [Parameter(ParameterSetName = 'GetQuery', ValueFromPipelineByPropertyName = $true)] + [System.Guid] + $TenantId, + + [switch] + $Force + ) + + begin { + $params = @{} + $customHeaders = New-EntraBetaCustomHeaders -Command $MyInvocation.MyCommand + if ($PSBoundParameters.ContainsKey('Verbose')) { + $params['Verbose'] = $Null + } + if ($null -ne $PSBoundParameters['Feature']) { + $Feature = $PSBoundParameters['Feature'] + 'Enabled' + } + if ($null -ne $PSBoundParameters['Enabled']) { + $Enabled = $PSBoundParameters['Enabled'] + } + if ($PSBoundParameters.ContainsKey('Debug')) { + $params['Debug'] = $PSBoundParameters['Debug'] + } + if ($null -ne $PSBoundParameters['WarningVariable']) { + $params['WarningVariable'] = $PSBoundParameters['WarningVariable'] + } + if ($null -ne $PSBoundParameters['InformationVariable']) { + $params['InformationVariable'] = $PSBoundParameters['InformationVariable'] + } + if ($null -ne $PSBoundParameters['InformationAction']) { + $params['InformationAction'] = $PSBoundParameters['InformationAction'] + } + if ($null -ne $PSBoundParameters['OutVariable']) { + $params['OutVariable'] = $PSBoundParameters['OutVariable'] + } + if ($null -ne $PSBoundParameters['OutBuffer']) { + $params['OutBuffer'] = $PSBoundParameters['OutBuffer'] + } + if ($null -ne $PSBoundParameters['ErrorVariable']) { + $params['ErrorVariable'] = $PSBoundParameters['ErrorVariable'] + } + if ($null -ne $PSBoundParameters['PipelineVariable']) { + $params['PipelineVariable'] = $PSBoundParameters['PipelineVariable'] + } + if ($null -ne $PSBoundParameters['ErrorAction']) { + $params['ErrorAction'] = $PSBoundParameters['ErrorAction'] + } + if ($null -ne $PSBoundParameters['WarningAction']) { + $params['WarningAction'] = $PSBoundParameters['WarningAction'] + } + Write-Debug('============================ TRANSFORMATIONS ============================') $params.Keys | ForEach-Object { "$_ : $($params[$_])" } | Write-Debug Write-Debug("=========================================================================`n") + } + + process { if ([string]::IsNullOrWhiteSpace($TenantId)) { $OnPremisesDirectorySynchronizationId = (Get-MgBetaDirectoryOnPremiseSynchronization).Id - } - else { + } else { $OnPremisesDirectorySynchronizationId = Get-MgBetaDirectoryOnPremiseSynchronization -OnPremisesDirectorySynchronizationId $TenantId -ErrorAction SilentlyContinue -ErrorVariable er if ([string]::IsNullOrWhiteSpace($er)) { $OnPremisesDirectorySynchronizationId = $OnPremisesDirectorySynchronizationId.Id - } - else { - throw "Set-EntraBetaDirsyncFeature :$er" + } else { + throw "Set-EntraBetaDirSyncFeature :$er" break } } - + $body = @{ features = @{ $Feature = $Enabled } } @@ -87,34 +89,30 @@ function Set-EntraBetaDirSyncFeature { if ($Force) { # If -Force is used, skip confirmation and proceed with the action. $decision = 0 - } - else { + } else { $title = 'Confirm' $question = 'Do you want to continue?' - $Suspend = new-Object System.Management.Automation.Host.ChoiceDescription "&Suspend", "S" - $Yes = new-Object System.Management.Automation.Host.ChoiceDescription "&Yes", "Y" - $No = new-Object System.Management.Automation.Host.ChoiceDescription "&No", "N" + $Suspend = New-Object System.Management.Automation.Host.ChoiceDescription '&Suspend', 'S' + $Yes = New-Object System.Management.Automation.Host.ChoiceDescription '&Yes', 'Y' + $No = New-Object System.Management.Automation.Host.ChoiceDescription '&No', 'N' $choices = [System.Management.Automation.Host.ChoiceDescription[]]( $Yes, $No, $Suspend) $decision = $Host.UI.PromptForChoice($title, $question, $choices, 1) } if ($decision -eq 0) { - $response = Update-MgBetaDirectoryOnPremiseSynchronization -Headers $customHeaders -OnPremisesDirectorySynchronizationId $OnPremisesDirectorySynchronizationId -BodyParameter $body -ErrorAction SilentlyContinue -ErrorVariable "er" + $response = Update-MgBetaDirectoryOnPremiseSynchronization -Headers $customHeaders -OnPremisesDirectorySynchronizationId $OnPremisesDirectorySynchronizationId -BodyParameter $body -ErrorAction SilentlyContinue -ErrorVariable 'er' $er break if ([string]::IsNullOrWhiteSpace($er)) { $response + } else { + Write-Error "Cannot bind parameter 'TenantId'. Cannot convert value `"$TenantId`" to type + `"System.Guid`". Error: `"Guid should contain 32 digits with 4 dashes (xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx).`"" } - else { - Write-Error "Cannot bind parameter 'TenantId'. Cannot convert value `"$TenantId`" to type - `"System.Guid`". Error: `"Guid should contain 32 digits with 4 dashes (xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx).`" " - } - - } - else { + + } else { return } - - } -} + end { } +} diff --git a/module_legacy/Entra/AdditionalFunctions/Get-EntraAdministrativeUnit.ps1 b/module_legacy/Entra/AdditionalFunctions/Get-EntraAdministrativeUnit.ps1 index 849b52436..f41c26d50 100644 --- a/module_legacy/Entra/AdditionalFunctions/Get-EntraAdministrativeUnit.ps1 +++ b/module_legacy/Entra/AdditionalFunctions/Get-EntraAdministrativeUnit.ps1 @@ -4,47 +4,45 @@ function Get-EntraAdministrativeUnit { [CmdletBinding(DefaultParameterSetName = 'GetQuery')] param ( - [Alias("ObjectId")] - [Parameter(ParameterSetName = "GetById", Mandatory = $true, ValueFromPipeline = $true, ValueFromPipelineByPropertyName = $true)] - [System.String] $AdministrativeUnitId, - [Parameter(ParameterSetName = "GetQuery", ValueFromPipeline = $true, ValueFromPipelineByPropertyName = $true)] - [System.Nullable`1[System.Int32]] $Top, - [Parameter(ValueFromPipeline = $true, ValueFromPipelineByPropertyName = $true)] - [switch] $All, - [Parameter(ParameterSetName = "GetQuery", ValueFromPipeline = $true, ValueFromPipelineByPropertyName = $true)] - [System.String] $Filter + [Alias('ObjectId')] + [Parameter(ParameterSetName = 'GetById', Mandatory = $true, ValueFromPipeline = $true, ValueFromPipelineByPropertyName = $true)] + [System.String] $AdministrativeUnitId, + [Parameter(ParameterSetName = 'GetQuery', ValueFromPipeline = $true, ValueFromPipelineByPropertyName = $true)] + [System.Nullable`1[System.Int32]] $Top, + [Parameter(ValueFromPipeline = $true, ValueFromPipelineByPropertyName = $true)] + [switch] $All, + [Parameter(ParameterSetName = 'GetQuery', ValueFromPipeline = $true, ValueFromPipelineByPropertyName = $true)] + [System.String] $Filter ) - PROCESS { - $params = @{} - $customHeaders = New-EntraCustomHeaders -Command $MyInvocation.MyCommand - $baseUri = "/v1.0/directory/administrativeUnits" - $properties = '$select=*' - $params["Uri"] = "$baseUri/?$properties" - if($null -ne $PSBoundParameters["AdministrativeUnitId"]) - { - $params["AdministrativeUnitId"] = $PSBoundParameters["AdministrativeUnitId"] - $params["Uri"] = "$baseUri/$($params.AdministrativeUnitId)?$properties" - } - if ($PSBoundParameters.ContainsKey("Top")) { - $topCount = $PSBoundParameters["Top"] - if ($topCount -gt 999) { - $params["Uri"] += "&`$top=999" + PROCESS { + $params = @{} + $customHeaders = New-EntraCustomHeaders -Command $MyInvocation.MyCommand + $baseUri = '/v1.0/directory/administrativeUnits' + $properties = '$select=*' + $params['Uri'] = "$baseUri/?$properties" + if ($null -ne $PSBoundParameters['AdministrativeUnitId']) { + $params['AdministrativeUnitId'] = $PSBoundParameters['AdministrativeUnitId'] + $params['Uri'] = "$baseUri/$($params.AdministrativeUnitId)?$properties" } - else { - $params["Uri"] += "&`$top=$topCount" + if ($PSBoundParameters.ContainsKey('Top')) { + $topCount = $PSBoundParameters['Top'] + if ($topCount -gt 999) { + $params['Uri'] += "&`$top=999" + } else { + $params['Uri'] += "&`$top=$topCount" + } + } + if ($null -ne $PSBoundParameters['Filter']) { + $Filter = $PSBoundParameters['Filter'] + $f = '$' + 'Filter' + $params['Uri'] += "&$f=$Filter" } - } - if ($null -ne $PSBoundParameters["Filter"]) { - $Filter = $PSBoundParameters["Filter"] - $f = '$' + 'Filter' - $params["Uri"] += "&$f=$Filter" - } - Write-Debug("============================ TRANSFORMATIONS ============================") + Write-Debug('============================ TRANSFORMATIONS ============================') $params.Keys | ForEach-Object { "$_ : $($params[$_])" } | Write-Debug Write-Debug("=========================================================================`n") - + $response = (Invoke-GraphRequest -Headers $customHeaders -Uri $($params.Uri) -Method GET) $data = $response | ConvertTo-Json -Depth 10 | ConvertFrom-Json @@ -53,24 +51,25 @@ function Get-EntraAdministrativeUnit { $all = $All.IsPresent $increment = $topCount - $data.Count while (($response.'@odata.nextLink' -and (($all -and ($increment -lt 0)) -or $increment -gt 0))) { - $params["Uri"] = $response.'@odata.nextLink' + $params['Uri'] = $response.'@odata.nextLink' if ($increment -gt 0) { $topValue = [Math]::Min($increment, 999) - $params["Uri"] = $params["Uri"].Replace('$top=999', "`$top=$topValue") + $params['Uri'] = $params['Uri'].Replace('$top=999', "`$top=$topValue") $increment -= $topValue } - $response = Invoke-GraphRequest @params + $response = Invoke-GraphRequest @params $data += $response.value | ConvertTo-Json -Depth 10 | ConvertFrom-Json } + } catch { + Write-Error $_.Exception.Message } - catch {} $data | ForEach-Object { if ($null -ne $_) { Add-Member -InputObject $_ -MemberType AliasProperty -Name ObjectId -Value Id Add-Member -InputObject $_ -MemberType AliasProperty -Name DeletionTimeStamp -Value deletedDateTime } } - + if ($data) { $aulist = @() foreach ($item in $data) { @@ -85,4 +84,4 @@ function Get-EntraAdministrativeUnit { $aulist } } -} \ No newline at end of file +} diff --git a/module_legacy/Entra/AdditionalFunctions/Get-EntraAdministrativeUnitMember.ps1 b/module_legacy/Entra/AdditionalFunctions/Get-EntraAdministrativeUnitMember.ps1 index 7bb91f323..6714ad453 100644 --- a/module_legacy/Entra/AdditionalFunctions/Get-EntraAdministrativeUnitMember.ps1 +++ b/module_legacy/Entra/AdditionalFunctions/Get-EntraAdministrativeUnitMember.ps1 @@ -3,14 +3,14 @@ # ------------------------------------------------------------------------------ function Get-EntraAdministrativeUnitMember { [CmdletBinding(DefaultParameterSetName = 'GetQuery')] - param ( - [Parameter(ParameterSetName = "GetQuery", ValueFromPipeline = $true, ValueFromPipelineByPropertyName = $true)] - [System.Nullable`1[System.Int32]] $Top, - [Alias("ObjectId")] - [Parameter(Mandatory = $true, ValueFromPipeline = $true, ValueFromPipelineByPropertyName = $true)] - [System.String] $AdministrativeUnitId, - [Parameter(ValueFromPipeline = $true, ValueFromPipelineByPropertyName = $true)] - [switch] $All + param ( + [Parameter(ParameterSetName = 'GetQuery', ValueFromPipeline = $true, ValueFromPipelineByPropertyName = $true)] + [System.Nullable`1[System.Int32]] $Top, + [Alias('ObjectId')] + [Parameter(Mandatory = $true, ValueFromPipeline = $true, ValueFromPipelineByPropertyName = $true)] + [System.String] $AdministrativeUnitId, + [Parameter(ValueFromPipeline = $true, ValueFromPipelineByPropertyName = $true)] + [switch] $All ) PROCESS { @@ -18,23 +18,21 @@ function Get-EntraAdministrativeUnitMember { $topCount = $null $customHeaders = New-EntraCustomHeaders -Command $MyInvocation.MyCommand $baseUri = "/v1.0/directory/administrativeUnits/$AdministrativeUnitId/members?`$select=*" - $params["Uri"] = "$baseUri" - if($null -ne $PSBoundParameters["AdministrativeUnitId"]) - { - $params["AdministrativeUnitId"] = $PSBoundParameters["AdministrativeUnitId"] + $params['Uri'] = "$baseUri" + if ($null -ne $PSBoundParameters['AdministrativeUnitId']) { + $params['AdministrativeUnitId'] = $PSBoundParameters['AdministrativeUnitId'] } - if ($PSBoundParameters.ContainsKey("Top")) { - $topCount = $PSBoundParameters["Top"] + if ($PSBoundParameters.ContainsKey('Top')) { + $topCount = $PSBoundParameters['Top'] if ($topCount -gt 999) { $minTop = 999 - $params["Uri"] += "&`$top=999" - } - else { - $params["Uri"] += "&`$top=$topCount" + $params['Uri'] += "&`$top=999" + } else { + $params['Uri'] += "&`$top=$topCount" } } - Write-Debug("============================ TRANSFORMATIONS ============================") + Write-Debug('============================ TRANSFORMATIONS ============================') $params.Keys | ForEach-Object { "$_ : $($params[$_])" } | Write-Debug Write-Debug("=========================================================================`n") @@ -46,22 +44,22 @@ function Get-EntraAdministrativeUnitMember { $all = $All.IsPresent $increment = $topCount - $data.Count while (($response.'@odata.nextLink' -and (($all -and ($increment -lt 0)) -or $increment -gt 0))) { - $params["Uri"] = $response.'@odata.nextLink' + $params['Uri'] = $response.'@odata.nextLink' if ($increment -gt 0) { $topValue = [Math]::Min($increment, 999) if ($minTop) { - $params["Uri"] = $params["Uri"].Replace("`$top=$minTop", "`$top=$topValue") - } - else { - $params["Uri"] = $params["Uri"].Replace("`$top=$topCount", "`$top=$topValue") + $params['Uri'] = $params['Uri'].Replace("`$top=$minTop", "`$top=$topValue") + } else { + $params['Uri'] = $params['Uri'].Replace("`$top=$topCount", "`$top=$topValue") } $increment -= $topValue } $response = (Invoke-GraphRequest -Headers $customHeaders -Uri $($params.Uri) -Method GET) $data += $response.value | ConvertTo-Json -Depth 10 | ConvertFrom-Json } + } catch { + Write-Error $_.Exception.Message } - catch {} $data | ForEach-Object { if ($null -ne $_) { Add-Member -InputObject $_ -MemberType AliasProperty -Name ObjectId -Value Id @@ -84,4 +82,4 @@ function Get-EntraAdministrativeUnitMember { $memberList } } -} \ No newline at end of file +} diff --git a/module_legacy/Entra/AdditionalFunctions/Get-EntraAttributeSet.ps1 b/module_legacy/Entra/AdditionalFunctions/Get-EntraAttributeSet.ps1 index cdccf1849..e0b0f438f 100644 --- a/module_legacy/Entra/AdditionalFunctions/Get-EntraAttributeSet.ps1 +++ b/module_legacy/Entra/AdditionalFunctions/Get-EntraAttributeSet.ps1 @@ -5,34 +5,34 @@ function Get-EntraAttributeSet { [CmdletBinding(DefaultParameterSetName = 'GetQuery')] param ( - [Parameter(ParameterSetName = "GetById", Mandatory = $true, ValueFromPipeline = $true, ValueFromPipelineByPropertyName = $true)] - [Alias("Id")] + [Parameter(ParameterSetName = 'GetById', Mandatory = $true, ValueFromPipeline = $true, ValueFromPipelineByPropertyName = $true)] + [Alias('Id')] [System.String] $AttributeSetId ) PROCESS { $params = @{} $customHeaders = New-EntraCustomHeaders -Command $MyInvocation.MyCommand - $params["Uri"] = "https://graph.microsoft.com/v1.0/directory/attributeSets/" - $params["Method"] = "GET" - if ($null -ne $PSBoundParameters["AttributeSetId"]) { - $params["Uri"] += $AttributeSetId + $params['Uri'] = 'https://graph.microsoft.com/v1.0/directory/attributeSets/' + $params['Method'] = 'GET' + if ($null -ne $PSBoundParameters['AttributeSetId']) { + $params['Uri'] += $AttributeSetId } - Write-Debug("============================ TRANSFORMATIONS ============================") + Write-Debug('============================ TRANSFORMATIONS ============================') $params.Keys | ForEach-Object { "$_ : $($params[$_])" } | Write-Debug Write-Debug("=========================================================================`n") $response = Invoke-GraphRequest @params -Headers $customHeaders | ConvertTo-Json | ConvertFrom-Json try { $response = $response.value + } catch { + Write-Error $_.Exception.Message } - catch {} - if($response) - { + if ($response) { $userList = @() foreach ($data in $response) { $userType = New-Object Microsoft.Graph.PowerShell.Models.MicrosoftGraphAttributeSet $data.PSObject.Properties | ForEach-Object { - $propertyName = $_.Name.Substring(0,1).ToUpper() + $_.Name.Substring(1) + $propertyName = $_.Name.Substring(0, 1).ToUpper() + $_.Name.Substring(1) $propertyValue = $_.Value $userType | Add-Member -MemberType NoteProperty -Name $propertyName -Value $propertyValue -Force } @@ -41,4 +41,4 @@ function Get-EntraAttributeSet { $userList } } -} \ No newline at end of file +} diff --git a/module_legacy/Entra/AdditionalFunctions/Get-EntraAuditDirectoryLog.ps1 b/module_legacy/Entra/AdditionalFunctions/Get-EntraAuditDirectoryLog.ps1 index 2b6b69b3c..6d895093c 100644 --- a/module_legacy/Entra/AdditionalFunctions/Get-EntraAuditDirectoryLog.ps1 +++ b/module_legacy/Entra/AdditionalFunctions/Get-EntraAuditDirectoryLog.ps1 @@ -5,14 +5,14 @@ function Get-EntraAuditDirectoryLog { [CmdletBinding(DefaultParameterSetName = 'GetQuery')] param ( - [Parameter(ParameterSetName = "GetById", ValueFromPipeline = $true, ValueFromPipelineByPropertyName = $true)] - [System.String] $Id, - [Parameter(ParameterSetName = "GetQuery", ValueFromPipeline = $true, ValueFromPipelineByPropertyName = $true)] - [System.Int32] $Top, - [Parameter(ValueFromPipeline = $true, ValueFromPipelineByPropertyName = $true)] - [switch] $All, - [Parameter(ParameterSetName = "GetQuery", ValueFromPipeline = $true, ValueFromPipelineByPropertyName = $true)] - [System.String] $Filter + [Parameter(ParameterSetName = 'GetById', ValueFromPipeline = $true, ValueFromPipelineByPropertyName = $true)] + [System.String] $Id, + [Parameter(ParameterSetName = 'GetQuery', ValueFromPipeline = $true, ValueFromPipelineByPropertyName = $true)] + [System.Int32] $Top, + [Parameter(ValueFromPipeline = $true, ValueFromPipelineByPropertyName = $true)] + [switch] $All, + [Parameter(ParameterSetName = 'GetQuery', ValueFromPipeline = $true, ValueFromPipelineByPropertyName = $true)] + [System.String] $Filter ) PROCESS { @@ -20,33 +20,29 @@ function Get-EntraAuditDirectoryLog { $params = @{} $topCount = $null $baseUri = 'https://graph.microsoft.com/v1.0/auditLogs/directoryAudits' - $params["Method"] = "GET" - $params["Uri"] = "$baseUri"+"?" + $params['Method'] = 'GET' + $params['Uri'] = "$baseUri" + '?' - if($PSBoundParameters.ContainsKey("Top")) - { - $topCount = $PSBoundParameters["Top"] + if ($PSBoundParameters.ContainsKey('Top')) { + $topCount = $PSBoundParameters['Top'] if ($topCount -gt 999) { - $params["Uri"] += "&`$top=999" - } - else{ - $params["Uri"] += "&`$top=$topCount" + $params['Uri'] += "&`$top=999" + } else { + $params['Uri'] += "&`$top=$topCount" } } - if($null -ne $PSBoundParameters["Id"]) - { - $LogId = $PSBoundParameters["Id"] - $params["Uri"] = "$baseUri/$($LogId)" + if ($null -ne $PSBoundParameters['Id']) { + $LogId = $PSBoundParameters['Id'] + $params['Uri'] = "$baseUri/$($LogId)" } - if($null -ne $PSBoundParameters["Filter"]) - { - $Filter = $PSBoundParameters["Filter"] + if ($null -ne $PSBoundParameters['Filter']) { + $Filter = $PSBoundParameters['Filter'] $f = '$Filter' - $params["Uri"] += "&$f=$Filter" + $params['Uri'] += "&$f=$Filter" } - Write-Debug("============================ TRANSFORMATIONS ============================") - $params.Keys | ForEach-Object {"$_ : $($params[$_])" } | Write-Debug + Write-Debug('============================ TRANSFORMATIONS ============================') + $params.Keys | ForEach-Object { "$_ : $($params[$_])" } | Write-Debug Write-Debug("=========================================================================`n") $response = Invoke-GraphRequest @params -Headers $customHeaders @@ -56,16 +52,18 @@ function Get-EntraAuditDirectoryLog { $all = $All.IsPresent $increment = $topCount - $data.Count while (($response.'@odata.nextLink' -and (($all -and ($increment -lt 0)) -or $increment -gt 0))) { - $params["Uri"] = $response.'@odata.nextLink' + $params['Uri'] = $response.'@odata.nextLink' if ($increment -gt 0) { $topValue = [Math]::Min($increment, 999) - $params["Uri"] = $params["Uri"].Replace('$top=999', "`$top=$topValue") + $params['Uri'] = $params['Uri'].Replace('$top=999', "`$top=$topValue") $increment -= $topValue } $response = Invoke-GraphRequest @params $data += $response.value | ConvertTo-Json -Depth 10 | ConvertFrom-Json } - } catch {} + } catch { + Write-Error $_.Exception.Message + } $userList = @() foreach ($response in $data) { @@ -79,4 +77,4 @@ function Get-EntraAuditDirectoryLog { } $userList } -} \ No newline at end of file +} diff --git a/module_legacy/Entra/AdditionalFunctions/Get-EntraAuditSignInLog.ps1 b/module_legacy/Entra/AdditionalFunctions/Get-EntraAuditSignInLog.ps1 index 5686e768d..b6790c942 100644 --- a/module_legacy/Entra/AdditionalFunctions/Get-EntraAuditSignInLog.ps1 +++ b/module_legacy/Entra/AdditionalFunctions/Get-EntraAuditSignInLog.ps1 @@ -5,15 +5,15 @@ function Get-EntraAuditSignInLog { [CmdletBinding(DefaultParameterSetName = 'GetQuery')] param ( - [Parameter(ParameterSetName = "GetById", ValueFromPipeline = $true, ValueFromPipelineByPropertyName = $true)] - [Alias("Id")] - [System.String] $SignInId, - [Parameter(ParameterSetName = "GetQuery", ValueFromPipeline = $true, ValueFromPipelineByPropertyName = $true)] - [System.Int32] $Top, - [Parameter(ValueFromPipeline = $true, ValueFromPipelineByPropertyName = $true)] - [switch] $All, - [Parameter(ParameterSetName = "GetQuery", ValueFromPipeline = $true, ValueFromPipelineByPropertyName = $true)] - [System.String] $Filter + [Parameter(ParameterSetName = 'GetById', ValueFromPipeline = $true, ValueFromPipelineByPropertyName = $true)] + [Alias('Id')] + [System.String] $SignInId, + [Parameter(ParameterSetName = 'GetQuery', ValueFromPipeline = $true, ValueFromPipelineByPropertyName = $true)] + [System.Int32] $Top, + [Parameter(ValueFromPipeline = $true, ValueFromPipelineByPropertyName = $true)] + [switch] $All, + [Parameter(ParameterSetName = 'GetQuery', ValueFromPipeline = $true, ValueFromPipelineByPropertyName = $true)] + [System.String] $Filter ) PROCESS { @@ -21,41 +21,36 @@ function Get-EntraAuditSignInLog { $params = @{} $topCount = $null $baseUri = 'https://graph.microsoft.com/v1.0/auditLogs/signIns' - $params["Method"] = "GET" - $params["Uri"] = "$baseUri" + $params['Method'] = 'GET' + $params['Uri'] = "$baseUri" $query = $null - if($PSBoundParameters.ContainsKey("Top")) - { - $topCount = $PSBoundParameters["Top"] + if ($PSBoundParameters.ContainsKey('Top')) { + $topCount = $PSBoundParameters['Top'] if ($topCount -gt 999) { $query += "&`$top=999" - } - else{ + } else { $query += "&`$top=$topCount" } } - if($null -ne $PSBoundParameters["SignInId"]) - { - $logId = $PSBoundParameters["SignInId"] - $params["Uri"] = "$baseUri/$($logId)" + if ($null -ne $PSBoundParameters['SignInId']) { + $logId = $PSBoundParameters['SignInId'] + $params['Uri'] = "$baseUri/$($logId)" } - if($null -ne $PSBoundParameters["Filter"]) - { - $Filter = $PSBoundParameters["Filter"] + if ($null -ne $PSBoundParameters['Filter']) { + $Filter = $PSBoundParameters['Filter'] $f = '$filter' $query += "&$f=$Filter" } - if($null -ne $query) - { - $query = "?" + $query.TrimStart("&") - $params["Uri"] += $query + if ($null -ne $query) { + $query = '?' + $query.TrimStart('&') + $params['Uri'] += $query } - Write-Debug("============================ TRANSFORMATIONS ============================") - $params.Keys | ForEach-Object {"$_ : $($params[$_])" } | Write-Debug + Write-Debug('============================ TRANSFORMATIONS ============================') + $params.Keys | ForEach-Object { "$_ : $($params[$_])" } | Write-Debug Write-Debug("=========================================================================`n") $response = Invoke-GraphRequest @params -Headers $customHeaders @@ -65,16 +60,18 @@ function Get-EntraAuditSignInLog { $all = $All.IsPresent $increment = $topCount - $data.Count while (($response.'@odata.nextLink' -and (($all -and ($increment -lt 0)) -or $increment -gt 0))) { - $params["Uri"] = $response.'@odata.nextLink' + $params['Uri'] = $response.'@odata.nextLink' if ($increment -gt 0) { $topValue = [Math]::Min($increment, 999) - $params["Uri"] = $params["Uri"].Replace('$top=999', "`$top=$topValue") + $params['Uri'] = $params['Uri'].Replace('$top=999', "`$top=$topValue") $increment -= $topValue } $response = Invoke-GraphRequest @params $data += $response.value | ConvertTo-Json -Depth 100 | ConvertFrom-Json } - } catch {} + } catch { + Write-Error $_.Exception.Message + } $userList = @() foreach ($response in $data) { $userType = New-Object Microsoft.Graph.PowerShell.Models.MicrosoftGraphSignIn @@ -87,4 +84,4 @@ function Get-EntraAuditSignInLog { } $userList } -} \ No newline at end of file +} diff --git a/module_legacy/Entra/AdditionalFunctions/Get-EntraCustomSecurityAttributeDefinition.ps1 b/module_legacy/Entra/AdditionalFunctions/Get-EntraCustomSecurityAttributeDefinition.ps1 index 47113ca5c..11a5b8166 100644 --- a/module_legacy/Entra/AdditionalFunctions/Get-EntraCustomSecurityAttributeDefinition.ps1 +++ b/module_legacy/Entra/AdditionalFunctions/Get-EntraCustomSecurityAttributeDefinition.ps1 @@ -4,30 +4,31 @@ function Get-EntraCustomSecurityAttributeDefinition { [CmdletBinding(DefaultParameterSetName = 'GetQuery')] param ( - [Parameter(ParameterSetName = "GetById", Mandatory = $true, ValueFromPipeline = $true, ValueFromPipelineByPropertyName = $true)] + [Parameter(ParameterSetName = 'GetById', Mandatory = $true, ValueFromPipeline = $true, ValueFromPipelineByPropertyName = $true)] [System.String] $Id ) - PROCESS { + PROCESS { $params = @{} - $Method = "GET" - $Uri = "https://graph.microsoft.com/v1.0/directory/customSecurityAttributeDefinitions/" + $Method = 'GET' + $Uri = 'https://graph.microsoft.com/v1.0/directory/customSecurityAttributeDefinitions/' $customHeaders = New-EntraCustomHeaders -Command $MyInvocation.MyCommand - - if ($null -ne $PSBoundParameters["Id"]) { + + if ($null -ne $PSBoundParameters['Id']) { $Uri += $Id } - Write-Debug("============================ TRANSFORMATIONS ============================") + Write-Debug('============================ TRANSFORMATIONS ============================') $params.Keys | ForEach-Object { "$_ : $($params[$_])" } | Write-Debug Write-Debug("=========================================================================`n") - + $response = (Invoke-GraphRequest -Uri $Uri -Method $Method -Headers $customHeaders) | ConvertTo-Json | ConvertFrom-Json - try { - $response = $response.value + try { + $response = $response.value + } catch { + Write-Error $_.Exception.Message } - catch {} - if($response){ + if ($response) { $userList = @() foreach ($data in $response) { $userType = New-Object Microsoft.Graph.PowerShell.Models.MicrosoftGraphCustomSecurityAttributeDefinition @@ -39,6 +40,6 @@ function Get-EntraCustomSecurityAttributeDefinition { $userList += $userType } $userList - } + } } -} \ No newline at end of file +} diff --git a/module_legacy/Entra/AdditionalFunctions/Get-EntraCustomSecurityAttributeDefinitionAllowedValue.ps1 b/module_legacy/Entra/AdditionalFunctions/Get-EntraCustomSecurityAttributeDefinitionAllowedValue.ps1 index b2a2620f4..610805946 100644 --- a/module_legacy/Entra/AdditionalFunctions/Get-EntraCustomSecurityAttributeDefinitionAllowedValue.ps1 +++ b/module_legacy/Entra/AdditionalFunctions/Get-EntraCustomSecurityAttributeDefinitionAllowedValue.ps1 @@ -4,43 +4,43 @@ function Get-EntraCustomSecurityAttributeDefinitionAllowedValue { [CmdletBinding(DefaultParameterSetName = 'GetQuery')] param ( - [Parameter(ParameterSetName = "GetById", Mandatory = $true, ValueFromPipeline = $true, ValueFromPipelineByPropertyName = $true)] + [Parameter(ParameterSetName = 'GetById', Mandatory = $true, ValueFromPipeline = $true, ValueFromPipelineByPropertyName = $true)] [System.String] $Id, - [Parameter(ParameterSetName = "GetQuery", ValueFromPipeline = $true, ValueFromPipelineByPropertyName = $true)] + [Parameter(ParameterSetName = 'GetQuery', ValueFromPipeline = $true, ValueFromPipelineByPropertyName = $true)] [System.String] $Filter, [Parameter(Mandatory = $true, ValueFromPipeline = $true, ValueFromPipelineByPropertyName = $true)] [System.String] $CustomSecurityAttributeDefinitionId ) - PROCESS { + PROCESS { $params = @{} - $params["Uri"] = "https://graph.microsoft.com/v1.0/directory/customSecurityAttributeDefinitions/$CustomSecurityAttributeDefinitionId/allowedValues/" - $params["Method"] = "GET" + $params['Uri'] = "https://graph.microsoft.com/v1.0/directory/customSecurityAttributeDefinitions/$CustomSecurityAttributeDefinitionId/allowedValues/" + $params['Method'] = 'GET' $customHeaders = New-EntraCustomHeaders -Command $MyInvocation.MyCommand - if ($null -ne $PSBoundParameters["Id"]) { - $params["Uri"] += $Id + if ($null -ne $PSBoundParameters['Id']) { + $params['Uri'] += $Id } - if ($null -ne $PSBoundParameters["Filter"]) { - $params["Uri"] += '?$filter=' + $Filter + if ($null -ne $PSBoundParameters['Filter']) { + $params['Uri'] += '?$filter=' + $Filter } - Write-Debug("============================ TRANSFORMATIONS ============================") + Write-Debug('============================ TRANSFORMATIONS ============================') $params.Keys | ForEach-Object { "$_ : $($params[$_])" } | Write-Debug Write-Debug("=========================================================================`n") - - $response = (Invoke-GraphRequest @params -Headers $customHeaders) | ConvertTo-Json -Depth 5 | ConvertFrom-Json - try { - $response = $response.value + + $response = (Invoke-GraphRequest @params -Headers $customHeaders) | ConvertTo-Json -Depth 5 | ConvertFrom-Json + try { + $response = $response.value + } catch { + Write-Error $_.Exception.Message } - catch {} - if($response) - { + if ($response) { $userList = @() foreach ($data in $response) { $userType = New-Object Microsoft.Graph.PowerShell.Models.MicrosoftGraphAllowedValue $data.PSObject.Properties | ForEach-Object { - $propertyName = $_.Name.Substring(0,1).ToUpper() + $_.Name.Substring(1) + $propertyName = $_.Name.Substring(0, 1).ToUpper() + $_.Name.Substring(1) $propertyValue = $_.Value $userType | Add-Member -MemberType NoteProperty -Name $propertyName -Value $propertyValue -Force } @@ -49,4 +49,4 @@ function Get-EntraCustomSecurityAttributeDefinitionAllowedValue { $userList } } -} \ No newline at end of file +} diff --git a/module_legacy/Entra/AdditionalFunctions/Get-EntraDirectoryObjectOnPremisesProvisioningError.ps1 b/module_legacy/Entra/AdditionalFunctions/Get-EntraDirectoryObjectOnPremisesProvisioningError.ps1 index 5d1d03af9..4816031db 100644 --- a/module_legacy/Entra/AdditionalFunctions/Get-EntraDirectoryObjectOnPremisesProvisioningError.ps1 +++ b/module_legacy/Entra/AdditionalFunctions/Get-EntraDirectoryObjectOnPremisesProvisioningError.ps1 @@ -5,36 +5,35 @@ function Get-EntraDirectoryObjectOnPremisesProvisioningError { [CmdletBinding(DefaultParameterSetName = 'GetById')] param ( - [Parameter(ParameterSetName = "GetById")][ValidateNotNullOrEmpty()][ValidateScript({if ($_ -is [System.Guid]) { $true } else {throw "TenantId must be of type [System.Guid]."}})][System.Guid] $TenantId + [Parameter(ParameterSetName = 'GetById')][ValidateNotNullOrEmpty()][ValidateScript({ if ($_ -is [System.Guid]) { $true } else { throw 'TenantId must be of type [System.Guid].' } })][System.Guid] $TenantId ) - PROCESS { + PROCESS { $params = @{} - $customHeaders = New-EntraCustomHeaders -Command $MyInvocation.MyCommand - if ($null -ne $PSBoundParameters["TenantId"]) { - $params["TenantId"] = $PSBoundParameters["TenantId"] - } - Write-Debug("============================ TRANSFORMATIONS ============================") + $customHeaders = New-EntraCustomHeaders -Command $MyInvocation.MyCommand + if ($null -ne $PSBoundParameters['TenantId']) { + $params['TenantId'] = $PSBoundParameters['TenantId'] + } + Write-Debug('============================ TRANSFORMATIONS ============================') $params.Keys | ForEach-Object { "$_ : $($params[$_])" } | Write-Debug Write-Debug("=========================================================================`n") - $Object = @("users", "groups", "contacts") + $Object = @('users', 'groups', 'contacts') $response = @() - + try { foreach ($obj in $object) { $obj = ($obj | Out-String).trimend() $uri = 'https://graph.microsoft.com/v1.0/' + $obj + '?$select=onPremisesProvisioningErrors' $response += ((Invoke-GraphRequest -Headers $customHeaders -Uri $uri -Method GET).value).onPremisesProvisioningErrors } + } catch { + Write-Error $_.Exception.Message } - catch {} if ([string]::IsNullOrWhiteSpace($response)) { - write-host "False" - } - else { + Write-Host 'False' + } else { $response } - + } } Set-Alias -Name Get-EntraHasObjectsWithDirSyncProvisioningError -Value Get-EntraDirectoryObjectOnPremisesProvisioningError -Scope Global -Force - diff --git a/module_legacy/Entra/AdditionalFunctions/Get-EntraFeatureRolloutPolicy.ps1 b/module_legacy/Entra/AdditionalFunctions/Get-EntraFeatureRolloutPolicy.ps1 index 1b32be76c..4fdf2022a 100644 --- a/module_legacy/Entra/AdditionalFunctions/Get-EntraFeatureRolloutPolicy.ps1 +++ b/module_legacy/Entra/AdditionalFunctions/Get-EntraFeatureRolloutPolicy.ps1 @@ -4,66 +4,61 @@ function Get-EntraFeatureRolloutPolicy { [CmdletBinding(DefaultParameterSetName = 'GetQuery')] param ( - [Parameter(ParameterSetName = "GetById", Mandatory = $true, ValueFromPipeline = $true, ValueFromPipelineByPropertyName = $true)] - [System.String] $Id, - [Parameter(ParameterSetName = "GetVague", ValueFromPipeline = $true, ValueFromPipelineByPropertyName = $true)] - [System.String] $SearchString, - [Parameter(ParameterSetName = "GetQuery", ValueFromPipeline = $true, ValueFromPipelineByPropertyName = $true)] - [System.String] $Filter, - [Parameter(Mandatory = $false, ValueFromPipeline = $false, ValueFromPipelineByPropertyName = $true)] - [System.String[]] $Property + [Parameter(ParameterSetName = 'GetById', Mandatory = $true, ValueFromPipeline = $true, ValueFromPipelineByPropertyName = $true)] + [System.String] $Id, + [Parameter(ParameterSetName = 'GetVague', ValueFromPipeline = $true, ValueFromPipelineByPropertyName = $true)] + [System.String] $SearchString, + [Parameter(ParameterSetName = 'GetQuery', ValueFromPipeline = $true, ValueFromPipelineByPropertyName = $true)] + [System.String] $Filter, + [Parameter(Mandatory = $false, ValueFromPipeline = $false, ValueFromPipelineByPropertyName = $true)] + [System.String[]] $Property ) PROCESS { $customHeaders = New-EntraCustomHeaders -Command $MyInvocation.MyCommand $params = @{} $baseUri = 'https://graph.microsoft.com/v1.0/policies/featureRolloutPolicies' - $params["Method"] = "GET" - $params["Uri"] = "$baseUri" + $params['Method'] = 'GET' + $params['Uri'] = "$baseUri" $query = $null - - if($null -ne $PSBoundParameters["Id"]) - { - $Id = $PSBoundParameters["Id"] - $params["Uri"] = "https://graph.microsoft.com/v1.0/policies/featureRolloutPolicies/$Id" + + if ($null -ne $PSBoundParameters['Id']) { + $Id = $PSBoundParameters['Id'] + $params['Uri'] = "https://graph.microsoft.com/v1.0/policies/featureRolloutPolicies/$Id" } - if($null -ne $PSBoundParameters["SearchString"]) - { - $FilterValue = $PSBoundParameters["SearchString"] - $filter="displayName eq '$FilterValue' or startswith(displayName,'$FilterValue')" + if ($null -ne $PSBoundParameters['SearchString']) { + $FilterValue = $PSBoundParameters['SearchString'] + $filter = "displayName eq '$FilterValue' or startswith(displayName,'$FilterValue')" $f = '$' + 'Filter' $query += "&$f=$Filter" } - if($null -ne $PSBoundParameters["Filter"]) - { - $Filter = $PSBoundParameters["Filter"] + if ($null -ne $PSBoundParameters['Filter']) { + $Filter = $PSBoundParameters['Filter'] $f = '$' + 'Filter' $query += "&$f=$Filter" - } - if($null -ne $PSBoundParameters["Property"]) - { - $selectProperties = $PSBoundParameters["Property"] + } + if ($null -ne $PSBoundParameters['Property']) { + $selectProperties = $PSBoundParameters['Property'] $selectProperties = $selectProperties -Join ',' $query += "&`$select=$($selectProperties)" } - if($null -ne $query) - { - $query = "?" + $query.TrimStart("&") - $params["Uri"] += $query + if ($null -ne $query) { + $query = '?' + $query.TrimStart('&') + $params['Uri'] += $query } - - Write-Debug("============================ TRANSFORMATIONS ============================") - $params.Keys | ForEach-Object {"$_ : $($params[$_])" } | Write-Debug + + Write-Debug('============================ TRANSFORMATIONS ============================') + $params.Keys | ForEach-Object { "$_ : $($params[$_])" } | Write-Debug Write-Debug("=========================================================================`n") - + $data = Invoke-GraphRequest @params -Headers $customHeaders | ConvertTo-Json | ConvertFrom-Json - try { + try { $data = $data.value | ConvertTo-Json | ConvertFrom-Json + } catch { + Write-Error $_.Exception.Message } - catch {} - if($data) - { + if ($data) { $userList = @() foreach ($response in $data) { $userType = New-Object Microsoft.Graph.PowerShell.Models.MicrosoftGraphFeatureRolloutPolicy @@ -77,4 +72,4 @@ function Get-EntraFeatureRolloutPolicy { $userList } } -} \ No newline at end of file +} diff --git a/module_legacy/Entra/AdditionalFunctions/Get-EntraObjectSetting.ps1 b/module_legacy/Entra/AdditionalFunctions/Get-EntraObjectSetting.ps1 index faf51a15f..dacf4401a 100644 --- a/module_legacy/Entra/AdditionalFunctions/Get-EntraObjectSetting.ps1 +++ b/module_legacy/Entra/AdditionalFunctions/Get-EntraObjectSetting.ps1 @@ -4,8 +4,8 @@ function Get-EntraObjectSetting { [CmdletBinding(DefaultParameterSetName = 'GetQuery')] param ( - [Parameter(ParameterSetName = "GetById", Mandatory = $true, ValueFromPipeline = $true, ValueFromPipelineByPropertyName = $true)][System.String] $Id, - [Parameter(ParameterSetName = "GetQuery", ValueFromPipeline = $true, ValueFromPipelineByPropertyName = $true)] + [Parameter(ParameterSetName = 'GetById', Mandatory = $true, ValueFromPipeline = $true, ValueFromPipelineByPropertyName = $true)][System.String] $Id, + [Parameter(ParameterSetName = 'GetQuery', ValueFromPipeline = $true, ValueFromPipelineByPropertyName = $true)] [System.Int32] $Top, [Parameter(ValueFromPipeline = $true, ValueFromPipelineByPropertyName = $true)] [switch] $All, @@ -22,32 +22,28 @@ function Get-EntraObjectSetting { $params = @{} $topCount = $null $baseUri = "https://graph.microsoft.com/v1.0/$TargetType/$TargetObjectId/settings" - $params["Method"] = "GET" - $params["Uri"] = $baseUri+'?$select=*' - if($null -ne $PSBoundParameters["Property"]) - { - $selectProperties = $PSBoundParameters["Property"] + $params['Method'] = 'GET' + $params['Uri'] = $baseUri + '?$select=*' + if ($null -ne $PSBoundParameters['Property']) { + $selectProperties = $PSBoundParameters['Property'] $selectProperties = $selectProperties -Join ',' - $params["Uri"] = $baseUri+"?`$select=$($selectProperties)" + $params['Uri'] = $baseUri + "?`$select=$($selectProperties)" } - if($PSBoundParameters.ContainsKey("Top") -and (-not $PSBoundParameters.ContainsKey("All"))) - { - $topCount = $PSBoundParameters["Top"] + if ($PSBoundParameters.ContainsKey('Top') -and (-not $PSBoundParameters.ContainsKey('All'))) { + $topCount = $PSBoundParameters['Top'] if ($topCount -gt 999) { - $params["Uri"] += "&`$top=999" - } - else{ - $params["Uri"] += "&`$top=$topCount" + $params['Uri'] += "&`$top=999" + } else { + $params['Uri'] += "&`$top=$topCount" } } - if($null -ne $PSBoundParameters["Id"]) - { - $Id = $PSBoundParameters["Id"] - $params["Uri"] = "$baseUri/$($Id)" + if ($null -ne $PSBoundParameters['Id']) { + $Id = $PSBoundParameters['Id'] + $params['Uri'] = "$baseUri/$($Id)" } - Write-Debug("============================ TRANSFORMATIONS ============================") - $params.Keys | ForEach-Object {"$_ : $($params[$_])" } | Write-Debug + Write-Debug('============================ TRANSFORMATIONS ============================') + $params.Keys | ForEach-Object { "$_ : $($params[$_])" } | Write-Debug Write-Debug("=========================================================================`n") $response = Invoke-GraphRequest @params -Headers $customHeaders @@ -57,24 +53,26 @@ function Get-EntraObjectSetting { $all = $All.IsPresent $increment = $topCount - $data.Count while ($response.'@odata.nextLink' -and (($all) -or ($increment -gt 0 -and -not $all))) { - $params["Uri"] = $response.'@odata.nextLink' + $params['Uri'] = $response.'@odata.nextLink' if (-not $all) { $topValue = [Math]::Min($increment, 999) - $params["Uri"] = $params["Uri"].Replace('$top=999', "`$top=$topValue") + $params['Uri'] = $params['Uri'].Replace('$top=999', "`$top=$topValue") $increment -= $topValue } $response = Invoke-GraphRequest @params $data += $response.value | ConvertTo-Json -Depth 10 | ConvertFrom-Json } - } catch {} + } catch { + Write-Error $_.Exception.Message + } $targetTypeList = @() - if($TargetType.ToLower() -eq 'groups'){ - foreach($res in $data){ + if ($TargetType.ToLower() -eq 'groups') { + foreach ($res in $data) { $groupType = New-Object Microsoft.Graph.PowerShell.Models.MicrosoftGraphGroupSetting $res.PSObject.Properties | ForEach-Object { - $propertyName = $_.Name.Substring(0,1).ToUpper() + $_.Name.Substring(1) + $propertyName = $_.Name.Substring(0, 1).ToUpper() + $_.Name.Substring(1) $propertyValue = $_.Value $groupType | Add-Member -MemberType NoteProperty -Name $propertyName -Value $propertyValue -Force } @@ -82,11 +80,11 @@ function Get-EntraObjectSetting { } } - if($TargetType.ToLower() -eq 'users'){ - foreach($res in $data){ + if ($TargetType.ToLower() -eq 'users') { + foreach ($res in $data) { $userType = New-Object Microsoft.Graph.PowerShell.Models.MicrosoftGraphUserSettings $res.PSObject.Properties | ForEach-Object { - $propertyName = $_.Name.Substring(0,1).ToUpper() + $_.Name.Substring(1) + $propertyName = $_.Name.Substring(0, 1).ToUpper() + $_.Name.Substring(1) $propertyValue = $_.Value $userType | Add-Member -MemberType NoteProperty -Name $propertyName -Value $propertyValue -Force } @@ -96,4 +94,4 @@ function Get-EntraObjectSetting { $targetTypeList } -} \ No newline at end of file +} diff --git a/module_legacy/Entra/AdditionalFunctions/Remove-EntraPolicy.ps1 b/module_legacy/Entra/AdditionalFunctions/Remove-EntraPolicy.ps1 index 4dab294b7..c7ecfc6ee 100644 --- a/module_legacy/Entra/AdditionalFunctions/Remove-EntraPolicy.ps1 +++ b/module_legacy/Entra/AdditionalFunctions/Remove-EntraPolicy.ps1 @@ -4,39 +4,41 @@ function Remove-EntraPolicy { [CmdletBinding(DefaultParameterSetName = '')] param ( - [Parameter(Mandatory = $true, ValueFromPipeline = $true, ValueFromPipelineByPropertyName = $true)] - [System.String] $Id + [Parameter(Mandatory = $true, ValueFromPipeline = $true, ValueFromPipelineByPropertyName = $true)] + [System.String] $Id ) - PROCESS { + PROCESS { $params = @{} $customHeaders = New-EntraCustomHeaders -Command $MyInvocation.MyCommand - $policyTypes = "activityBasedTimeoutPolicies", "defaultAppManagementPolicy", "appManagementPolicies", "authenticationFlowsPolicy", "authenticationMethodsPolicy", "claimsMappingPolicies", "featureRolloutPolicies", "homeRealmDiscoveryPolicies", "permissionGrantPolicies", "tokenIssuancePolicies", "tokenLifetimePolicies" - + $policyTypes = 'activityBasedTimeoutPolicies', 'defaultAppManagementPolicy', 'appManagementPolicies', 'authenticationFlowsPolicy', 'authenticationMethodsPolicy', 'claimsMappingPolicies', 'featureRolloutPolicies', 'homeRealmDiscoveryPolicies', 'permissionGrantPolicies', 'tokenIssuancePolicies', 'tokenLifetimePolicies' + foreach ($policyType in $policyTypes) { - $uri = "https://graph.microsoft.com/v1.0/policies/" + $policyType + "/" + $id + $uri = 'https://graph.microsoft.com/v1.0/policies/' + $policyType + '/' + $id try { $response = Invoke-GraphRequest -Headers $customHeaders -Uri $uri -Method GET break + } catch { + Write-Error $_.Exception.Message } - catch {} } - $policy = ($response.'@odata.context') -match 'policies/([^/]+)/\$entity' - + # Unused variable + #$policy = ($response.'@odata.context') -match 'policies/([^/]+)/\$entity' + $policyType = $Matches[1] - Write-Debug("============================ Matches ============================") + Write-Debug('============================ Matches ============================') Write-Debug($Matches[1]) - if (($null -ne $PSBoundParameters["id"]) -and ($null -ne $policyType )) { - $URI = "https://graph.microsoft.com/v1.0/policies/" + $policyType + "/" + $id + if (($null -ne $PSBoundParameters['id']) -and ($null -ne $policyType )) { + $URI = 'https://graph.microsoft.com/v1.0/policies/' + $policyType + '/' + $id } - $Method = "DELETE" - Write-Debug("============================ TRANSFORMATIONS ============================") - $params.Keys | ForEach-Object {"$_ : $($params[$_])" } | Write-Debug + $Method = 'DELETE' + Write-Debug('============================ TRANSFORMATIONS ============================') + $params.Keys | ForEach-Object { "$_ : $($params[$_])" } | Write-Debug Write-Debug("=========================================================================`n") $response = Invoke-GraphRequest -Headers $customHeaders -Uri $uri -Method $Method $response - } -} \ No newline at end of file + } +} diff --git a/module_legacy/Entra/AdditionalFunctions/Set-EntraPolicy.ps1 b/module_legacy/Entra/AdditionalFunctions/Set-EntraPolicy.ps1 index aa4498b83..6efba4dda 100644 --- a/module_legacy/Entra/AdditionalFunctions/Set-EntraPolicy.ps1 +++ b/module_legacy/Entra/AdditionalFunctions/Set-EntraPolicy.ps1 @@ -4,98 +4,99 @@ function Set-EntraPolicy { [CmdletBinding(DefaultParameterSetName = 'InvokeByDynamicParameters')] param ( - [Parameter(ParameterSetName = "InvokeByDynamicParameters")] - [System.String] $AlternativeIdentifier, - [Parameter(Mandatory = $true, ValueFromPipeline = $true, ValueFromPipelineByPropertyName = $true)] - [System.String] $Id, - [Parameter(ParameterSetName = "InvokeByDynamicParameters")] - [System.Collections.Generic.List`1[System.String]] $Definition, - [Parameter(ParameterSetName = "InvokeByDynamicParameters")] - [System.String] $DisplayName, - [Parameter(ParameterSetName = "InvokeByDynamicParameters")] - [System.String] $Type, - [Parameter(ParameterSetName = "InvokeByDynamicParameters")] - [System.Collections.Generic.List`1[Microsoft.Open.MSGraph.Model.KeyCredential]] $KeyCredentials, - [Parameter(ParameterSetName = "InvokeByDynamicParameters")] - [System.Nullable`1[System.Boolean]] $IsOrganizationDefault + [Parameter(ParameterSetName = 'InvokeByDynamicParameters')] + [System.String] $AlternativeIdentifier, + [Parameter(Mandatory = $true, ValueFromPipeline = $true, ValueFromPipelineByPropertyName = $true)] + [System.String] $Id, + [Parameter(ParameterSetName = 'InvokeByDynamicParameters')] + [System.Collections.Generic.List`1[System.String]] $Definition, + [Parameter(ParameterSetName = 'InvokeByDynamicParameters')] + [System.String] $DisplayName, + [Parameter(ParameterSetName = 'InvokeByDynamicParameters')] + [System.String] $Type, + [Parameter(ParameterSetName = 'InvokeByDynamicParameters')] + [System.Collections.Generic.List`1[Microsoft.Open.MSGraph.Model.KeyCredential]] $KeyCredentials, + [Parameter(ParameterSetName = 'InvokeByDynamicParameters')] + [System.Nullable`1[System.Boolean]] $IsOrganizationDefault ) - PROCESS { + PROCESS { $params = @{} $customHeaders = New-EntraCustomHeaders -Command $MyInvocation.MyCommand - + $policyTypeMap = @{ - "ActivityBasedTimeoutPolicy" = "activityBasedTimeoutPolicies" - "ApplicationManagementPolicy" = "appManagementPolicies" - "DefaultAppManagementPolicy" = "defaultAppManagementPolicy" - "AuthenticationFlowsPolicy" = "authenticationFlowsPolicy" - "AuthenticationMethodsPolicy" = "authenticationMethodsPolicy" - "ClaimsMappingPolicy" = "claimsMappingPolicies" - "FeatureRolloutPolicy" = "featureRolloutPolicies" - "HomeRealmDiscoveryPolicy" = "homeRealmDiscoveryPolicies" - "PermissionGrantPolicy" = "permissionGrantPolicies" - "TokenIssuancePolicy" = "tokenIssuancePolicies" - "TokenLifetimePolicy" = "tokenLifetimePolicies" + 'ActivityBasedTimeoutPolicy' = 'activityBasedTimeoutPolicies' + 'ApplicationManagementPolicy' = 'appManagementPolicies' + 'DefaultAppManagementPolicy' = 'defaultAppManagementPolicy' + 'AuthenticationFlowsPolicy' = 'authenticationFlowsPolicy' + 'AuthenticationMethodsPolicy' = 'authenticationMethodsPolicy' + 'ClaimsMappingPolicy' = 'claimsMappingPolicies' + 'FeatureRolloutPolicy' = 'featureRolloutPolicies' + 'HomeRealmDiscoveryPolicy' = 'homeRealmDiscoveryPolicies' + 'PermissionGrantPolicy' = 'permissionGrantPolicies' + 'TokenIssuancePolicy' = 'tokenIssuancePolicies' + 'TokenLifetimePolicy' = 'tokenLifetimePolicies' } $policyTypes = $policyTypeMap.Values - if ($null -ne $PSBoundParameters["type"]) { - $type = if ($policyTypeMap.ContainsKey($type)) { $policyTypeMap[$type] } else { - Write-Error "Set-EntraBetADPolicy : Error occurred while executing SetPolicy + if ($null -ne $PSBoundParameters['type']) { + $type = if ($policyTypeMap.ContainsKey($type)) { $policyTypeMap[$type] } else { + Write-Error "Set-EntraBetADPolicy : Error occurred while executing SetPolicy Code: Request_BadRequest Message: Invalid value specified for property 'type' of resource 'Policy'." - return; + return } } else { $type = $null - } - - if(!$type) { + } + + if (!$type) { foreach ($pType in $policyTypes) { - $uri = "https://graph.microsoft.com/v1.0/policies/" + $pType + "/" + $id + $uri = 'https://graph.microsoft.com/v1.0/policies/' + $pType + '/' + $id try { $response = Invoke-GraphRequest -Uri $uri -Method GET break + } catch { + Write-Error $_.Exception.Message } - catch {} } - $policy = ($response.'@odata.context') -match 'policies/([^/]+)/\$entity' + # Unused variable + #$policy = ($response.'@odata.context') -match 'policies/([^/]+)/\$entity' $type = $Matches[1] } - - if($policyTypes -notcontains $type) { - Write-Error "Set-AzureADPolicy : Error occurred while executing SetPolicy + + if ($policyTypes -notcontains $type) { + Write-Error "Set-AzureADPolicy : Error occurred while executing SetPolicy Code: Request_BadRequest Message: Invalid value specified for property 'type' of resource 'Policy'." - } - else { - if ($null -ne $PSBoundParameters["Definition"]) { - $params["Definition"] = $PSBoundParameters["Definition"] + } else { + if ($null -ne $PSBoundParameters['Definition']) { + $params['Definition'] = $PSBoundParameters['Definition'] } - if ($null -ne $PSBoundParameters["DisplayName"]) { - $params["DisplayName"] = $PSBoundParameters["DisplayName"] + if ($null -ne $PSBoundParameters['DisplayName']) { + $params['DisplayName'] = $PSBoundParameters['DisplayName'] } - if ($null -ne $PSBoundParameters["Definition"]) { - $params["Definition"] = $PSBoundParameters["Definition"] + if ($null -ne $PSBoundParameters['Definition']) { + $params['Definition'] = $PSBoundParameters['Definition'] } - if ($null -ne $PSBoundParameters["IsOrganizationDefault"]) { - $params["IsOrganizationDefault"] = $PSBoundParameters["IsOrganizationDefault"] + if ($null -ne $PSBoundParameters['IsOrganizationDefault']) { + $params['IsOrganizationDefault'] = $PSBoundParameters['IsOrganizationDefault'] } - if (($null -ne $PSBoundParameters["id"]) -and ($null -ne $type )) { - $URI = "https://graph.microsoft.com/v1.0/policies/" + $type + "/" + $id + if (($null -ne $PSBoundParameters['id']) -and ($null -ne $type )) { + $URI = 'https://graph.microsoft.com/v1.0/policies/' + $type + '/' + $id } - - $Method = "PATCH" - - Write-Debug("============================ TRANSFORMATIONS ============================") - $params.Keys | ForEach-Object {"$_ : $($params[$_])" } | Write-Debug - Write-Debug("=========================================================================`n") - - $body = $params | ConvertTo-Json - Invoke-GraphRequest -Headers $customHeaders -Uri $uri -Body $body -Method $Method - + + $Method = 'PATCH' + + Write-Debug('============================ TRANSFORMATIONS ============================') + $params.Keys | ForEach-Object { "$_ : $($params[$_])" } | Write-Debug + Write-Debug("=========================================================================`n") + + $body = $params | ConvertTo-Json + Invoke-GraphRequest -Headers $customHeaders -Uri $uri -Body $body -Method $Method + } - - } -} \ No newline at end of file + + } +} diff --git a/module_legacy/EntraBeta/AdditionalFunctions/Get-EntraBetaApplicationPasswordCredential.ps1 b/module_legacy/EntraBeta/AdditionalFunctions/Get-EntraBetaApplicationPasswordCredential.ps1 index e475c8dca..6f8a6ce25 100644 --- a/module_legacy/EntraBeta/AdditionalFunctions/Get-EntraBetaApplicationPasswordCredential.ps1 +++ b/module_legacy/EntraBeta/AdditionalFunctions/Get-EntraBetaApplicationPasswordCredential.ps1 @@ -5,35 +5,35 @@ function Get-EntraBetaApplicationPasswordCredential { [CmdletBinding(DefaultParameterSetName = '')] param ( - [Parameter(Mandatory = $true, ValueFromPipeline = $true, ValueFromPipelineByPropertyName = $true)] - [Alias("ObjectId")] - [System.String] $ApplicationId, - [Parameter(Mandatory = $false, ValueFromPipeline = $false, ValueFromPipelineByPropertyName = $true)] - [System.String[]] $Property + [Parameter(Mandatory = $true, ValueFromPipeline = $true, ValueFromPipelineByPropertyName = $true)] + [Alias('ObjectId')] + [System.String] $ApplicationId, + [Parameter(Mandatory = $false, ValueFromPipeline = $false, ValueFromPipelineByPropertyName = $true)] + [System.String[]] $Property ) PROCESS { $customHeaders = New-EntraBetaCustomHeaders -Command $MyInvocation.MyCommand $params = @{} $baseUri = "https://graph.microsoft.com/beta/applications/$ApplicationId/passwordCredentials" - $params["Method"] = "GET" - $params["Uri"] = "$baseUri" + $params['Method'] = 'GET' + $params['Uri'] = "$baseUri" $response = Invoke-GraphRequest @params -Headers $customHeaders | ConvertTo-Json | ConvertFrom-Json try { $response = $response.value + } catch { + Write-Error $_.Exception.Message } - catch {} $response | ForEach-Object { - if($null -ne $_) { + if ($null -ne $_) { $CustomKeyIdentifier = [System.Text.Encoding]::UTF8.GetBytes([System.Text.Encoding]::UTF8.GetString([System.Convert]::FromBase64String($_.CustomKeyIdentifier))) Add-Member -InputObject $_ -MemberType NoteProperty -Name CustomKeyIdentifier -Value $CustomKeyIdentifier -Force Add-Member -InputObject $_ -MemberType AliasProperty -Name EndDate -Value endDateTime Add-Member -InputObject $_ -MemberType AliasProperty -Name StartDate -Value startDateTime } } - if($response) - { + if ($response) { $userList = @() foreach ($data in $response) { $userType = New-Object Microsoft.Graph.Beta.PowerShell.Models.MicrosoftGraphPasswordCredential @@ -43,14 +43,12 @@ function Get-EntraBetaApplicationPasswordCredential { $userType | Add-Member -MemberType NoteProperty -Name $propertyName -Value $propertyValue -Force } $userList += $userType - } - if($null -ne $PSBoundParameters["Property"]) - { - $userList | Select-Object $PSBoundParameters["Property"] } - else { + if ($null -ne $PSBoundParameters['Property']) { + $userList | Select-Object $PSBoundParameters['Property'] + } else { $userList - } + } } } -} \ No newline at end of file +} diff --git a/module_legacy/EntraBeta/AdditionalFunctions/Get-EntraBetaDirectoryObjectOnPremisesProvisioningError.ps1 b/module_legacy/EntraBeta/AdditionalFunctions/Get-EntraBetaDirectoryObjectOnPremisesProvisioningError.ps1 index 9866fe1d0..afdd65857 100644 --- a/module_legacy/EntraBeta/AdditionalFunctions/Get-EntraBetaDirectoryObjectOnPremisesProvisioningError.ps1 +++ b/module_legacy/EntraBeta/AdditionalFunctions/Get-EntraBetaDirectoryObjectOnPremisesProvisioningError.ps1 @@ -5,36 +5,35 @@ function Get-EntraBetaDirectoryObjectOnPremisesProvisioningError { [CmdletBinding(DefaultParameterSetName = 'GetById')] param ( - [Parameter(ParameterSetName = "GetById")][ValidateNotNullOrEmpty()][ValidateScript({if ($_ -is [System.Guid]) { $true } else {throw "TenantId must be of type [System.Guid]."}})][System.Guid] $TenantId + [Parameter(ParameterSetName = 'GetById')][ValidateNotNullOrEmpty()][ValidateScript({ if ($_ -is [System.Guid]) { $true } else { throw 'TenantId must be of type [System.Guid].' } })][System.Guid] $TenantId ) PROCESS { $params = @{} $customHeaders = New-EntraBetaCustomHeaders -Command $MyInvocation.MyCommand - if ($null -ne $PSBoundParameters["TenantId"]) { - $params["TenantId"] = $PSBoundParameters["TenantId"] + if ($null -ne $PSBoundParameters['TenantId']) { + $params['TenantId'] = $PSBoundParameters['TenantId'] } - Write-Debug("============================ TRANSFORMATIONS ============================") + Write-Debug('============================ TRANSFORMATIONS ============================') $params.Keys | ForEach-Object { "$_ : $($params[$_])" } | Write-Debug Write-Debug("=========================================================================`n") - $Object = @("users", "groups", "contacts") + $Object = @('users', 'groups', 'contacts') $response = @() try { foreach ($obj in $object) { - $obj = ($obj | Out-String).trimend() + $obj = ($obj | Out-String).TrimEnd() $uri = 'https://graph.microsoft.com/beta/' + $obj + '?$select=onPremisesProvisioningErrors' $response += ((Invoke-GraphRequest -Headers $customHeaders -Uri $uri -Method GET).value).onPremisesProvisioningErrors } + } catch { + Write-Error $_.Exception.Message } - catch {} if ([string]::IsNullOrWhiteSpace($response)) { - write-host "False" - } - else { + Write-Host 'False' + } else { $response } } } Set-Alias -Name Get-EntraBetaHasObjectsWithDirSyncProvisioningError -Value Get-EntraBetaDirectoryObjectOnPremisesProvisioningError -Scope Global -Force - diff --git a/module_legacy/docfx.json b/module_legacy/docfx.json index 5c7747e82..ff5bf913f 100644 --- a/module_legacy/docfx.json +++ b/module_legacy/docfx.json @@ -1,24 +1,108 @@ { "build": { "content": [ - { "dest": "entra-preview", "files": [ "breadcrumb/toc.yml" ]}, - - { "dest": "entra-preview", "files": [ "**/*.md", "**/*.yml" ], "src": "docs/entra-powershell-v1.0", "version": "entra-powershell-preview" }, - { "dest": "module", "exclude": [ "toc.yml" ], "files": [ "**/*.yml" ], "src": "entra-powershell-preview", "version": "entra-powershell-preview" }, - { "dest": "module", "files": [ "**/About/*.md" ], "src": "entra-powershell-preview", "version": "entra-powershell-preview" }, - { "dest": "module/entra-powershell-preview", "files": [ "toc.yml" ], "src": "entra-powershell-preview", "version": "entra-powershell-preview" }, - - { "dest": "entra-preview", "files": [ "**/*.md", "**/*.yml" ], "src": "docs/entra-powershell-beta", "version": "entra-powershell-beta-preview" }, - { "dest": "module", "exclude": [ "toc.yml" ], "files": [ "**/*.yml" ], "src": "entra-powershell-beta-preview", "version": "entra-powershell-beta-preview" }, - { "dest": "module", "files": [ "**/About/*.md" ], "src": "entra-powershell-beta-preview", "version": "entra-powershell-beta-preview" }, - { "dest": "module/entra-powershell-beta-preview", "files": [ "toc.yml" ], "src": "entra-powershell-beta-preview", "version": "entra-powershell-beta-preview" }, - - { "dest": "entra-preview", "files": [ "**/*.md", "**/*.yml" ], "src": "virtual-folder" }, - { "dest": "module", "files": [ "**/*.md", "**/*.yml" ], "src": "virtual-folder-module" } + { + "dest": "entra-preview", + "files": [ + "breadcrumb/toc.yml" + ] + }, + { + "dest": "entra-preview", + "files": [ + "**/*.md", + "**/*.yml" + ], + "src": "docs/entra-powershell-v1.0", + "version": "entra-powershell-preview" + }, + { + "dest": "module", + "exclude": [ + "toc.yml" + ], + "files": [ + "**/*.yml" + ], + "src": "entra-powershell-preview", + "version": "entra-powershell-preview" + }, + { + "dest": "module", + "files": [ + "**/About/*.md" + ], + "src": "entra-powershell-preview", + "version": "entra-powershell-preview" + }, + { + "dest": "module/entra-powershell-preview", + "files": [ + "toc.yml" + ], + "src": "entra-powershell-preview", + "version": "entra-powershell-preview" + }, + { + "dest": "entra-preview", + "files": [ + "**/*.md", + "**/*.yml" + ], + "src": "docs/entra-powershell-beta", + "version": "entra-powershell-beta-preview" + }, + { + "dest": "module", + "exclude": [ + "toc.yml" + ], + "files": [ + "**/*.yml" + ], + "src": "entra-powershell-beta-preview", + "version": "entra-powershell-beta-preview" + }, + { + "dest": "module", + "files": [ + "**/About/*.md" + ], + "src": "entra-powershell-beta-preview", + "version": "entra-powershell-beta-preview" + }, + { + "dest": "module/entra-powershell-beta-preview", + "files": [ + "toc.yml" + ], + "src": "entra-powershell-beta-preview", + "version": "entra-powershell-beta-preview" + }, + { + "dest": "entra-preview", + "files": [ + "**/*.md", + "**/*.yml" + ], + "src": "virtual-folder" + }, + { + "dest": "module", + "files": [ + "**/*.md", + "**/*.yml" + ], + "src": "virtual-folder-module" + } ], "versions": { - "entra-powershell-preview": { "dest": "entra-powershell-preview" }, - "entra-powershell-beta-preview": { "dest": "entra-powershell-beta-preview" }, + "entra-powershell-preview": { + "dest": "entra-powershell-preview" + }, + "entra-powershell-beta-preview": { + "dest": "entra-powershell-beta-preview" + } }, "overwrite": [], "externalReference": [], @@ -30,7 +114,7 @@ "ms.prod": "powershell", "ms.topic": "reference", "ms.author": "stevemutungi", - "author": "SteveMutungi254", + "author": "SteveMutungi254" }, "template": [], "markdownEngineName": "markdig", diff --git a/src/CompatibilityAdapterBuilder.ps1 b/src/CompatibilityAdapterBuilder.ps1 index 19b940bcb..5b9e0d97b 100644 --- a/src/CompatibilityAdapterBuilder.ps1 +++ b/src/CompatibilityAdapterBuilder.ps1 @@ -5,26 +5,26 @@ Set-StrictMode -Version 5 class CompatibilityAdapterBuilder { [string] $SourceModuleName - [string[]] $SourceModulePrefixs + [string[]] $SourceModulePrefixes [string] $NewPrefix [string[]] $DestinationModuleName - [string[]] $DestinationPrefixs + [string[]] $DestinationPrefixes [string] $ModuleName hidden [string[]] $MissingCommandsToMap = @() hidden [string[]] $TypesToCreate = @() - hidden [string] $TypePrefix = "" + hidden [string] $TypePrefix = '' hidden [hashtable] $CmdCustomizations = @{} hidden [hashtable] $GenericParametersTransformations = @{} hidden [hashtable] $GenericOutputTransformations = @{} hidden [hashtable] $TypeCustomizations = @{} - hidden [string] $OutputFolder = (join-path $PSScriptRoot '../bin') + hidden [string] $OutputFolder = (Join-Path $PSScriptRoot '../bin') hidden [string] $HelpFolder = $null hidden [MappedCmdCollection] $ModuleMap = $null hidden [bool] $GenerateCommandsToMapData hidden [hashtable] $HelperCmdletsToExport = @{} hidden [string] $BasePath = $null hidden [string] $LoadMessage - hidden [string[]] $cmdtoSkipNameconverssion = @( + hidden [string[]] $cmdToSkipNameConversion = @( 'Select-EntraGroupIdsGroupIsMemberOf', 'Get-EntraUserAppRoleAssignment', 'Get-EntraPermissionGrantConditionSet', @@ -64,132 +64,131 @@ class CompatibilityAdapterBuilder { 'New-EntraNamedLocationPolicy', 'New-EntraServicePrincipalAppRoleAssignment', 'Restore-EntraDeletedDirectoryObject', - 'Restore-EntraBetaDeletedDirectoryObject', - 'New-EntraBetaServicePrincipalAppRoleAssignment', - 'New-EntraBetaNamedLocationPolicy', - 'Get-EntraBetaPermissionGrantConditionSet', - 'Get-EntraBetaPermissionGrantConditionSet', - 'Get-EntraBetaApplicationKeyCredential', - 'Get-EntraBetaPrivilegedRoleDefinition', - 'Get-EntraBetaFeatureRolloutPolicy', - 'Set-EntraBetaPermissionGrantPolicy', - 'Remove-EntraBetaApplicationPassword', - 'Get-EntraBetaServicePrincipalPolicy', - 'Get-EntraBetaPrivilegedRoleAssignmentRequest', - 'New-EntraBetaApplicationPassword', - 'Set-EntraBetaPasswordSingleSignOnCredential', - 'Get-EntraBetaObjectSetting', - 'Add-EntraBetaApplicationPolicy', - 'Add-EntraBetaFeatureRolloutPolicyDirectoryObject', - 'Revoke-EntraBetaUserAllRefreshToken', - 'Get-EntraBetaPrivilegedRole', - 'Get-EntraBetaApplicationTemplate', - 'Select-EntraBetaGroupIdsContactIsMemberOf', - 'Set-EntraBetaCustomSecurityAttributeDefinitionAllowedValue', - 'Set-EntraBetaUserLicense', - 'Set-EntraBetaTrustFrameworkPolicy', - 'Remove-EntraBetaUserAppRoleAssignment', - 'Get-EntraBetaApplicationPolicy', - 'Get-EntraBetaPermissionGrantPolicy', - 'Select-EntraBetaGroupIdsGroupIsMemberOf', - 'New-EntraBetaUserAppRoleAssignment', - 'Get-EntraBetaTrustFrameworkPolicy', - 'Remove-EntraBetaObjectSetting', - 'Add-EntraBetacustomSecurityAttributeDefinitionAllowedValue', - 'Get-EntraBetaUserOAuth2PermissionGrant', - 'New-EntraBetaApplicationKey', - 'Get-EntraBetaPolicy', - 'Get-EntraBetaDirectorySetting', - 'New-EntraBetaServiceAppRoleAssignment', - 'Get-EntraBetaObjectByObjectId', - 'Remove-EntraBetaPasswordSingleSignOnCredential', - 'Set-EntraBetaPermissionGrantConditionSet', - 'Set-EntraBetaConditionalAccessPolicy', - 'Get-EntraBetaPolicyAppliedObject', - 'Remove-EntraBetaDeletedApplication', - 'Get-EntraBetaCustomSecurityAttributeDefinitionAllowedValue', - 'Get-EntraBetaUserAppRoleAssignment', - 'Get-EntraBetaDirectorySettingTemplate', - 'Remove-EntraBetaServicePrincipalPolicy', - 'Get-EntraBetaPermissionGrantConditionSet', - 'Set-EntraBetaObjectSetting', - 'Remove-EntraBetaFeatureRolloutPolicyDirectoryObject', - 'Get-EntraBetaAuthorizationPolicy', - 'Remove-EntraBetaPermissionGrantPolicy', - 'Set-EntraBetaDirectorySetting', - 'Set-EntraBetaAuthorizationPolicy', - 'Remove-EntraBetaDirectorySetting', - 'Remove-EntraBetaApplicationPolicy', - 'New-EntraBetaConditionalAccessPolicy', - 'Set-EntraBetaPrivilegedRoleAssignmentRequest', - 'Remove-EntraBetaTrustFrameworkPolicy', - 'New-EntraBetaPasswordSingleSignOnCredential', - 'Remove-EntraBetaPolicy', - 'Set-EntraBetaPolicy', - 'Set-EntraBetaCustomSecurityAttributeDefinition', - 'Get-EntraBetaPrivilegedResource', - 'Set-EntraBetaUserPassword', - 'New-EntraBetaApplicationFromApplicationTemplate', - 'Set-EntraBetaPrivilegedRoleSetting', - 'Remove-EntraBetaApplicationKey', - 'Get-EntraBetaPrivilegedRoleSetting', - 'Remove-EntraBetaOAuth2PermissionGrant', - 'Select-EntraBetaGroupIdsServicePrincipalIsMemberOf', - 'Get-EntraBetaServicePrincipalDelegatedPermissionClassification', - 'New-EntraBetaPrivilegedRoleAssignment', - 'Get-EntraBetaPasswordSingleSignOnCredential', - 'Set-EntraBetaFeatureRolloutPolicy', - 'New-EntraBetaPermissionGrantPolicy', - 'Remove-EntraBetaFeatureRolloutPolicy', - 'Get-EntraBetaCustomSecurityAttributeDefinition', - 'Remove-EntraBetaServicePrincipalDelegatedPermissionClassification', - 'Select-EntraBetaGroupIdsUserIsMemberOf', - 'Set-EntraBetaNamedLocationPolicy', - 'New-EntraBetaNamedLocationPolicy', - 'Restore-EntraBetaDeletedApplication', - 'Remove-EntraBetaPermissionGrantConditionSet' - + 'Restore-EntraBetaDeletedDirectoryObject', + 'New-EntraBetaServicePrincipalAppRoleAssignment', + 'New-EntraBetaNamedLocationPolicy', + 'Get-EntraBetaPermissionGrantConditionSet', + 'Get-EntraBetaPermissionGrantConditionSet', + 'Get-EntraBetaApplicationKeyCredential', + 'Get-EntraBetaPrivilegedRoleDefinition', + 'Get-EntraBetaFeatureRolloutPolicy', + 'Set-EntraBetaPermissionGrantPolicy', + 'Remove-EntraBetaApplicationPassword', + 'Get-EntraBetaServicePrincipalPolicy', + 'Get-EntraBetaPrivilegedRoleAssignmentRequest', + 'New-EntraBetaApplicationPassword', + 'Set-EntraBetaPasswordSingleSignOnCredential', + 'Get-EntraBetaObjectSetting', + 'Add-EntraBetaApplicationPolicy', + 'Add-EntraBetaFeatureRolloutPolicyDirectoryObject', + 'Revoke-EntraBetaUserAllRefreshToken', + 'Get-EntraBetaPrivilegedRole', + 'Get-EntraBetaApplicationTemplate', + 'Select-EntraBetaGroupIdsContactIsMemberOf', + 'Set-EntraBetaCustomSecurityAttributeDefinitionAllowedValue', + 'Set-EntraBetaUserLicense', + 'Set-EntraBetaTrustFrameworkPolicy', + 'Remove-EntraBetaUserAppRoleAssignment', + 'Get-EntraBetaApplicationPolicy', + 'Get-EntraBetaPermissionGrantPolicy', + 'Select-EntraBetaGroupIdsGroupIsMemberOf', + 'New-EntraBetaUserAppRoleAssignment', + 'Get-EntraBetaTrustFrameworkPolicy', + 'Remove-EntraBetaObjectSetting', + 'Add-EntraBetaCustomSecurityAttributeDefinitionAllowedValue', + 'Get-EntraBetaUserOAuth2PermissionGrant', + 'New-EntraBetaApplicationKey', + 'Get-EntraBetaPolicy', + 'Get-EntraBetaDirectorySetting', + 'New-EntraBetaServiceAppRoleAssignment', + 'Get-EntraBetaObjectByObjectId', + 'Remove-EntraBetaPasswordSingleSignOnCredential', + 'Set-EntraBetaPermissionGrantConditionSet', + 'Set-EntraBetaConditionalAccessPolicy', + 'Get-EntraBetaPolicyAppliedObject', + 'Remove-EntraBetaDeletedApplication', + 'Get-EntraBetaCustomSecurityAttributeDefinitionAllowedValue', + 'Get-EntraBetaUserAppRoleAssignment', + 'Get-EntraBetaDirectorySettingTemplate', + 'Remove-EntraBetaServicePrincipalPolicy', + 'Get-EntraBetaPermissionGrantConditionSet', + 'Set-EntraBetaObjectSetting', + 'Remove-EntraBetaFeatureRolloutPolicyDirectoryObject', + 'Get-EntraBetaAuthorizationPolicy', + 'Remove-EntraBetaPermissionGrantPolicy', + 'Set-EntraBetaDirectorySetting', + 'Set-EntraBetaAuthorizationPolicy', + 'Remove-EntraBetaDirectorySetting', + 'Remove-EntraBetaApplicationPolicy', + 'New-EntraBetaConditionalAccessPolicy', + 'Set-EntraBetaPrivilegedRoleAssignmentRequest', + 'Remove-EntraBetaTrustFrameworkPolicy', + 'New-EntraBetaPasswordSingleSignOnCredential', + 'Remove-EntraBetaPolicy', + 'Set-EntraBetaPolicy', + 'Set-EntraBetaCustomSecurityAttributeDefinition', + 'Get-EntraBetaPrivilegedResource', + 'Set-EntraBetaUserPassword', + 'New-EntraBetaApplicationFromApplicationTemplate', + 'Set-EntraBetaPrivilegedRoleSetting', + 'Remove-EntraBetaApplicationKey', + 'Get-EntraBetaPrivilegedRoleSetting', + 'Remove-EntraBetaOAuth2PermissionGrant', + 'Select-EntraBetaGroupIdsServicePrincipalIsMemberOf', + 'Get-EntraBetaServicePrincipalDelegatedPermissionClassification', + 'New-EntraBetaPrivilegedRoleAssignment', + 'Get-EntraBetaPasswordSingleSignOnCredential', + 'Set-EntraBetaFeatureRolloutPolicy', + 'New-EntraBetaPermissionGrantPolicy', + 'Remove-EntraBetaFeatureRolloutPolicy', + 'Get-EntraBetaCustomSecurityAttributeDefinition', + 'Remove-EntraBetaServicePrincipalDelegatedPermissionClassification', + 'Select-EntraBetaGroupIdsUserIsMemberOf', + 'Set-EntraBetaNamedLocationPolicy', + 'New-EntraBetaNamedLocationPolicy', + 'Restore-EntraBetaDeletedApplication', + 'Remove-EntraBetaPermissionGrantConditionSet' + ) # Constructor that changes the output folder, load all the Required Modules and creates the output folder. - CompatibilityAdapterBuilder() { - $this.BasePath = (join-path $PSScriptRoot '../module_legacy/Entra/') - $this.HelpFolder = (join-path $this.BasePath './help') - $this.Configure((join-path $this.BasePath "/config/ModuleSettings.json")) + CompatibilityAdapterBuilder() { + $this.BasePath = (Join-Path $PSScriptRoot '../module_legacy/Entra/') + $this.HelpFolder = (Join-Path $this.BasePath './help') + $this.Configure((Join-Path $this.BasePath '/config/ModuleSettings.json')) } - CompatibilityAdapterBuilder([string] $Module){ - $this.BasePath = (join-path $PSScriptRoot '../module_legacy/') - $this.BasePath = (join-path $this.BasePath $Module) - $this.HelpFolder = (join-path $this.BasePath './help') - $this.Configure((join-path $this.BasePath "/config/ModuleSettings.json")) + CompatibilityAdapterBuilder([string] $Module) { + $this.BasePath = (Join-Path $PSScriptRoot '../module_legacy/') + $this.BasePath = (Join-Path $this.BasePath $Module) + $this.HelpFolder = (Join-Path $this.BasePath './help') + $this.Configure((Join-Path $this.BasePath '/config/ModuleSettings.json')) } - CompatibilityAdapterBuilder([bool] $notRunningUT = $false){ - if($notRunningUT) - { - $this.BasePath = (join-path $PSScriptRoot '../module_legacy/Entra/') - $this.HelpFolder = (join-path $this.BasePath './help') - $this.Configure((join-path $this.BasePath "/config/ModuleSettings.json")) - } + CompatibilityAdapterBuilder([bool] $notRunningUT = $false) { + if ($notRunningUT) { + $this.BasePath = (Join-Path $PSScriptRoot '../module_legacy/Entra/') + $this.HelpFolder = (Join-Path $this.BasePath './help') + $this.Configure((Join-Path $this.BasePath '/config/ModuleSettings.json')) + } } - hidden Configure([string] $ModuleSettingsPath){ + hidden Configure([string] $ModuleSettingsPath) { $settingPath = $ModuleSettingsPath $content = Get-Content -Path $settingPath | ConvertFrom-Json $this.SourceModuleName = $content.sourceModule - $this.SourceModulePrefixs = $content.sourceModulePrefix + $this.SourceModulePrefixes = $content.sourceModulePrefix $this.NewPrefix = $content.newPrefix $this.DestinationModuleName = $content.destinationModuleName - $this.DestinationPrefixs = $content.destinationPrefix + $this.DestinationPrefixes = $content.destinationPrefix $this.ModuleName = $content.moduleName $this.TypePrefix = $content.typePrefix Import-Module $this.SourceModuleName -Force | Out-Null - foreach ($moduleName in $this.DestinationModuleName){ + foreach ($moduleName in $this.DestinationModuleName) { Import-Module $moduleName -RequiredVersion $content.destinationModuleVersion -Force | Out-Null } - if(!(Test-Path $this.OutputFolder)){ + if (!(Test-Path $this.OutputFolder)) { New-Item -ItemType Directory -Path $this.OutputFolder | Out-Null } @@ -198,56 +197,55 @@ class CompatibilityAdapterBuilder { # Generates the module then generates all the files required to create the module. BuildModule() { - $this.WriteModuleFile() - $this.WriteModuleManifest() + $this.WriteModuleFile() + $this.WriteModuleManifest() } - + AddTypes($types) { $this.TypeCustomizations = $types - foreach($type in $types.Keys){ + foreach ($type in $types.Keys) { $this.TypesToCreate += $type } } # Add customization based on the the CommandMap object. AddCustomization([hashtable[]] $Commands) { - foreach($cmd in $Commands) { + foreach ($cmd in $Commands) { $parameters = $null $outputs = $null - if($null -ne $cmd.TargetName){ - if($cmd.Parameters){ + if ($null -ne $cmd.TargetName) { + if ($cmd.Parameters) { $parameters = @{} - foreach($param in $cmd.Parameters){ + foreach ($param in $cmd.Parameters) { $parameters.Add($param.SourceName, [DataMap]::New($param.SourceName, $param.TargetName, $param.ConversionType, [Scriptblock]::Create($param.SpecialMapping))) } } - - if($cmd.Outputs){ + + if ($cmd.Outputs) { $outputs = @{} - foreach($param in $cmd.Outputs){ + foreach ($param in $cmd.Outputs) { $outputs.Add($param.SourceName, [DataMap]::New($param.SourceName, $param.TargetName, $param.ConversionType, [Scriptblock]::Create($param.SpecialMapping))) } } - $customCommand = [CommandMap]::New($cmd.SourceName,$cmd.TargetName, $parameters, $outputs) + $customCommand = [CommandMap]::New($cmd.SourceName, $cmd.TargetName, $parameters, $outputs) $this.CmdCustomizations.Add($cmd.SourceName, $customCommand) - } - else { - if($cmd.Parameters){ + } else { + if ($cmd.Parameters) { $parameters = @{} - foreach($param in $cmd.Parameters){ + foreach ($param in $cmd.Parameters) { $this.GenericParametersTransformations.Add($param.SourceName, [DataMap]::New($param.SourceName, $param.TargetName, $param.ConversionType, [Scriptblock]::Create($param.SpecialMapping))) } } - - if($cmd.Outputs){ + + if ($cmd.Outputs) { $outputs = @{} - foreach($param in $cmd.Outputs){ + foreach ($param in $cmd.Outputs) { $this.GenericOutputTransformations.Add($param.SourceName, [DataMap]::New($param.SourceName, $param.TargetName, $param.ConversionType, [Scriptblock]::Create($param.SpecialMapping))) } } - if($null -ne $cmd.SourceName) { + if ($null -ne $cmd.SourceName) { $scriptBlock = [Scriptblock]::Create($cmd.CustomScript) $customCommand = [CommandMap]::New($cmd.SourceName, $scriptBlock) $this.CmdCustomizations.Add($cmd.SourceName, $customCommand) @@ -256,16 +254,16 @@ class CompatibilityAdapterBuilder { } } - AddHelperCommand([string] $FileName){ + AddHelperCommand([string] $FileName) { $properties = Get-ItemProperty -Path $FileName - if($null -ne $properties){ - $name = $properties.PSChildName.Replace(".ps1","") + if ($null -ne $properties) { + $name = $properties.PSChildName.Replace('.ps1', '') $this.HelperCmdletsToExport.Add($name, $(Get-Content -Path $FileName) -join "`n") } } hidden GenerateHelpFiles() { - foreach($file in Get-ChildItem -Path $this.HelpFolder -Filter "*.xml") { + foreach ($file in Get-ChildItem -Path $this.HelpFolder -Filter '*.xml') { Copy-Item $file.FullName $this.OutputFolder -Force } #$helpPath = Join-Path $this.OutputFolder "$($this.ModuleName)-Help.xml" @@ -275,123 +273,121 @@ class CompatibilityAdapterBuilder { } hidden [string] GetHelpHeader() { - $helpHeader = @" + $helpHeader = @' -"@ +'@ return $helpHeader } hidden [string] GetHelpCommandsFromFiles($filePath) { - $helpCommands = "" - $replacePrefix = "-" + $this.NewPrefix - $oldPrefix = "-AzureAD" - foreach($file in Get-ChildItem -Path $this.HelpFolder -Filter "*.xml") { - (Get-Content $file.FullName | Select-Object -Skip 2 | Select-Object -SkipLast 1).Replace($oldPrefix,$replacePrefix) | Add-Content -Path $filePath + $helpCommands = '' + $replacePrefix = '-' + $this.NewPrefix + $oldPrefix = '-AzureAD' + foreach ($file in Get-ChildItem -Path $this.HelpFolder -Filter '*.xml') { + (Get-Content $file.FullName | Select-Object -Skip 2 | Select-Object -SkipLast 1).Replace($oldPrefix, $replacePrefix) | Add-Content -Path $filePath } return $helpCommands } hidden [string] GetHelpFooter() { - $helpHeader = @" + $helpHeader = @' -"@ +'@ return $helpHeader } - - hidden WriteModuleFile() { + + hidden WriteModuleFile() { $filePath = Join-Path $this.OutputFolder "$($this.ModuleName).psm1" #This call create the mapping used to create the final module. $data = $this.Map() $psm1FileContent = $this.GetFileHeader() - foreach($cmd in $data.Commands) { + foreach ($cmd in $data.Commands) { $psm1FileContent += $cmd.CommandBlock } $psm1FileContent += $this.GetUnsupportedCommand() - $psm1FileContent += $this.GetAlisesFunction() - foreach($function in $this.HelperCmdletsToExport.GetEnumerator()){ + $psm1FileContent += $this.GetAliasesFunction() + foreach ($function in $this.HelperCmdletsToExport.GetEnumerator()) { $psm1FileContent += $function.Value } - $psm1FileContent += $this.GetExportMemeber() + $psm1FileContent += $this.GetExportMember() $psm1FileContent += $this.SetMissingCommands() $psm1FileContent += $this.LoadMessage $psm1FileContent += $this.GetTypesDefinitions() $psm1FileContent | Out-File -FilePath $filePath } - hidden GetInnerTypes([string] $type){ - $object = New-Object -TypeName $type + hidden GetInnerTypes([string] $type) { + $object = New-Object -TypeName $type $object.GetType().GetProperties() | ForEach-Object { - if($_.PropertyType.Name -eq 'Nullable`1') { + if ($_.PropertyType.Name -eq 'Nullable`1') { $name = $_.PropertyType.GenericTypeArguments.FullName - if(!$_.PropertyType.GenericTypeArguments.IsEnum){ - if($name -like "$($this.TypePrefix)*") { - if(!$this.TypesToCreate.Contains($name)){ + if (!$_.PropertyType.GenericTypeArguments.IsEnum) { + if ($name -like "$($this.TypePrefix)*") { + if (!$this.TypesToCreate.Contains($name)) { $this.TypesToCreate += $name $this.GetInnerTypes($name) - } + } } } - } - elseif($_.PropertyType.Name -eq 'List`1') { + } elseif ($_.PropertyType.Name -eq 'List`1') { $name = $_.PropertyType.GenericTypeArguments.FullName - if(!$_.PropertyType.GenericTypeArguments.IsEnum){ - if($name -like "$($this.TypePrefix)*") { - if(!$this.TypesToCreate.Contains($name)){ + if (!$_.PropertyType.GenericTypeArguments.IsEnum) { + if ($name -like "$($this.TypePrefix)*") { + if (!$this.TypesToCreate.Contains($name)) { $this.TypesToCreate += $name $this.GetInnerTypes($name) - } + } } } - } - else { - if(!$_.PropertyType.IsEnum){ + } else { + if (!$_.PropertyType.IsEnum) { $name = $_.PropertyType.FullName - if($name -like "$($this.TypePrefix)*") { - if(!$this.TypesToCreate.Contains($name)){ + if ($name -like "$($this.TypePrefix)*") { + if (!$this.TypesToCreate.Contains($name)) { $this.TypesToCreate += $name $this.GetInnerTypes($name) } } } - } + } } } hidden [string] GetTypesDefinitions() { $types = $this.TypesToCreate | Sort-Object -Unique - - foreach($type in $types) { + + foreach ($type in $types) { $this.GetInnerTypes($type) } - $types = $this.TypesToCreate | Sort-Object -Unique + $types = $this.TypesToCreate | Sort-Object -Unique $namespace = $null $def = @" # ------------------------------------------------------------------------------ -# Type definitios required for commands inputs +# Type definitions required for commands inputs # ------------------------------------------------------------------------------ `$def = @" "@ Write-Host "Creating types definitions for $($types.Count) types." - foreach($type in $types) { - Write-Host "- Generating type for $type" - if($type.contains("+")){ - $type = $type.Substring(0,$type.IndexOf("+")) - Write-Host "- Real type is $type" - } - $object = New-Object -TypeName $type - $namespaceNew = $object.GetType().Namespace - $enumsDefined = @() + foreach ($type in $types) { + Write-Host "- Generating type for $type" + if ($type.contains('+')) { + $type = $type.Substring(0, $type.IndexOf('+')) + Write-Host "- Real type is $type" + } + $object = New-Object -TypeName $type + $namespaceNew = $object.GetType().Namespace + $enumsDefined = @() - if($namespace -ne $namespaceNew){ - if($null -ne $namespace){ - $def += @" + if ($namespace -ne $namespaceNew) { + if ($null -ne $namespace) { + $def += @" } namespace $namespaceNew @@ -400,117 +396,113 @@ namespace $namespaceNew using System.Linq; "@ - } - else { - $def += @" + } else { + $def += @" namespace $namespaceNew { using System.Linq; - -"@ + +"@ + } + $namespace = $object.GetType().Namespace } - $namespace = $object.GetType().Namespace - } - $name = $object.GetType().Name - if($object.GetType().IsEnum){ $name = $object.GetType().Name - if(!$enumsDefined.Contains($name)){ - $def += $this.GetEnumString($name, $object.GetType().FullName) - $enumsDefined += $name - continue - } - } - $def += @" + if ($object.GetType().IsEnum) { + $name = $object.GetType().Name + if (!$enumsDefined.Contains($name)) { + $def += $this.GetEnumString($name, $object.GetType().FullName) + $enumsDefined += $name + continue + } + } + $def += @" public class $name { "@ - if($this.TypeCustomizations.ContainsKey($object.GetType().FullName)){ - $extraFunctions = $this.TypeCustomizations[$object.GetType().FullName] - $def += @" + if ($this.TypeCustomizations.ContainsKey($object.GetType().FullName)) { + $extraFunctions = $this.TypeCustomizations[$object.GetType().FullName] + $def += @" $extraFunctions } "@ - } - else { - - $object.GetType().GetProperties() | ForEach-Object { - if($_.PropertyType.Name -eq 'Nullable`1') { - $name = $_.PropertyType.GenericTypeArguments.FullName - if($_.PropertyType.GenericTypeArguments.IsEnum){ - $name = $_.PropertyType.GenericTypeArguments.Name - if(!$enumsDefined.Contains($name)){ - $def += $this.GetEnumString($name, $_.PropertyType.GenericTypeArguments.FullName) - $enumsDefined += $name - } - } - $name = "System.Nullable<$($name)>" - } - elseif ($_.PropertyType.Name -eq 'List`1') { - $name = $_.PropertyType.GenericTypeArguments.FullName - if($_.PropertyType.GenericTypeArguments.IsEnum){ - $name = $_.PropertyType.GenericTypeArguments.Name - if(!$enumsDefined.Contains($name)){ - $def += $this.GetEnumString($name, $_.PropertyType.GenericTypeArguments.FullName) - $enumsDefined += $name + } else { + + $object.GetType().GetProperties() | ForEach-Object { + if ($_.PropertyType.Name -eq 'Nullable`1') { + $name = $_.PropertyType.GenericTypeArguments.FullName + if ($_.PropertyType.GenericTypeArguments.IsEnum) { + $name = $_.PropertyType.GenericTypeArguments.Name + if (!$enumsDefined.Contains($name)) { + $def += $this.GetEnumString($name, $_.PropertyType.GenericTypeArguments.FullName) + $enumsDefined += $name + } + } + $name = "System.Nullable<$($name)>" + } elseif ($_.PropertyType.Name -eq 'List`1') { + $name = $_.PropertyType.GenericTypeArguments.FullName + if ($_.PropertyType.GenericTypeArguments.IsEnum) { + $name = $_.PropertyType.GenericTypeArguments.Name + if (!$enumsDefined.Contains($name)) { + $def += $this.GetEnumString($name, $_.PropertyType.GenericTypeArguments.FullName) + $enumsDefined += $name + } + } + $name = "System.Collections.Generic.List<$($name)>" + } else { + $name = $_.PropertyType.FullName + if ($_.PropertyType.IsEnum) { + $name = $_.PropertyType.Name + if (!$enumsDefined.Contains($name)) { + $def += $this.GetEnumString($name, $_.PropertyType.FullName) + $enumsDefined += $name + } + } } + $def += " public $($name) $($_.Name);`n" } - $name = "System.Collections.Generic.List<$($name)>" - } - else { - $name = $_.PropertyType.FullName - if($_.PropertyType.IsEnum){ - $name = $_.PropertyType.Name - if(!$enumsDefined.Contains($name)){ - $def += $this.GetEnumString($name, $_.PropertyType.FullName) - $enumsDefined += $name - } - } - } - $def += " public $($name) $($_.Name);`n" - } - $constructor = "" + $constructor = '' - if(1 -eq $object.GetType().GetProperties().Count){ + if (1 -eq $object.GetType().GetProperties().Count) { - $constructor = @" + $constructor = @" public $($object.GetType().Name)() - { + { } - + public $($object.GetType().Name)($name value) { $($object.GetType().GetProperties()[0].Name) = value; } "@ - } + } - $def += @" + $def += @" $constructor } "@ + } } - } - $def += @" + $def += @' } -"@ +'@ $def += @" `"@ try{ Add-Type -TypeDefinition `$def } - catch{} + catch { Write-Error $_.Exception.Message } # ------------------------------------------------------------------------------ -# End of Type definitios required for commands inputs +# End of Type definitions required for commands inputs # ------------------------------------------------------------------------------ "@ @@ -522,140 +514,134 @@ public $($object.GetType().Name)() public enum $($enumName){ "@ - [enum]::getvalues([type]$enumType) | ForEach-Object { - $def += " $_ = $($_.value__),`n" - } - $def += @" + [enum]::GetValues([type]$enumType) | ForEach-Object { + $def += " $_ = $($_.value__),`n" + } + $def += @' } -"@ +'@ return $def } hidden WriteModuleManifest() { - $settingPath = join-path $this.BasePath "./config/ModuleMetadata.json" + $settingPath = Join-Path $this.BasePath './config/ModuleMetadata.json' $files = @("$($this.ModuleName).psd1", "$($this.ModuleName).psm1", "$($this.ModuleName)-Help.xml") $content = Get-Content -Path $settingPath | ConvertFrom-Json $PSData = @{ - Tags = $($content.tags) - LicenseUri = $($content.licenseUri) - ProjectUri = $($content.projectUri) - IconUri = $($content.iconUri) + Tags = $($content.tags) + LicenseUri = $($content.licenseUri) + ProjectUri = $($content.projectUri) + IconUri = $($content.iconUri) ReleaseNotes = $($content.releaseNotes) - Prerelease = $null + Prerelease = $null } - $manisfestPath = Join-Path $this.OutputFolder "$($this.ModuleName).psd1" - $functions = $this.ModuleMap.CommandsList + "Enable-EntraAzureADAlias" + "Get-EntraUnsupportedCommand" + $manifestPath = Join-Path $this.OutputFolder "$($this.ModuleName).psd1" + $functions = $this.ModuleMap.CommandsList + 'Enable-EntraAzureADAlias' + 'Get-EntraUnsupportedCommand' $requiredModules = @() - foreach($module in $content.requiredModules){ - $requiredModules += @{ModuleName = $module; RequiredVersion = $content.requiredModulesVersion} + foreach ($module in $content.requiredModules) { + $requiredModules += @{ModuleName = $module; RequiredVersion = $content.requiredModulesVersion } } $moduleSettings = @{ - Path = $manisfestPath - GUID = $($content.guid) - ModuleVersion = "$($content.version)" - FunctionsToExport = $functions - CmdletsToExport=@() - AliasesToExport=@() - Author = $($content.authors) - CompanyName = $($content.owners) - FileList = $files - RootModule = "$($this.ModuleName).psm1" - Description = 'Microsoft Graph Entra PowerShell.' - DotNetFrameworkVersion = $([System.Version]::Parse('4.7.2')) - PowerShellVersion = $([System.Version]::Parse('5.1')) - CompatiblePSEditions = @('Desktop','Core') - RequiredModules = $requiredModules - NestedModules = @() + Path = $manifestPath + GUID = $($content.guid) + ModuleVersion = "$($content.version)" + FunctionsToExport = $functions + CmdletsToExport = @() + AliasesToExport = @() + Author = $($content.authors) + CompanyName = $($content.owners) + FileList = $files + RootModule = "$($this.ModuleName).psm1" + Description = 'Microsoft Graph Entra PowerShell.' + DotNetFrameworkVersion = $([System.Version]::Parse('4.7.2')) + PowerShellVersion = $([System.Version]::Parse('5.1')) + CompatiblePSEditions = @('Desktop', 'Core') + RequiredModules = $requiredModules + NestedModules = @() } - - if($null -ne $content.Prerelease){ + + if ($null -ne $content.Prerelease) { $PSData.Prerelease = $content.Prerelease } - $this.LoadMessage = $this.LoadMessage.Replace("{VERSION}", $content.version) + $this.LoadMessage = $this.LoadMessage.Replace('{VERSION}', $content.version) New-ModuleManifest @moduleSettings - Update-ModuleManifest -Path $manisfestPath -PrivateData $PSData + Update-ModuleManifest -Path $manifestPath -PrivateData $PSData } # Creates the ModuleMap object, this is mainly used by other methods but can be called when debugging or finding missing cmdlets - hidden [MappedCmdCollection] Map(){ + hidden [MappedCmdCollection] Map() { $this.ModuleMap = [MappedCmdCollection]::new($this.ModuleName) - $originalCmdlets = $this.GetModuleCommands($this.SourceModuleName, $this.SourceModulePrefixs, $true) - $targetCmdlets = $this.GetModuleCommands($this.DestinationModuleName, $this.DestinationPrefixs, $true) + $originalCmdlets = $this.GetModuleCommands($this.SourceModuleName, $this.SourceModulePrefixes, $true) + $targetCmdlets = $this.GetModuleCommands($this.DestinationModuleName, $this.DestinationPrefixes, $true) $newCmdletData = @() $cmdletsToExport = @() $missingCmdletsToExport = @() - if('Microsoft.Graph.Entra' -eq $this.ModuleName){ - $cmdletsToSkip = @("Add-AzureADMSApplicationOwner", "Get-AzureADMSApplication", "Get-AzureADMSApplicationExtensionProperty", "Get-AzureADMSApplicationOwner", "New-AzureADApplication", "New-AzureADMSApplicationExtensionProperty", "Remove-AzureADMSApplication", "Remove-AzureADMSApplicationExtensionProperty", "Remove-AzureADMSApplicationOwner", "Set-AzureADApplication", "Set-AzureADMSApplicationLogo", "Get-AzureADMSGroup", "New-AzureADGroup", "Remove-AzureADMSGroup", "Set-AzureADGroup") - } - else{ - $cmdletsToSkip = @("Add-AzureADMSAdministrativeUnitMember", "Add-AzureADMSScopedRoleMembership", "Get-AzureADMSAdministrativeUnit", "Get-AzureADMSAdministrativeUnitMember", "Get-AzureADMSScopedRoleMembership", "New-AzureADAdministrativeUnit", "Remove-AzureADMSAdministrativeUnit", "Remove-AzureADMSAdministrativeUnitMember", "Remove-AzureADMSScopedRoleMembership", "Set-AzureADAdministrativeUnit", "Add-AzureADMSApplicationOwner", "Get-AzureADMSApplication", "Get-AzureADMSApplicationExtensionProperty", "Get-AzureADMSApplicationOwner", "New-AzureADApplication","New-AzureADMSApplicationExtensionProperty","Remove-AzureADMSApplication","Remove-AzureADMSApplicationExtensionProperty","Remove-AzureADMSApplicationOwner","Set-AzureADApplication","Set-AzureADMSApplicationLogo","Get-AzureADMSGroup","New-AzureADGroup","Remove-AzureADMSGroup","Set-AzureADGroup","Get-AzureADMSPrivilegedRoleAssignment","Get-AzureADMSServicePrincipal","Set-AzureADMSServicePrincipal","Get-AzureADMSUser","Set-AzureADMSUser","New-AzureADMSUser","New-AzureADMSServicePrincipal") + if ('Microsoft.Graph.Entra' -eq $this.ModuleName) { + $cmdletsToSkip = @('Add-AzureADMSApplicationOwner', 'Get-AzureADMSApplication', 'Get-AzureADMSApplicationExtensionProperty', 'Get-AzureADMSApplicationOwner', 'New-AzureADApplication', 'New-AzureADMSApplicationExtensionProperty', 'Remove-AzureADMSApplication', 'Remove-AzureADMSApplicationExtensionProperty', 'Remove-AzureADMSApplicationOwner', 'Set-AzureADApplication', 'Set-AzureADMSApplicationLogo', 'Get-AzureADMSGroup', 'New-AzureADGroup', 'Remove-AzureADMSGroup', 'Set-AzureADGroup') + } else { + $cmdletsToSkip = @('Add-AzureADMSAdministrativeUnitMember', 'Add-AzureADMSScopedRoleMembership', 'Get-AzureADMSAdministrativeUnit', 'Get-AzureADMSAdministrativeUnitMember', 'Get-AzureADMSScopedRoleMembership', 'New-AzureADAdministrativeUnit', 'Remove-AzureADMSAdministrativeUnit', 'Remove-AzureADMSAdministrativeUnitMember', 'Remove-AzureADMSScopedRoleMembership', 'Set-AzureADAdministrativeUnit', 'Add-AzureADMSApplicationOwner', 'Get-AzureADMSApplication', 'Get-AzureADMSApplicationExtensionProperty', 'Get-AzureADMSApplicationOwner', 'New-AzureADApplication', 'New-AzureADMSApplicationExtensionProperty', 'Remove-AzureADMSApplication', 'Remove-AzureADMSApplicationExtensionProperty', 'Remove-AzureADMSApplicationOwner', 'Set-AzureADApplication', 'Set-AzureADMSApplicationLogo', 'Get-AzureADMSGroup', 'New-AzureADGroup', 'Remove-AzureADMSGroup', 'Set-AzureADGroup', 'Get-AzureADMSPrivilegedRoleAssignment', 'Get-AzureADMSServicePrincipal', 'Set-AzureADMSServicePrincipal', 'Get-AzureADMSUser', 'Set-AzureADMSUser', 'New-AzureADMSUser', 'New-AzureADMSServicePrincipal') } - foreach ($cmd in $originalCmdlets.Keys){ + foreach ($cmd in $originalCmdlets.Keys) { if ($cmdletsToSkip -contains $cmd) { continue } $originalCmdlet = $originalCmdlets[$cmd] $newFunction = $this.GetNewCmdTranslation($cmd, $originalCmdlet, $targetCmdlets, $this.NewPrefix) - if($newFunction){ + if ($newFunction) { $newCmdletData += $newFunction - $cmdletsToExport += $newFunction.Generate - } - else{ - $missingCmdletsToExport += $cmd + $cmdletsToExport += $newFunction.Generate + } else { + $missingCmdletsToExport += $cmd $this.MissingCommandsToMap += $cmd - } + } } - foreach($function in $this.HelperCmdletsToExport.GetEnumerator()){ + foreach ($function in $this.HelperCmdletsToExport.GetEnumerator()) { $cmdletsToExport += $function.Key } - + $this.ModuleMap.CommandsList = $cmdletsToExport $this.ModuleMap.MissingCommandsList = $missingCmdletsToExport $this.ModuleMap.Commands = $this.NewModuleMap($newCmdletData) return $this.ModuleMap - } + } - hidden [scriptblock] GetUnsupportedCommand(){ - $unsupported = @" + hidden [scriptblock] GetUnsupportedCommand() { + $unsupported = @' function Get-EntraUnsupportedCommand { Throw [System.NotSupportedException] "This command is not supported by Microsoft Entra PowerShell." } -"@ +'@ return [scriptblock]::Create($unsupported) } - hidden [scriptblock] GetAlisesFunction() { - if($this.ModuleMap){ + hidden [scriptblock] GetAliasesFunction() { + if ($this.ModuleMap) { $aliases = '' - foreach ($func in $this.ModuleMap.Commands) { + foreach ($func in $this.ModuleMap.Commands) { $aliases += " Set-Alias -Name $($func.SourceName) -Value $($func.Name) -Scope Global -Force`n" } foreach ($func in $this.MissingCommandsToMap) { $aliases += " Set-Alias -Name $($func) -Value Get-EntraUnsupportedCommand -Scope Global -Force`n" } - - #Adding direct aliases - $aliasDefinitionsPath ="" - if($this.ModuleName -eq 'Microsoft.Graph.Entra') - { + + #Adding direct aliases + $aliasDefinitionsPath = '' + if ($this.ModuleName -eq 'Microsoft.Graph.Entra') { $aliasDefinitionsPath = "$PSScriptRoot/EntraAliasDefinitions.ps1" - } - elseif ($this.ModuleName -eq 'Microsoft.Graph.Entra.Beta') { + } elseif ($this.ModuleName -eq 'Microsoft.Graph.Entra.Beta') { $aliasDefinitionsPath = "$PSScriptRoot/EntraBetaAliasDefinitions.ps1" } - #Adding direct aliases - $aliasDefinitionsPath ="" - if($this.ModuleName -eq 'Microsoft.Graph.Entra') - { + #Adding direct aliases + $aliasDefinitionsPath = '' + if ($this.ModuleName -eq 'Microsoft.Graph.Entra') { $aliasDefinitionsPath = "$PSScriptRoot/EntraAliasDefinitions.ps1" - } - elseif ($this.ModuleName -eq 'Microsoft.Graph.Entra.Beta') { + } elseif ($this.ModuleName -eq 'Microsoft.Graph.Entra.Beta') { $aliasDefinitionsPath = "$PSScriptRoot/EntraBetaAliasDefinitions.ps1" } @@ -664,7 +650,7 @@ function Get-EntraUnsupportedCommand { $aliases += $directAliases # Append the content to $aliases } - $aliasFunction = @" + $aliasFunction = @" function Enable-EntraAzureADAlias { $($aliases)} @@ -675,10 +661,10 @@ $($aliases)} return $null } - hidden [scriptblock] GetExportMemeber() { + hidden [scriptblock] GetExportMember() { $CommandsToExport = $this.ModuleMap.CommandsList - $CommandsToExport += "Get-EntraUnsupportedCommand" - $CommandsToExport += "Enable-EntraAzureADAlias" + $CommandsToExport += 'Get-EntraUnsupportedCommand' + $CommandsToExport += 'Enable-EntraAzureADAlias' $functionsToExport = @" Export-ModuleMember -Function @( @@ -699,31 +685,29 @@ Set-Variable -name MISSING_CMDS -value @('$($this.ModuleMap.MissingCommandsList hidden [CommandTranslation[]] NewModuleMap([PSCustomObject[]] $Commands) { [CommandTranslation[]] $translations = @() - foreach($Command in $Commands){ - if('' -eq $command.New){ + foreach ($Command in $Commands) { + if ('' -eq $command.New) { $translations += $this.NewCustomFunctionMap($Command) - } - else { + } else { $translations += $this.NewFunctionMap($Command) - } + } } return $translations } - hidden [CommandTranslation] NewCustomFunctionMap([PSCustomObject] $Command){ + hidden [CommandTranslation] NewCustomFunctionMap([PSCustomObject] $Command) { Write-Host "Creating custom function map for $($Command.Generate)" $parameterDefinitions = $this.GetParametersDefinitions($Command) - $ParamterTransformations = $this.GetParametersTransformations($Command) + $ParameterTransformations = $this.GetParametersTransformations($Command) $OutputTransformations = $this.GetOutputTransformations($Command) - if (($this.cmdtoSkipNameconverssion -notcontains $Command.Generate) -and ($parameterDefinitions.Contains('$ObjectId') -or $parameterDefinitions.Contains('$Id'))) { + if (($this.cmdToSkipNameConversion -notcontains $Command.Generate) -and ($parameterDefinitions.Contains('$ObjectId') -or $parameterDefinitions.Contains('$Id'))) { $function = @" function $($Command.Generate) { -$($Command.CustomScript) +$($Command.CustomScript) } "@ - } - else { + } else { $function = @" function $($Command.Generate) { [CmdletBinding($($Command.DefaultParameterSet))] @@ -731,63 +715,61 @@ function $($Command.Generate) { $parameterDefinitions ) -$($Command.CustomScript) +$($Command.CustomScript) } -"@ +"@ } $codeBlock = [Scriptblock]::Create($function) - return [CommandTranslation]::New($Command.Generate,$Command.Old,$codeBlock) + return [CommandTranslation]::New($Command.Generate, $Command.Old, $codeBlock) } - hidden [CommandTranslation] NewFunctionMap([PSCustomObject] $Command){ + hidden [CommandTranslation] NewFunctionMap([PSCustomObject] $Command) { Write-Host "Creating new function for $($Command.Generate)" - - $cmdLstToSkipKeyIdpair=@( - "Get-EntraGroup", - "Get-EntraServicePrincipalDelegatedPermissionClassification", - "Get-EntraApplication", - "Get-EntraDeletedApplication", - "Get-EntraDeletedGroup", - "Get-EntraBetaDeletedGroup", - "Get-EntraRoleAssignment", - "Get-EntraContact", - "Get-EntraRoleDefinition", - "Get-EntraContract", - "Get-EntraDevice", - "Get-EntraDirectoryRole", - "Get-EntraServicePrincipal", - "Get-EntraAdministrativeUnit", - "Get-EntraDirectoryRoleAssignment", - "Get-EntraBetaCustomSecurityAttributeDefinitionAllowedValue", - "Get-EntraBetaFeatureRolloutPolicy", - "Get-EntraBetaGroup", - "Get-EntraBetaPrivilegedResource", - "Get-EntraBetaServicePrincipal", - "Get-EntraBetaAdministrativeUnit", - "Get-EntraBetaAdministrativeUnit", - "Get-EntraBetaDevice", - "Get-EntraBetaPrivilegedRoleDefinition" + + $cmdLstToSkipKeyIdpair = @( + 'Get-EntraGroup', + 'Get-EntraServicePrincipalDelegatedPermissionClassification', + 'Get-EntraApplication', + 'Get-EntraDeletedApplication', + 'Get-EntraDeletedGroup', + 'Get-EntraBetaDeletedGroup', + 'Get-EntraRoleAssignment', + 'Get-EntraContact', + 'Get-EntraRoleDefinition', + 'Get-EntraContract', + 'Get-EntraDevice', + 'Get-EntraDirectoryRole', + 'Get-EntraServicePrincipal', + 'Get-EntraAdministrativeUnit', + 'Get-EntraDirectoryRoleAssignment', + 'Get-EntraBetaCustomSecurityAttributeDefinitionAllowedValue', + 'Get-EntraBetaFeatureRolloutPolicy', + 'Get-EntraBetaGroup', + 'Get-EntraBetaPrivilegedResource', + 'Get-EntraBetaServicePrincipal', + 'Get-EntraBetaAdministrativeUnit', + 'Get-EntraBetaAdministrativeUnit', + 'Get-EntraBetaDevice', + 'Get-EntraBetaPrivilegedRoleDefinition' ) - - + + $parameterDefinitions = $this.GetParametersDefinitions($Command) - $ParamterTransformations = $this.GetParametersTransformations($Command) + $ParameterTransformations = $this.GetParametersTransformations($Command) $OutputTransformations = $this.GetOutputTransformations($Command) - - if($cmdLstToSkipKeyIdpair.Contains($Command.Generate)) { - + + if ($cmdLstToSkipKeyIdpair.Contains($Command.Generate)) { + $keyId = $this.GetKeyIdPair($Command) + } else { + $keyId = '' } - else { - $keyId='' - } - - $customHeadersCommandName = "New-EntraCustomHeaders" - if($this.ModuleName -eq 'Microsoft.Graph.Entra.Beta') - { - $customHeadersCommandName = "New-EntraBetaCustomHeaders" + $customHeadersCommandName = 'New-EntraCustomHeaders' + + if ($this.ModuleName -eq 'Microsoft.Graph.Entra.Beta') { + $customHeadersCommandName = 'New-EntraBetaCustomHeaders' } $function = @" @@ -797,15 +779,15 @@ function $($Command.Generate) { $parameterDefinitions ) - PROCESS { + PROCESS { `$params = @{} `$customHeaders = $customHeadersCommandName -Command `$MyInvocation.MyCommand $($keyId) -$ParamterTransformations +$ParameterTransformations Write-Debug("============================ TRANSFORMATIONS ============================") `$params.Keys | ForEach-Object {"`$_ : `$(`$params[`$_])" } | Write-Debug Write-Debug("=========================================================================``n") - + `$response = $($Command.New) @params -Headers `$customHeaders $OutputTransformations `$response @@ -814,77 +796,76 @@ $OutputTransformations "@ $codeBlock = [Scriptblock]::Create($function) - return [CommandTranslation]::New($Command.Generate,$Command.Old,$codeBlock) + return [CommandTranslation]::New($Command.Generate, $Command.Old, $codeBlock) } - hidden [string] GetParametersDefinitions([PSCustomObject] $Command) { - $commonParameterNames = @("ProgressAction","Verbose", "Debug","ErrorAction", "ErrorVariable", "WarningAction", "WarningVariable", "OutBuffer", "PipelineVariable", "OutVariable", "InformationAction", "InformationVariable","WhatIf","Confirm") - $ignorePropertyParameter = @("Get-EntraBetaApplicationPolicy", "Get-EntraBetaApplicationSignInSummary","Get-EntraBetaPrivilegedRoleAssignment","Get-EntraBetaTrustFrameworkPolicy","Get-EntraBetaPolicy","Get-EntraBetaPolicyAppliedObject","Get-EntraBetaServicePrincipalPolicy","Get-EntraApplicationLogo","Get-EntraBetaApplicationLogo","Get-EntraApplicationKeyCredential","Get-EntraBetaApplicationKeyCredential","Get-EntraBetaServicePrincipalKeyCredential","Get-EntraBetaServicePrincipalPasswordCredential","Get-EntraServicePrincipalKeyCredential","Get-EntraServicePrincipalPasswordCredential") + hidden [string] GetParametersDefinitions([PSCustomObject] $Command) { + $commonParameterNames = @('ProgressAction', 'Verbose', 'Debug', 'ErrorAction', 'ErrorVariable', 'WarningAction', 'WarningVariable', 'OutBuffer', 'PipelineVariable', 'OutVariable', 'InformationAction', 'InformationVariable', 'WhatIf', 'Confirm') + $ignorePropertyParameter = @('Get-EntraBetaApplicationPolicy', 'Get-EntraBetaApplicationSignInSummary', 'Get-EntraBetaPrivilegedRoleAssignment', 'Get-EntraBetaTrustFrameworkPolicy', 'Get-EntraBetaPolicy', 'Get-EntraBetaPolicyAppliedObject', 'Get-EntraBetaServicePrincipalPolicy', 'Get-EntraApplicationLogo', 'Get-EntraBetaApplicationLogo', 'Get-EntraApplicationKeyCredential', 'Get-EntraBetaApplicationKeyCredential', 'Get-EntraBetaServicePrincipalKeyCredential', 'Get-EntraBetaServicePrincipalPasswordCredential', 'Get-EntraServicePrincipalKeyCredential', 'Get-EntraServicePrincipalPasswordCredential') $params = $(Get-Command -Name $Command.Old).Parameters $paramsList = @() - $ParamAlias=$null + $ParamAlias = $null foreach ($paramKey in $Command.Parameters.Keys) { - if($commonParameterNames.Contains($paramKey)) { + if ($commonParameterNames.Contains($paramKey)) { continue } $targetParam = $Command.Parameters[$paramKey] $param = $params[$paramKey] $paramType = $param.ParameterType.ToString() - $paramtypeToCreate = $param.ParameterType.ToString() - if($param.Name -eq 'All'){ - $paramType = "switch" + $paramTypeToCreate = $param.ParameterType.ToString() + if ($param.Name -eq 'All') { + $paramType = 'switch' } - - if( ($this.cmdtoSkipNameconverssion -notcontains $Command.Generate) -and (($param.Name -eq 'ObjectId' -or $param.Name -eq 'Id') -and $null -ne $targetParam.TargetName)){ + + if ( ($this.cmdToSkipNameConversion -notcontains $Command.Generate) -and (($param.Name -eq 'ObjectId' -or $param.Name -eq 'Id') -and $null -ne $targetParam.TargetName)) { if ($targetParam.TargetName) { $ParamAlias = $this.GetParameterAlias($param.Name) $param.Name = $targetParam.TargetName - } - } - if(($null -ne $this.TypePrefix) -and ($paramType -like "*$($this.TypePrefix)*")){ - if($paramType -like "*List*"){ - $paramType = "System.Collections.Generic.List``1[$($param.ParameterType.GenericTypeArguments.FullName)]" - $paramtypeToCreate = $param.ParameterType.GenericTypeArguments.FullName } - elseif($paramType -like "*Nullable*"){ + } + if (($null -ne $this.TypePrefix) -and ($paramType -like "*$($this.TypePrefix)*")) { + if ($paramType -like '*List*') { + $paramType = "System.Collections.Generic.List``1[$($param.ParameterType.GenericTypeArguments.FullName)]" + $paramTypeToCreate = $param.ParameterType.GenericTypeArguments.FullName + } elseif ($paramType -like '*Nullable*') { $paramType = "System.Nullable``1[$($param.ParameterType.GenericTypeArguments.FullName)]" - $paramtypeToCreate = $param.ParameterType.GenericTypeArguments.FullName + $paramTypeToCreate = $param.ParameterType.GenericTypeArguments.FullName } - if(!$this.TypesToCreate.Contains($paramtypeToCreate)) { - $this.TypesToCreate += $paramtypeToCreate - } - } + if (!$this.TypesToCreate.Contains($paramTypeToCreate)) { + $this.TypesToCreate += $paramTypeToCreate + } + } $paramBlock = @" - $ParamAlias + $ParamAlias $($this.GetParameterAttributes($Param))[$($paramType)] `$$($param.Name) "@ $paramsList += $paramBlock - $ParamAlias=$null + $ParamAlias = $null } $addProperty = $true - if('' -ne $Command.New){ + if ('' -ne $Command.New) { $addProperty = $false - $targetCmdparams = $(Get-Command -Name $Command.New).Parameters.Keys - if($null -ne $targetCmdparams){ - foreach($param in $targetCmdparams) { - if($param -eq 'Property') { + $targetCmdParams = $(Get-Command -Name $Command.New).Parameters.Keys + if ($null -ne $targetCmdParams) { + foreach ($param in $targetCmdParams) { + if ($param -eq 'Property') { $addProperty = $true break } - } - } + } + } } - if("Get" -eq $Command.Verb -and !$ignorePropertyParameter.Contains($Command.Generate) -and $addProperty){ + if ('Get' -eq $Command.Verb -and !$ignorePropertyParameter.Contains($Command.Generate) -and $addProperty) { $paramsList += $this.GetPropertyParameterBlock() } return $paramsList -Join ",`n" } - hidden [string] GetPropertyParameterBlock(){ - $propertyType = "System.String[]" + hidden [string] GetPropertyParameterBlock() { + $propertyType = 'System.String[]' $arrayAttrib = @() $arrayAttrib += "Mandatory = `$false" $arrayAttrib += "ValueFromPipeline = `$false" @@ -897,48 +878,44 @@ $OutputTransformations return $propertyParamBlock } - hidden [string] GetParameterAlias($param){ + hidden [string] GetParameterAlias($param) { return "[Alias('$param')]" } - hidden [string] GetParameterAttributes($param){ - $attributesString = "" + hidden [string] GetParameterAttributes($param) { + $attributesString = '' - foreach($attrib in $param.Attributes){ + foreach ($attrib in $param.Attributes) { $arrayAttrib = @() - + try { - if($attrib.ParameterSetName -ne "__AllParameterSets"){ + if ($attrib.ParameterSetName -ne '__AllParameterSets') { $arrayAttrib += "ParameterSetName = `"$($attrib.ParameterSetName)`"" } - } - catch {} - - try { - if($attrib.Mandatory){ + } catch {} + + try { + if ($attrib.Mandatory) { $arrayAttrib += "Mandatory = `$true" } - } - catch {} - - - try { - if($attrib.ValueFromPipeline){ + } catch {} + + + try { + if ($attrib.ValueFromPipeline) { $arrayAttrib += "ValueFromPipeline = `$true" } - } - catch {} - + } catch {} + try { - if($attrib.ValueFromPipelineByPropertyName){ + if ($attrib.ValueFromPipelineByPropertyName) { $arrayAttrib += "ValueFromPipelineByPropertyName = `$true" } - } - catch {} - + } catch {} + $strAttrib = $arrayAttrib -Join ', ' - if($strAttrib.Length -gt 0){ + if ($strAttrib.Length -gt 0) { $attributesString += "[Parameter($strAttrib)]`n " } } @@ -947,92 +924,87 @@ $OutputTransformations } hidden [string] GetParametersTransformations([PSCustomObject] $Command) { - $paramsList = "" + $paramsList = '' - foreach ($paramKey in $Command.Parameters.Keys) { + foreach ($paramKey in $Command.Parameters.Keys) { $param = $Command.Parameters[$paramKey] - $paramBlock = "" - - if([TransformationTypes]::None -eq $param.ConversionType){ + $paramBlock = '' + + if ([TransformationTypes]::None -eq $param.ConversionType) { $paramBlock = $this.GetParameterTransformationName($param.Name, $param.Name) - } - elseif([TransformationTypes]::Name -eq $param.ConversionType){ - if(($this.cmdtoSkipNameconverssion -notcontains $Command.Generate) -and ($param.Name -eq 'ObjectId' -or $param.Name -eq 'Id') -and $null -ne $param.TargetName){ + } elseif ([TransformationTypes]::Name -eq $param.ConversionType) { + if (($this.cmdToSkipNameConversion -notcontains $Command.Generate) -and ($param.Name -eq 'ObjectId' -or $param.Name -eq 'Id') -and $null -ne $param.TargetName) { $paramBlock = $this.GetParameterTransformationName($param.TargetName, $param.TargetName) - }else{ + } else { $paramBlock = $this.GetParameterTransformationName($param.Name, $param.TargetName) - } - } - elseif([TransformationTypes]::Bool2Switch -eq $param.ConversionType){ + } + } elseif ([TransformationTypes]::Bool2Switch -eq $param.ConversionType) { $paramBlock = $this.GetParameterTransformationBoolean2Switch($param.Name, $param.TargetName) - } - elseif([TransformationTypes]::SystemSwitch -eq $param.ConversionType){ + } elseif ([TransformationTypes]::SystemSwitch -eq $param.ConversionType) { $paramBlock = $this.GetParameterTransformationSystemSwitch($param.Name) - } - elseif([TransformationTypes]::ScriptBlock -eq $param.ConversionType){ + } elseif ([TransformationTypes]::ScriptBlock -eq $param.ConversionType) { $paramBlock = $this.GetParameterCustom($param) - } - elseif([TransformationTypes]::Remove -eq $param.ConversionType){ + } elseif ([TransformationTypes]::Remove -eq $param.ConversionType) { $paramBlock = $this.GetParameterException($param) } - - $paramsList += $paramBlock + + $paramsList += $paramBlock } - if("Get" -eq $Command.Verb){ - $paramsList += $this.GetCustomParameterTransformation("Property") + if ('Get' -eq $Command.Verb) { + $paramsList += $this.GetCustomParameterTransformation('Property') } - + return $paramsList } - hidden [string] GetKeyIdPair($Command){ + hidden [string] GetKeyIdPair($Command) { $keys = @() - foreach ($paramKey in $Command.Parameters.Keys) { + foreach ($paramKey in $Command.Parameters.Keys) { $param = $Command.Parameters[$paramKey] - if($param.NameChanged){ - if($param.Name -eq "ObjectId"){ + if ($param.NameChanged) { + if ($param.Name -eq 'ObjectId') { $keys += "$($param.Name) = `"Id`"" - } - elseif($param.Name -eq "Id"){ - } - else{ + } elseif ($param.Name -eq 'Id') { + } else { $keys += "$($param.Name) = `"$($param.TargetName)`"" } - } + } } - - return "`$keysChanged = @{$($keys -Join "; ")}" + + return "`$keysChanged = @{$($keys -Join '; ')}" } - hidden [string] GetParameterTransformationName([string] $OldName, [string] $NewName){ -# $paramBlock = @" -# if(`$null -ne `$PSBoundParameters["$($OldName)"]) -# { -# `$params["$($NewName)"] = `$PSBoundParameters["$($OldName)"] - -# } + hidden [string] GetParameterTransformationName([string] $OldName, [string] $NewName) { + # $paramBlock = @" + # if(`$null -ne `$PSBoundParameters["$($OldName)"]) + # { + # `$params["$($NewName)"] = `$PSBoundParameters["$($OldName)"] -# "@ - $paramBlock = if ($OldName -eq "Top") {@" + # } + + # "@ + $paramBlock = if ($OldName -eq 'Top') { + @" if (`$PSBoundParameters.ContainsKey(`"Top`")) { `$params["$($NewName)"] = `$PSBoundParameters["$($OldName)"] } "@ - } else {@" + } else { + @" if (`$null -ne `$PSBoundParameters["$($OldName)"]) { `$params["$($NewName)"] = `$PSBoundParameters["$($OldName)"] } "@ -} + } return $paramBlock } - hidden [string] GetParameterTransformationBoolean2Switch([string] $OldName, [string] $NewName){ + hidden [string] GetParameterTransformationBoolean2Switch([string] $OldName, [string] $NewName) { $paramBlock = @" if(`$null -ne `$PSBoundParameters["$($OldName)"]) { @@ -1046,7 +1018,7 @@ $OutputTransformations return $paramBlock } - hidden [string] GetParameterTransformationSystemSwitch([string] $Name){ + hidden [string] GetParameterTransformationSystemSwitch([string] $Name) { $paramBlock = @" if(`$PSBoundParameters.ContainsKey("$($Name)")) { @@ -1058,12 +1030,12 @@ $OutputTransformations } - hidden [string] GetParameterException([DataMap] $Param){ - $paramBlock = "" + hidden [string] GetParameterException([DataMap] $Param) { + $paramBlock = '' return $paramBlock } - hidden [string] GetParameterCustom([DataMap] $Param){ + hidden [string] GetParameterCustom([DataMap] $Param) { $paramBlock = @" if(`$null -ne `$PSBoundParameters["$($Param.Name)"]) { @@ -1076,7 +1048,7 @@ $OutputTransformations return $paramBlock } - hidden [string] GetCustomParameterTransformation([string] $ParameterName){ + hidden [string] GetCustomParameterTransformation([string] $ParameterName) { $paramBlock = @" if(`$null -ne `$PSBoundParameters["$($ParameterName)"]) { @@ -1086,43 +1058,39 @@ $OutputTransformations "@ return $paramBlock } - + hidden [string] GetOutputTransformations([PSCustomObject] $Command) { - $responseVerbs = @("Get","Add","New") - $output = "" - - if($this.CmdCustomizations.ContainsKey($Command.Old)) { - $cmd = $this.CmdCustomizations[$Command.Old] - if($null -ne $cmd.Outputs){ - foreach($key in $cmd.Outputs.GetEnumerator()) { - $customOutput = $cmd.Outputs[$key.Name] - if([TransformationTypes]::Name -eq $customOutput.ConversionType){ + $responseVerbs = @('Get', 'Add', 'New') + $output = '' + + if ($this.CmdCustomizations.ContainsKey($Command.Old)) { + $cmd = $this.CmdCustomizations[$Command.Old] + if ($null -ne $cmd.Outputs) { + foreach ($key in $cmd.Outputs.GetEnumerator()) { + $customOutput = $cmd.Outputs[$key.Name] + if ([TransformationTypes]::Name -eq $customOutput.ConversionType) { $output += $this.GetOutputTransformationName($customOutput.Name, $customOutput.TargetName) - } - elseif([TransformationTypes]::ScriptBlock -eq $customOutput.ConversionType){ + } elseif ([TransformationTypes]::ScriptBlock -eq $customOutput.ConversionType) { $output += $this.GetOutputTransformationCustom($customOutput) - } - elseif([TransformationTypes]::FlatObject -eq $customOutput.ConversionType){ + } elseif ([TransformationTypes]::FlatObject -eq $customOutput.ConversionType) { $output += $this.GetOutputTransformationFlatObject($customOutput) } } } } - - foreach($key in $this.GenericOutputTransformations.GetEnumerator()) { - $customOutput = $this.GenericOutputTransformations[$key.Name] - if(2 -eq $customOutput.ConversionType){ + + foreach ($key in $this.GenericOutputTransformations.GetEnumerator()) { + $customOutput = $this.GenericOutputTransformations[$key.Name] + if (2 -eq $customOutput.ConversionType) { $output += $this.GetOutputTransformationName($customOutput.Name, $customOutput.TargetName) - } - elseif([TransformationTypes]::ScriptBlock -eq $customOutput.ConversionType){ + } elseif ([TransformationTypes]::ScriptBlock -eq $customOutput.ConversionType) { $output += $this.GetOutputTransformationCustom($customOutput) - } - elseif([TransformationTypes]::FlatObject -eq $customOutput.ConversionType){ + } elseif ([TransformationTypes]::FlatObject -eq $customOutput.ConversionType) { $output += $this.GetOutputTransformationFlatObject($customOutput) } - } - - if("" -ne $output){ + } + + if ('' -ne $output) { $transform = @" `$response | ForEach-Object { if(`$null -ne `$_) { @@ -1132,19 +1100,19 @@ $($output) "@ return $transform } - return "" + return '' } - hidden [string] GetOutputTransformationName([string] $OldName, [string] $NewName){ - $outputBlock =@" + hidden [string] GetOutputTransformationName([string] $OldName, [string] $NewName) { + $outputBlock = @" Add-Member -InputObject `$_ -MemberType AliasProperty -Name $($NewName) -Value $($OldName) "@ return $outputBlock } - hidden [string] GetOutputTransformationCustom([DataMap] $Param){ - $outputBlock =@" + hidden [string] GetOutputTransformationCustom([DataMap] $Param) { + $outputBlock = @" $($Param.SpecialMapping) Add-Member -InputObject `$_ -MemberType ScriptProperty -Name $($Param.TargetName) -Value `$Value @@ -1152,218 +1120,209 @@ $($output) return $outputBlock } - hidden [string] GetOutputTransformationFlatObject([DataMap] $Param){ - $outputBlock =@" + hidden [string] GetOutputTransformationFlatObject([DataMap] $Param) { + $outputBlock = @" Add-Member -InputObject `$_ -NotePropertyMembers `$_.$($Param.Name) "@ return $outputBlock } - hidden [hashtable] GetModuleCommands([string[]] $ModuleNames, [string[]] $Prefix, [bool] $IgnoreEmptyNoun = $false){ - + hidden [hashtable] GetModuleCommands([string[]] $ModuleNames, [string[]] $Prefix, [bool] $IgnoreEmptyNoun = $false) { + $names = @() foreach ($moduleName in $ModuleNames) { $module = Get-Module -Name $moduleName $names += $module.ExportedCmdlets.Keys $names += $module.ExportedFunctions.Keys } - + $namesDic = @{} foreach ($name in $names) { $cmdComponents = $this.GetParsedCmd($name, $Prefix) - if(!$cmdComponents){ + if (!$cmdComponents) { $this.MissingCommandsToMap += $name continue } - if($IgnoreEmptyNoun -and !$cmdComponents.Noun) { + if ($IgnoreEmptyNoun -and !$cmdComponents.Noun) { continue } $namesDic.Add($name, $cmdComponents) } - + return $namesDic } - hidden [PSCustomObject] GetParsedCmd([string]$Name, [string[]]$Prefixs){ - foreach ($prefix in $Prefixs) { - $components = $name -split '-' + hidden [PSCustomObject] GetParsedCmd([string]$Name, [string[]]$Prefixes) { + foreach ($prefix in $Prefixes) { + $components = $name -split '-' $verb = $components[0] $prefixNoun = $components[1] $components = $prefixNoun -split $prefix - if($components.Length -eq 1) - { + if ($components.Length -eq 1) { continue } $noun = $prefixNoun.Substring($prefix.Length, $prefixNoun.Length - $prefix.Length) - + return [PSCustomObject] @{ - Verb = $verb - Noun = $noun + Verb = $verb + Noun = $noun Prefix = $prefix - } + } } return $null } - hidden [PSCustomObject] GetNewCmdTranslation($SourceCmdName, $SourceCmdlet, $TargetCmdlets, $NewPrefix){ + hidden [PSCustomObject] GetNewCmdTranslation($SourceCmdName, $SourceCmdlet, $TargetCmdlets, $NewPrefix) { $verbsEquivalence = @{ - 'Get' = @('Get') - 'New' = @('New','Add') - 'Add' = @('New','Add') - 'Remove' = @('Remove','Delete') - 'Delete' = @('Remove','Delete') - 'Set' = @('Set','Update') - 'Update' = @('Set','Update') + 'Get' = @('Get') + 'New' = @('New', 'Add') + 'Add' = @('New', 'Add') + 'Remove' = @('Remove', 'Delete') + 'Delete' = @('Remove', 'Delete') + 'Set' = @('Set', 'Update') + 'Update' = @('Set', 'Update') 'Confirm' = @('Confirm') - 'Enable' = @('New') + 'Enable' = @('New') } $targetCmd = $null - if($this.CmdCustomizations.ContainsKey($SourceCmdName)){ + if ($this.CmdCustomizations.ContainsKey($SourceCmdName)) { $targetCmd = $this.CmdCustomizations[$SourceCmdName].TargetName - } - else { - foreach ($prefix in $this.DestinationPrefixs){ - foreach ($verb in $verbsEquivalence[$SourceCmdlet.Verb]){ + } else { + foreach ($prefix in $this.DestinationPrefixes) { + foreach ($verb in $verbsEquivalence[$SourceCmdlet.Verb]) { $tmpCmd = "$($verb)-$($prefix)$($SourceCmdlet.Noun)" - if($TargetCmdlets.ContainsKey($tmpCmd)){ - $targetCmd = $tmpCmd; - break; + if ($TargetCmdlets.ContainsKey($tmpCmd)) { + $targetCmd = $tmpCmd + break } } } } - - if($null -ne $targetCmd){ - if($SourceCmdlet.Prefix.contains('MS')){ + + if ($null -ne $targetCmd) { + if ($SourceCmdlet.Prefix.contains('MS')) { $Prefix = $NewPrefix } else { $prefix = $NewPrefix } - $NewName = "" + $NewName = '' switch ($SourceCmdlet.Noun) { - "RoleDefinition" { $NewName = 'DirectoryRoleDefinition' } - "RoleAssignment" { $NewName = 'DirectoryRoleAssignment' } - "ServiceAppRoleAssignedTo" { $NewName = 'ServicePrincipalAppRoleAssignedTo' } - "ServiceAppRoleAssignment" { $NewName = 'ServicePrincipalAppRoleAssignment' } - "CustomSecurityAttributeDefinitionAllowedValues" { $NewName = 'CustomSecurityAttributeDefinitionAllowedValue' } - "AuditSignInLogs" { $NewName = 'AuditSignInLog' } - "AuditDirectoryLogs" { $NewName = 'AuditDirectoryLog' } + 'RoleDefinition' { $NewName = 'DirectoryRoleDefinition' } + 'RoleAssignment' { $NewName = 'DirectoryRoleAssignment' } + 'ServiceAppRoleAssignedTo' { $NewName = 'ServicePrincipalAppRoleAssignedTo' } + 'ServiceAppRoleAssignment' { $NewName = 'ServicePrincipalAppRoleAssignment' } + 'CustomSecurityAttributeDefinitionAllowedValues' { $NewName = 'CustomSecurityAttributeDefinitionAllowedValue' } + 'AuditSignInLogs' { $NewName = 'AuditSignInLog' } + 'AuditDirectoryLogs' { $NewName = 'AuditDirectoryLog' } default { $NewName = $SourceCmdlet.Noun } } $cmd = [PSCustomObject]@{ - Old = '{0}-{1}{2}' -f $SourceCmdlet.Verb, $SourceCmdlet.Prefix, $SourceCmdlet.Noun - New = $targetCmd - Generate = '{0}-{1}{2}' -f $SourceCmdlet.Verb, $Prefix, $NewName - Noun = $SourceCmdlet.Noun - Verb = $SourceCmdlet.Verb - Parameters = $null - DefaultParameterSet = "" - CustomScript = $null + Old = '{0}-{1}{2}' -f $SourceCmdlet.Verb, $SourceCmdlet.Prefix, $SourceCmdlet.Noun + New = $targetCmd + Generate = '{0}-{1}{2}' -f $SourceCmdlet.Verb, $Prefix, $NewName + Noun = $SourceCmdlet.Noun + Verb = $SourceCmdlet.Verb + Parameters = $null + DefaultParameterSet = '' + CustomScript = $null } - if('' -eq $targetCmd){ + if ('' -eq $targetCmd) { $cmd.CustomScript = $this.CmdCustomizations[$SourceCmdName].CustomScript } $cmd.Parameters = $this.GetCmdletParameters($cmd) - $defaulParam = $this.GetDefaultParameterSet($SourceCmdName) - $cmd.DefaultParameterSet = "DefaultParameterSetName = '$defaulParam'" + $defaultParam = $this.GetDefaultParameterSet($SourceCmdName) + $cmd.DefaultParameterSet = "DefaultParameterSetName = '$defaultParam'" return $cmd } return $null } - hidden [string] GetDefaultParameterSet($Cmdlet){ + hidden [string] GetDefaultParameterSet($Cmdlet) { $sourceCmd = Get-Command -Name $Cmdlet return $sourceCmd.DefaultParameterSet } - hidden [hashtable] GetCmdletParameters($Cmdlet){ - $Bool2Switch = @("All") - $SystemDebug = @("Verbose", "Debug") - $commonParameterNames = @("ErrorAction", "ErrorVariable", "WarningAction", "WarningVariable", "OutBuffer", "PipelineVariable", "OutVariable", "InformationAction", "InformationVariable") + hidden [hashtable] GetCmdletParameters($Cmdlet) { + $Bool2Switch = @('All') + $SystemDebug = @('Verbose', 'Debug') + $commonParameterNames = @('ErrorAction', 'ErrorVariable', 'WarningAction', 'WarningVariable', 'OutBuffer', 'PipelineVariable', 'OutVariable', 'InformationAction', 'InformationVariable') $sourceCmd = Get-Command -Name $Cmdlet.Old $targetCmd = $null - if('' -ne $Cmdlet.New){ - $targetCmd = Get-Command -Name $Cmdlet.New - } + if ('' -ne $Cmdlet.New) { + $targetCmd = Get-Command -Name $Cmdlet.New + } $paramsList = @{} foreach ($paramKey in $sourceCmd.Parameters.Keys) { $param = $sourceCmd.Parameters[$paramKey] $paramObj = [DataMap]::New($param.Name) - - if($this.CmdCustomizations.ContainsKey($Cmdlet.Old)) { + + if ($this.CmdCustomizations.ContainsKey($Cmdlet.Old)) { $custom = $this.CmdCustomizations[$Cmdlet.Old] - if(($null -ne $custom.Parameters) -and ($custom.Parameters.contains($param.Name))){ + if (($null -ne $custom.Parameters) -and ($custom.Parameters.contains($param.Name))) { $paramsList.Add($param.Name, $custom.Parameters[$param.Name]) continue } - if($custom.SpecialMapping) { - $paramObj.SetNone() + if ($custom.SpecialMapping) { + $paramObj.SetNone() $paramsList.Add($param.Name, $paramObj) continue } } - - if($this.GenericParametersTransformations.ContainsKey($param.Name)) { + + if ($this.GenericParametersTransformations.ContainsKey($param.Name)) { $genericParam = $this.GenericParametersTransformations[$param.Name] - if(5 -eq $genericParam.ConversionType){ + if (5 -eq $genericParam.ConversionType) { $tempName = "$($Cmdlet.Noun)$($genericParam.TargetName)" - if($targetCmd.Parameters.ContainsKey($tempName)){ + if ($targetCmd.Parameters.ContainsKey($tempName)) { $paramObj.SetTargetName($tempName) - } - elseif($targetCmd.Parameters.ContainsKey($genericParam.TargetName)){ + } elseif ($targetCmd.Parameters.ContainsKey($genericParam.TargetName)) { $paramObj.SetTargetName($genericParam.TargetName) - } - else - { + } else { foreach ($key in $targetCmd.Parameters.Keys) { - if($key.EndsWith($genericParam.TargetName)){ + if ($key.EndsWith($genericParam.TargetName)) { $paramObj.SetTargetName($key) break } } } - $paramsList.Add($paramObj.Name,$paramObj) - }else{ + $paramsList.Add($paramObj.Name, $paramObj) + } else { $paramsList.Add($genericParam.Name, $genericParam) - } + } continue } - - if($commonParameterNames.Contains($param.Name)) { + + if ($commonParameterNames.Contains($param.Name)) { $paramObj.SetNone() - } - elseif($Bool2Switch.Contains($param.Name)) { + } elseif ($Bool2Switch.Contains($param.Name)) { $paramObj.SetBool2Switch($param.Name) - } - elseif($SystemDebug.Contains($param.Name)) { + } elseif ($SystemDebug.Contains($param.Name)) { $paramObj.SetSystemSwitch($param.Name) - } - else - { - if($targetCmd.Parameters.ContainsKey($param.Name)){ - $paramObj.SetNone() + } else { + if ($targetCmd.Parameters.ContainsKey($param.Name)) { + $paramObj.SetNone() } } - - $paramsList.Add($paramObj.Name,$paramObj) + + $paramsList.Add($paramObj.Name, $paramObj) } - - return $paramsList + + return $paramsList } - hidden [string] GetFileHeader(){ - return @" + hidden [string] GetFileHeader() { + return @' # ------------------------------------------------------------------------------ # Copyright (c) Microsoft Corporation. All Rights Reserved. Licensed under the MIT License. See License in the project root for license information. # ------------------------------------------------------------------------------ Set-StrictMode -Version 5 -"@ +'@ } }