MDCA.psm1
$script:ModuleRoot = $PSScriptRoot $script:ModuleVersion = (Import-PowerShellDataFile -Path "$($script:ModuleRoot)\MDCA.psd1").ModuleVersion # Detect whether at some level dotsourcing was enforced $script:doDotSource = Get-PSFConfigValue -FullName MDCA.Import.DoDotSource -Fallback $false if ($MDCA_dotsourcemodule) { $script:doDotSource = $true } <# Note on Resolve-Path: All paths are sent through Resolve-Path/Resolve-PSFPath in order to convert them to the correct path separator. This allows ignoring path separators throughout the import sequence, which could otherwise cause trouble depending on OS. Resolve-Path can only be used for paths that already exist, Resolve-PSFPath can accept that the last leaf my not exist. This is important when testing for paths. #> # Detect whether at some level loading individual module files, rather than the compiled module was enforced $importIndividualFiles = Get-PSFConfigValue -FullName MDCA.Import.IndividualFiles -Fallback $false if ($MDCA_importIndividualFiles) { $importIndividualFiles = $true } if (Test-Path (Resolve-PSFPath -Path "$($script:ModuleRoot)\..\.git" -SingleItem -NewChild)) { $importIndividualFiles = $true } if ("<was compiled>" -eq '<was not compiled>') { $importIndividualFiles = $true } function Import-ModuleFile { <# .SYNOPSIS Loads files into the module on module import. .DESCRIPTION This helper function is used during module initialization. It should always be dotsourced itself, in order to proper function. This provides a central location to react to files being imported, if later desired .PARAMETER Path The path to the file to load .EXAMPLE PS C:\> . Import-ModuleFile -File $function.FullName Imports the file stored in $function according to import policy #> [CmdletBinding()] Param ( [string] $Path ) $resolvedPath = $ExecutionContext.SessionState.Path.GetResolvedPSPathFromPSPath($Path).ProviderPath if ($doDotSource) { . $resolvedPath } else { $ExecutionContext.InvokeCommand.InvokeScript($false, ([scriptblock]::Create([io.file]::ReadAllText($resolvedPath))), $null, $null) } } #region Load individual files if ($importIndividualFiles) { # Execute Preimport actions foreach ($path in (& "$ModuleRoot\internal\scripts\preimport.ps1")) { . Import-ModuleFile -Path $path } # Import all internal functions foreach ($function in (Get-ChildItem "$ModuleRoot\internal\functions" -Filter "*.ps1" -Recurse -ErrorAction Ignore)) { . Import-ModuleFile -Path $function.FullName } # Import all public functions foreach ($function in (Get-ChildItem "$ModuleRoot\functions" -Filter "*.ps1" -Recurse -ErrorAction Ignore)) { . Import-ModuleFile -Path $function.FullName } # Execute Postimport actions foreach ($path in (& "$ModuleRoot\internal\scripts\postimport.ps1")) { . Import-ModuleFile -Path $path } # End it here, do not load compiled code below return } #endregion Load individual files #region Load compiled code <# This file loads the strings documents from the respective language folders. This allows localizing messages and errors. Load psd1 language files for each language you wish to support. Partial translations are acceptable - when missing a current language message, it will fallback to English or another available language. #> Import-PSFLocalizedString -Path "$($script:ModuleRoot)\en-us\*.psd1" -Module 'MDCA' -Language 'en-US' enum SubnetCategory { Unknown = 0 Corporate = 1 Administrative = 2 Risky = 3 VPN = 4 CloudProvider = 5 Other = 6 } function ConvertFrom-RestSubnet { <# .SYNOPSIS Converts subnet objects to look nice. .DESCRIPTION Converts subnet objects to look nice. .PARAMETER InputObject The rest response representing a subnet .EXAMPLE PS C:\> Invoke-RestRequest -Path "subnet/$idString" -ErrorAction Stop | ConvertFrom-RestSubnet Retrieves the specified subnet and converts it into something userfriendly #> [CmdletBinding()] param ( [Parameter(ValueFromPipeline = $true)] $InputObject ) process { if (-not $InputObject) { return } [PSCustomObject]@{ PSTypeName = 'Mdca.Subnet' ID = $InputObject._id Name = $InputObject.Name Subnets = $InputObject.subnets.originalString SubnetsOriginal = $InputObject.subnets Location = $InputObject.location Organization = $InputObject.organization Tags = $InputObject.tags.name TagsOriginal = $InputObject.tags Category = $InputObject.Category -as [SubnetCategory] LastModified = $InputObject.LastModified } } } function Connect-MdcaService { <# .SYNOPSIS Connect to the Microsoft Defender for Cloud Apps API .DESCRIPTION Connect to the Microsoft Defender for Cloud Apps API .PARAMETER ClientID ID of the registered/enterprise application used for authentication. .PARAMETER TenantID The ID of the tenant/directory to connect to. .PARAMETER TenantName The simple name of the tenant. Assuming the path to the MDCA portal is https://contoso.portal.cloudappsecurity.com/#/dashboard Then the TenantName would be "contoso" Use the "-ServiceUrl" parameter if connecting to special clouds and need to change the domain "cloudappsecurity.com". .PARAMETER Scopes Any scopes to include in the request. Only used for interactive/delegate workflows, ignored for Certificate based authentication or when using Client Secrets. .PARAMETER DeviceCode Use the Device Code delegate authentication flow. This will prompt the user to complete login via browser. .PARAMETER Certificate The Certificate object used to authenticate with. Part of the Application Certificate authentication workflow. .PARAMETER CertificateThumbprint Thumbprint of the certificate to authenticate with. The certificate must be stored either in the user or computer certificate store. Part of the Application Certificate authentication workflow. .PARAMETER CertificateName The name/subject of the certificate to authenticate with. The certificate must be stored either in the user or computer certificate store. The newest certificate with a private key will be chosen. Part of the Application Certificate authentication workflow. .PARAMETER CertificatePath Path to a PFX file containing the certificate to authenticate with. Part of the Application Certificate authentication workflow. .PARAMETER CertificatePassword Password to use to read a PFX certificate file. Only used together with -CertificatePath. Part of the Application Certificate authentication workflow. .PARAMETER ClientSecret The client secret configured in the registered/enterprise application. Part of the Client Secret Certificate authentication workflow. .PARAMETER Credential The credentials to use to authenticate as a user. Part of the Username and Password delegate authentication workflow. Note: This workflow only works with cloud-only accounts and requires scopes to be pre-approved. .PARAMETER Token A legacy token used to authorize API access. These tokens are deprecated and should be avoided, but not every migration can be accomplished instantaneously... .PARAMETER ServiceUrl The pattern for the Url to connect to. This usually needs not be changed other than when connecting to non-default clouds. Receives the tenant-name as format-value that will be inserted into {0} if present. Defaults to: https://{0}.portal.cloudappsecurity.com/api/v1 .EXAMPLE PS C:\> Connect-MdcaService -ClientID $clientID -TenantID $tenantID -TenantName contoso -Certificate $cert Connect to the specified tenant using a certificate .EXAMPLE PS C:\> Connect-MdcaService -ClientID $clientID -TenantID $tenantID -TenantName contoso -DeviceCode Connect to the specified tenant using the DeviceCode flow #> [CmdletBinding()] param ( [Parameter(Mandatory = $true, ParameterSetName = 'DeviceCode')] [Parameter(Mandatory = $true, ParameterSetName = 'AppCertificate')] [Parameter(Mandatory = $true, ParameterSetName = 'AppSecret')] [Parameter(Mandatory = $true, ParameterSetName = 'UsernamePassword')] [string] $ClientID, [Parameter(Mandatory = $true, ParameterSetName = 'DeviceCode')] [Parameter(Mandatory = $true, ParameterSetName = 'AppCertificate')] [Parameter(Mandatory = $true, ParameterSetName = 'AppSecret')] [Parameter(Mandatory = $true, ParameterSetName = 'UsernamePassword')] [string] $TenantID, [Parameter(Mandatory = $true)] [string] $TenantName, [string[]] $Scopes, [Parameter(ParameterSetName = 'DeviceCode')] [switch] $DeviceCode, [Parameter(ParameterSetName = 'AppCertificate')] [System.Security.Cryptography.X509Certificates.X509Certificate2] $Certificate, [Parameter(ParameterSetName = 'AppCertificate')] [string] $CertificateThumbprint, [Parameter(ParameterSetName = 'AppCertificate')] [string] $CertificateName, [Parameter(ParameterSetName = 'AppCertificate')] [string] $CertificatePath, [Parameter(ParameterSetName = 'AppCertificate')] [System.Security.SecureString] $CertificatePassword, [Parameter(Mandatory = $true, ParameterSetName = 'AppSecret')] [System.Security.SecureString] $ClientSecret, [Parameter(Mandatory = $true, ParameterSetName = 'UsernamePassword')] [PSCredential] $Credential, [Parameter(Mandatory = $true, ParameterSetName = 'LegacyToken')] [System.Security.SecureString] $Token, [string] $ServiceUrl = 'https://{0}.portal.cloudappsecurity.com/api/v1' ) begin { $param = $PSBoundParameters | ConvertTo-PSFHashtable -ReferenceCommand Connect-RestService $param.Service = 'MDCA' $param.ServiceUrl = $ServiceUrl -f $TenantName $param.Resource = '05a65629-4c1b-48c1-a78b-804c4abdd4af' } process { if ($Token) { Write-PSFMessage -Level Warning -String 'Connect-MdcaService.Deprecated' -Once TokenIsDeprecated $param = @{ Service = 'MDCA' ServiceUrl = $ServiceUrl -f $TenantName ValidAfter = (Get-Date) ValidUntil = (Get-Date).AddYears(500) Data = @{ Token = $token } ExtraHeaderContent = @{ 'content-type' = 'application/json' } GetHeaderCode = { param ($Data) $token = [PSCredential]::new("foo", $Data.Data.Token).GetNetworkCredential().Password @{ Authorization = "Token $token" } } } Set-RestConnection @param return } try { Connect-RestService @param -ErrorAction Stop } catch { $PSCmdlet.ThrowTerminatingError($_) } Set-RestConnection -Service MDCA -ExtraHeaderContent @{ 'content-type' = 'application/json' } } } function Get-MdcaAlert { <# .SYNOPSIS List/Retrieve alerts .DESCRIPTION List/Retrieve alerts Either a specific alert by ID or a list by filter. .PARAMETER ID ID of the event to retrieve. .PARAMETER SortField Sort results by the specified field. By default, results are however sorted as the API backend choses. Options: date, severity .PARAMETER Descending By default, results are sorted in an ascending order (if sorting at all). This parameter reverses the sorting order. .PARAMETER Skip Skip the first X results. .PARAMETER Limit Return only X results in total. .PARAMETER Filter A custom filter as defined here: https://learn.microsoft.com/en-us/defender-cloud-apps/api-alerts#filters Example filter for open alerts of high severity: @{ alertOpen = @{ eq = $true } severity = @{ eq = 2 } } .EXAMPLE PS C:\> Get-MdcaAlert List all alerts. .EXAMPLE PS C:\> Get-MdcaAlert -ID 909cd095-1677-44eb-98a3-dda1e3c26733 Retrieve the specified alert #> [CmdletBinding(DefaultParameterSetName = 'default')] param ( [Parameter(Mandatory = $true, ParameterSetName = 'identity', ValueFromPipeline = $true, ValueFromPipelineByPropertyName = $true)] [Alias('_id')] [string[]] $ID, [Parameter(ParameterSetName = 'default')] [Parameter(ParameterSetName = 'Filter')] [ValidateSet('date', 'severity')] [string] $SortField, [Parameter(ParameterSetName = 'default')] [Parameter(ParameterSetName = 'Filter')] [switch] $Descending, [Parameter(ParameterSetName = 'default')] [Parameter(ParameterSetName = 'Filter')] [int] $Skip, [Parameter(ParameterSetName = 'default')] [Parameter(ParameterSetName = 'Filter')] [int] $Limit, [Parameter(ParameterSetName = 'Filter')] [hashtable] $Filter ) begin { Assert-RestConnection -Service MDCA -Cmdlet $PSCmdlet } process { #region ID if ($ID) { foreach ($idString in $ID) { try { Invoke-RestRequest -Path "alerts/$idString" -ErrorAction Stop } catch { $PSCmdlet.WriteError($_) } } return } #endregion ID $body = @{ } if ($SortField) { $body.sortField = $SortField $body.sortDirection = 'asc' if ($Descending) { $body.sortDirection = 'dsc' } } $noPaging = $false if ($PSBoundParameters.ContainsKey("Skip")) { $body.skip = $Skip; $noPaging = $true } if ($PSBoundParameters.ContainsKey("Limit")) { $body.limit = $Limit; $noPaging = $true } if ($Filter) { $body.filters = $Filter } do { $result = Invoke-RestRequest -Path alerts -Body $body $body.skip = @($result.Data).Count + $body.skip $result.data } while ($result.hasNext -and -not $noPaging) } } function Get-MdcaFile { <# .SYNOPSIS List or retrieve files. .DESCRIPTION List or retrieve files. .PARAMETER ID ID of the file to retrieve. .PARAMETER Skip Skip the first X results when listing files. .PARAMETER Limit Maximum number of files to retrieve. .PARAMETER Filter A custom filter as defined here: https://learn.microsoft.com/en-us/defender-cloud-apps/api-files#filters Example filter for public documents: @{ fileType = @{ eq = 1 } sharing = @{ eq = 3 } } .EXAMPLE PS C:\> Get-MdcaFile List all files. .EXAMPLE PS C:\> Get-MdcaFile -ID 25e86014-b08d-4d42-a685-ca00a230c458 Retrieve the specified file. #> [CmdletBinding(DefaultParameterSetName = 'default')] param ( [Parameter(Mandatory = $true, ParameterSetName = 'identity', ValueFromPipeline = $true, ValueFromPipelineByPropertyName = $true)] [Alias('_id')] [string[]] $ID, [Parameter(ParameterSetName = 'default')] [int] $Skip, [Parameter(ParameterSetName = 'default')] [int] $Limit, [hashtable] $Filter ) begin { Assert-RestConnection -Service MDCA -Cmdlet $PSCmdlet } process { #region ID if ($ID) { foreach ($idString in $ID) { try { Invoke-RestRequest -Path "files/$idString" -ErrorAction Stop } catch { $PSCmdlet.WriteError($_) } } return } #endregion ID $body = @{ } $noPaging = $false if ($PSBoundParameters.ContainsKey("Skip")) { $body.skip = $Skip; $noPaging = $true } if ($PSBoundParameters.ContainsKey("Limit")) { $body.limit = $Limit; $noPaging = $true } if ($Filter) { $body.filters = $Filter } do { $result = Invoke-RestRequest -Path files -Body $body $body.skip = @($result.Data).Count + $body.skip $result.data } while ($result.hasNext -and -not $noPaging) } } function Get-MdcaSubnet { <# .SYNOPSIS Returns the available / configured subnets. .DESCRIPTION Returns the available / configured subnets. Note: Filter parameters are currently non-functional. .PARAMETER ID ID of a subnet to retrieve. .PARAMETER SortField Field by which to sort the results. .PARAMETER Descending Whether to sort in a descending order .PARAMETER Skip Skip the first X results Using this parameter disables the automatic paging feature. .PARAMETER Limit Maximum number of subnets to return. Using this parameter disables the automatic paging feature. .PARAMETER Filter A full filter to specify with the request .PARAMETER IncludeCategory Only return subnets that contain any of the specified categories. .PARAMETER ExcludeCategory Do not return subnets that contain any of the specified categories. .PARAMETER IncludeTag Only return subnets that contain any of the specified tags. .PARAMETER ExcludeTag Do not return subnets that contain any of the specified tags. .PARAMETER BuiltIn Specify whether built-in only or custom only subnets should be returned .EXAMPLE PS C:\> Get-MdcaSubnet Returns all subnets from MDCA #> [CmdletBinding(DefaultParameterSetName = 'default')] Param ( [Parameter(Mandatory = $true, ParameterSetName = 'identity', ValueFromPipeline = $true, ValueFromPipelineByPropertyName = $true)] [Alias('_id')] [string[]] $ID, [ValidateSet('category', 'tags', 'name')] [string] $SortField, [switch] $Descending, [int] $Skip, [int] $Limit, [Parameter(ParameterSetName = 'Filter')] [hashtable] $Filter, [Parameter(ParameterSetName = 'Condition')] [SubnetCategory[]] $IncludeCategory, [Parameter(ParameterSetName = 'Condition')] [SubnetCategory[]] $ExcludeCategory, [Parameter(ParameterSetName = 'Condition')] [string[]] $IncludeTag, [Parameter(ParameterSetName = 'Condition')] [string[]] $ExcludeTag, [Parameter(ParameterSetName = 'Condition')] [bool] $BuiltIn ) begin { Assert-RestConnection -Service MDCA -Cmdlet $PSCmdlet } process { if ($ID) { foreach ($idString in $ID) { try { Invoke-RestRequest -Path "subnet/$idString" -ErrorAction Stop | ConvertFrom-RestSubnet } catch { $PSCmdlet.WriteError($_) } } return } $body = @{ } if ($SortField) { $body.sortField = $SortField $body.sortDirection = 'asc' if ($Descending) { $body.sortDirection = 'dsc' } } $noPaging = $false if ($PSBoundParameters.ContainsKey("Skip")) { $body.skip = $Skip; $noPaging = $true } if ($PSBoundParameters.ContainsKey("Limit")) { $body.limit = $Limit; $noPaging = $true } #region Filters # TODO: Figure out why filters are ignored switch ($PSCmdlet.ParameterSetName) { 'Filter' { $body.filters = $Filter } 'Condition' { $filterHash = @{} if ($IncludeCategory -or $ExcludeCategory) { $filterHash.category = @{} if ($IncludeCategory) { $filterHash.category.eq = @($IncludeCategory | ForEach-Object { [int]$_ }) } if ($ExcludeCategory) { $filterHash.category.neq = @($ExcludeCategory | ForEach-Object { [int]$_ }) } } if ($IncludeTag -or $ExcludeTag) { $filterHash.tags = @{ } if ($IncludeTag) { $filterHash.tags.eq = $IncludeTag } if ($ExcludeTag) { $filterHash.tags.neq = $ExcludeTag } } if ($PSBoundParameters.ContainsKey("BuiltIn")) { $filterHash.builtIn = @{ eq = $BuiltIn } } $body.filters = $filterHash } } #endregion Filters do { $result = Invoke-RestRequest -Path subnet -Body $body $body.skip = @($result.Data).Count + $body.skip $result.data | ConvertFrom-RestSubnet } while ($result.hasNext -and -not $noPaging) } } function Invoke-MdcaRequest { <# .SYNOPSIS Execute a custom request against the MDCA API .DESCRIPTION Execute a custom request against the MDCA API .PARAMETER Path The relative path of the endpoint to query. .PARAMETER Body Any body content needed for the request. .PARAMETER Query Any query content to include in the request. In opposite to -Body this is attached to the request Url and usually used for filtering. .PARAMETER Method The Rest Method to use. Defaults to GET .PARAMETER Header The Rest Method to use. Defaults to GET .EXAMPLE PS C:\> Invoke-MdcaRequest -Path activities List all activities #> [CmdletBinding()] Param ( [Parameter(Mandatory = $true)] [string] $Path, [Hashtable] $Body = @{ }, [Hashtable] $Query = @{ }, [string] $Method = 'GET', [Hashtable] $Header = @{ } ) process { $parameters = $PSBoundParameters | ConvertTo-PSFHashtable Invoke-RestRequest @parameters } } function New-MdcaSubnet { <# .SYNOPSIS Create a new MDCA subnet .DESCRIPTION Create a new MDCA subnet .PARAMETER Name Name of the subnet to create .PARAMETER Category The category the subnet should have .PARAMETER Subnets IPRanges / subnets that should be part of this subnet .PARAMETER Organization The organization this subnet is part of .PARAMETER Tag Any tags this subnet should have. .PARAMETER EnableException This parameters disables user-friendly warnings and enables the throwing of exceptions. This is less user friendly, but allows catching exceptions in calling scripts. .PARAMETER WhatIf if this switch is enabled, no actions are performed but informational messages will be displayed that explain what would happen if the command were to run. .PARAMETER Confirm If this switch is enabled, you will be prompted for confirmation before executing any operations that change state. .EXAMPLE PS C:\> New-MdcaSubnet -Name "europe" -Category Corporate -Subnets '10.1.0.0/16' -Organization ContosoEU -Tag europe, intranet Creates a new MDCA subnet #> [Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSUseDeclaredVarsMoreThanAssignments','')] [CmdletBinding(SupportsShouldProcess = $true)] Param ( [Parameter(Mandatory = $true, ValueFromPipelineByPropertyName = $true)] [string] $Name, [Parameter(Mandatory = $true, ValueFromPipelineByPropertyName = $true)] [SubnetCategory] $Category, [Parameter(Mandatory = $true, ValueFromPipelineByPropertyName = $true)] [string[]] $Subnets, [Parameter(ValueFromPipelineByPropertyName = $true)] [string] $Organization, [Parameter(ValueFromPipelineByPropertyName = $true)] [Alias('tags')] [string[]] $Tag, [switch] $EnableException ) begin { Assert-RestConnection -Service MDCA -Cmdlet $PSCmdlet } process { $body = @{ name = $Name category = [int]$Category subnets = $Subnets } if ($Organization) { $body.organization = $Organization } if ($Tag) { $body.tags = $Tag } Invoke-PSFProtectedCommand -ActionString 'New-MdcaSubnet.Create' -ActionStringValues $Name -Target $Name -ScriptBlock { $newID = Invoke-RestRequest -Method Post -Path "subnet/create_rule/" -Body $body } -EnableException $EnableException -PSCmdlet $PSCmdlet Get-MdcaSubnet -ID $newID } } function Remove-MdcaSubnet { <# .SYNOPSIS Remove a MDCA subnet .DESCRIPTION Remove a MDCA subnet .PARAMETER ID ID of the subnet to remove .PARAMETER EnableException This parameters disables user-friendly warnings and enables the throwing of exceptions. This is less user friendly, but allows catching exceptions in calling scripts. .PARAMETER WhatIf if this switch is enabled, no actions are performed but informational messages will be displayed that explain what would happen if the command were to run. .PARAMETER Confirm If this switch is enabled, you will be prompted for confirmation before executing any operations that change state. .EXAMPLE PS C:\> Get-MdcaSubnet | Where-Object Name -eq na | Remove-MdcaSubnet Removes the subnet named "na" #> [CmdletBinding(SupportsShouldProcess = $true)] Param ( [Parameter(Mandatory = $true, ValueFromPipeline = $true, ValueFromPipelineByPropertyName = $true)] [Alias('_id')] [string[]] $ID, [switch] $EnableException ) begin { Assert-RestConnection -Service MDCA -Cmdlet $PSCmdlet } process { foreach ($subnetID in $ID) { Invoke-PSFProtectedCommand -ActionString 'Remove-MdcaSubnet.Deleting' -ActionStringValues $subnetID -Target $subnetID -ScriptBlock { $null = Invoke-RestRequest -Method Delete -Path "subnet/$subnetID" -ErrorAction Stop } -EnableException $EnableException -Continue -PSCmdlet $PSCmdlet } } } function Set-MdcaSubnet { <# .SYNOPSIS Updates an existing MDCA subnet. .DESCRIPTION Updates an existing MDCA subnet. All properties will be overwritten each time! Not specifying tags equals to removing all existing tags. Note: Each time you update a subnet you must change its name. .PARAMETER ID ID of the subnet to modify. .PARAMETER Name The name to assign to the subnet. Note: Each time you update a subnet you must change its name. .PARAMETER Category The category the subnet should have. .PARAMETER Subnets The IP ranges assigned to this subnet .PARAMETER Organization The Organization the subnet is part of .PARAMETER Tag Any tags the subnet should include .PARAMETER PassThru Whether the result should be returned as output .PARAMETER EnableException This parameters disables user-friendly warnings and enables the throwing of exceptions. This is less user friendly, but allows catching exceptions in calling scripts. .PARAMETER WhatIf if this switch is enabled, no actions are performed but informational messages will be displayed that explain what would happen if the command were to run. .PARAMETER Confirm If this switch is enabled, you will be prompted for confirmation before executing any operations that change state. .EXAMPLE PS C:\> Get-MdcaSubnet | Where-Object Name -match "^na_{0,1}$" | Set-MdcaSubnet -Subnets '66.66.66.0/24' -Name { ($_.Name + "_") -replace "__" } Updates the subnet na to _only_ include the iprange '66.66.66.0/24'. Alternates the name between "na" and "na_" #> [CmdletBinding(SupportsShouldProcess = $true)] Param ( [Parameter(Mandatory = $true, ValueFromPipelineByPropertyName = $true)] [Alias('_id')] [string] $ID, [Parameter(Mandatory = $true, ValueFromPipelineByPropertyName = $true)] [string] $Name, [Parameter(Mandatory = $true, ValueFromPipelineByPropertyName = $true)] [SubnetCategory] $Category, [Parameter(Mandatory = $true, ValueFromPipelineByPropertyName = $true)] [string[]] $Subnets, [Parameter(ValueFromPipelineByPropertyName = $true)] [string] $Organization, [Parameter(ValueFromPipelineByPropertyName = $true)] [Alias('tags')] [string[]] $Tag, [switch] $PassThru, [switch] $EnableException ) begin { Assert-RestConnection -Service MDCA -Cmdlet $PSCmdlet } process { try { $subnet = Get-MdcaSubnet -ID $ID -ErrorAction Stop } catch { Stop-PSFFunction -String 'Set-MdcaSubnet.NotFound' -StringValues $ID -EnableException $EnableException return } if ($subnet.name -eq $Name) { Stop-PSFFunction -String 'Set-MdcaSubnet.DuplicateName' -StringValues $ID, $Name, $subnet.name -EnableException $EnableException return } $body = @{ name = $Name category = [int]$Category subnets = $Subnets } if ($Organization) { $body.organization = $Organization } if ($Tag) { $body.tags = $Tag } Invoke-PSFProtectedCommand -ActionString 'Set-MdcaSubnet.Modify' -ActionStringValues $subnet.name, $Name -Target $ID -ScriptBlock { $null = Invoke-RestRequest -Method Post -Path "subnet/$ID/update_rule/" -Body $body } -EnableException $EnableException -PSCmdlet $PSCmdlet if ($PassThru) { Get-MdcaSubnet -ID $ID } } } <# This is an example configuration file By default, it is enough to have a single one of them, however if you have enough configuration settings to justify having multiple copies of it, feel totally free to split them into multiple files. #> <# # Example Configuration Set-PSFConfig -Module 'MDCA' -Name 'Example.Setting' -Value 10 -Initialize -Validation 'integer' -Handler { } -Description "Example configuration setting. Your module can then use the setting using 'Get-PSFConfigValue'" #> Set-PSFConfig -Module 'MDCA' -Name 'Import.DoDotSource' -Value $false -Initialize -Validation 'bool' -Description "Whether the module files should be dotsourced on import. By default, the files of this module are read as string value and invoked, which is faster but worse on debugging." Set-PSFConfig -Module 'MDCA' -Name 'Import.IndividualFiles' -Value $false -Initialize -Validation 'bool' -Description "Whether the module files should be imported individually. During the module build, all module code is compiled into few files, which are imported instead by default. Loading the compiled versions is faster, using the individual files is easier for debugging and testing out adjustments." <# Stored scriptblocks are available in [PsfValidateScript()] attributes. This makes it easier to centrally provide the same scriptblock multiple times, without having to maintain it in separate locations. It also prevents lengthy validation scriptblocks from making your parameter block hard to read. Set-PSFScriptblock -Name 'MDCA.ScriptBlockName' -Scriptblock { } #> <# # Example: Register-PSFTeppScriptblock -Name "MDCA.alcohol" -ScriptBlock { 'Beer','Mead','Whiskey','Wine','Vodka','Rum (3y)', 'Rum (5y)', 'Rum (7y)' } #> <# # Example: Register-PSFTeppArgumentCompleter -Command Get-Alcohol -Parameter Type -Name MDCA.alcohol #> New-PSFLicense -Product 'MDCA' -Manufacturer 'Friedrich Weinmann' -ProductVersion $script:ModuleVersion -ProductType Module -Name MIT -Version "1.0.0.0" -Date (Get-Date "2022-05-12") -Text @" Copyright (c) 2022 Friedrich Weinmann Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. "@ $PSDefaultParameterValues['Invoke-RestRequest:Service'] = 'MDCA' #endregion Load compiled code |