msp360.psm1

function Install-MBSAgent {
    <#
    .SYNOPSIS
        Cmdlet installs MBS backup agent on a local machine
    .DESCRIPTION
        Cmdlet installs MBS backup agent on a local machine
    .EXAMPLE
        PS C:\> Install-MBSAgent -URL https://s3.amazonaws.com/cb_setups/MBS/XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXX/CompanyName_vX.X.X.XX.exe
        Install the MBS backup agent.
    .EXAMPLE
        PS C:\> Install-MBSAgent -URL https://s3.amazonaws.com/cb_setups/MBS/XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXX/CompanyName_vX.X.X.XX.exe -Force
        Force to reinstall the MBS backup agent.
    .INPUTS
        None
    .OUTPUTS
        None
    .NOTES
         
    #>

    [CmdletBinding()]
    param (
        #
        [Parameter(Mandatory=$true, HelpMessage="MBS agent URL. Copy the link from MBS portal in Download section.")]
        [String]
        $URL,
        #
        [Parameter(Mandatory=$false, HelpMessage="Force to reinstall the agent")]
        [switch]
        $Force
    )
    
    begin {

    }
    
    process {
        $TempPath = "$env:TMP"
        $TempFolder = "backup"
        if ($Force) {
            $Folder = New-Item -Path "$TempPath" -Name "$TempFolder" -ItemType "directory" -ErrorAction SilentlyContinue
            (New-Object Net.WebClient).DownloadFile("$URL", "$TempPath\$TempFolder\cbl.exe")
            Start-Process -FilePath "$TempPath\$TempFolder\cbl.exe" -ArgumentList "/S" -NoNewWindow -Wait
            Remove-Item -Path "$TempPath\$TempFolder" -Force -Recurse
        }else{
            if (Get-MBSAgent -ErrorAction SilentlyContinue) 
            {
                Write-Host "The backup agent is already installed."
            }else{
                $Folder = New-Item -Path "$TempPath" -Name "$TempFolder" -ItemType "directory"
                (New-Object Net.WebClient).DownloadFile("$URL", "$TempPath\$TempFolder\cbl.exe") 
                Start-Process -FilePath "$TempPath\$TempFolder\cbl.exe" -ArgumentList "/S" -NoNewWindow -Wait
                Remove-Item -Path "$TempPath\$TempFolder" -Force -Recurse
            }
        }
    }
    
    end {

    }
}

function Remove-MBSAgent {
    [CmdletBinding()]
    param (
        
    )
    
    begin {
        
    }
    
    process {
        if (Get-MBSAgent)
        {
            $CBB = Get-MBSAgent
            Start-Process -FilePath $CBB.UninstallString -ArgumentList "/S" -NoNewWindow -Wait
            Write-Host "The backup agent has been uninstalled."
        }else{
            Write-Host "Cannot find backup agent."
        }
    }
    
    end {
        
    }
}

function Get-MBSAgent {
    <#
    .SYNOPSIS
        Get MBS agent parameters (version 0.2.1)
    .DESCRIPTION
        Gets the information about MBS agent settings, paths, etc. The function pulls the registry values of the installed MBS backup agent and parses additional values.
    .EXAMPLE
        Get-MBSAgent
        Lists all of the parameters on the system into an object
    .INPUTS
        None.
    .OUTPUTS
        Properties: UninstallKey, FullPath, CBBPath, CBBName, CBBCLIPath, CBBProgramData, (other registry values from path UninstallKey)
    .NOTES
        The properties from registry path UninstallKey are fetched dynamically. If the software will add new keys, they can be listed by the function.
    #>


    [CmdletBinding()]
    param (
        
    )


    if (((Get-ItemProperty -Path "Registry::HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall\{07BCB989-197A-4E3D-852D-DE8363860401}" -Name "UninstallKey" -ErrorAction SilentlyContinue).'UninstallKey') -eq $null) {
        Write-Error "ERROR: MSP360 Online backup agent is not installed on this machine."
        return $false
    }

    $UninstallKey = (Get-ItemProperty -Path "Registry::HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall\{07BCB989-197A-4E3D-852D-DE8363860401}" -Name "UninstallKey")."UninstallKey"
    $UninstallPath = Get-ItemProperty -Path "Registry::HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall\{07BCB989-197A-4E3D-852D-DE8363860401}"
    $FullPath = (Get-ItemProperty -Path "Registry::HKEY_LOCAL_MACHINE\$UninstallKey" -Name "(default)")."(default)"
    $RegistryEntries = Get-ItemProperty -Path "Registry::HKEY_LOCAL_MACHINE\$UninstallKey"
    $CBBPath = $FullPath.Substring(0, $FullPath.LastIndexOf('\'))
    $CBBName = $FullPath.Substring($CBBPath.Length+1) -replace ".{4}$"
    $CBBCompany = $RegistryEntries.Publisher
    $CBBCLIPath = $CBBPath+"\cbb.exe"

    if (Test-Path -Path "$env:ProgramData\Online Backup\enginesettings.list") {
        $CBBProgramData = "$env:ProgramData\Online Backup"
    }
    elseif (Test-Path -Path "$env:ProgramData\$CBBCompany\enginesettings.list") {
        $CBBProgramData = "$env:ProgramData\$CBBCompany"
    } else {
        Write-Error "ERROR: The folder with backup agent settings not found"
        return $false
    }

    $MBSAgent = New-Object -TypeName psobject
    $MBSAgent | Add-Member -MemberType NoteProperty -Name UninstallKey -Value $UninstallKey
    $UninstallPath | Get-Member -MemberType NoteProperty | ForEach-Object {
        if (($_.Name -ne "UninstallKey") -And ($_.Name -ne "(default)") -And ($_.Name -ne "PSChildName") -And ($_.Name -ne "PSParentPath") -And ($_.Name -ne "PSPath") -And ($_.Name -ne "PSProvider")) {
            $PropertyName = $_.Name
            $MBSAgent | Add-Member -MemberType NoteProperty -Name $PropertyName -Value $UninstallPath.$PropertyName
        }
    }
    $MBSAgent | Add-Member -MemberType NoteProperty -Name FullPath -Value $FullPath
    $RegistryEntries | Get-Member -MemberType NoteProperty | ForEach-Object {
        if (($_.Name -ne "(default)") -And ($_.Name -ne "PSChildName") -And ($_.Name -ne "PSParentPath") -And ($_.Name -ne "PSPath") -And ($_.Name -ne "PSProvider")) {
            $PropertyName = $_.Name
            $MBSAgent | Add-Member -MemberType NoteProperty -Name $PropertyName -Value $RegistryEntries.$PropertyName
        }
    }
    $MBSAgent | Add-Member -MemberType NoteProperty -Name CBBPath -Value $CBBPath
    $MBSAgent | Add-Member -MemberType NoteProperty -Name CBBName -Value $CBBName
    $MBSAgent | Add-Member -MemberType NoteProperty -Name CBBCLIPath -Value $CBBCLIPath
    $MBSAgent | Add-Member -MemberType NoteProperty -Name CBBProgramData -Value $CBBProgramData

    return $MBSAgent
}

function Get-MBSApiUrl {
    <#
    .SYNOPSIS
        The cmdlet returns MBS API URLs object
    .DESCRIPTION
        The cmdlet returns MBS API URLs object
    .EXAMPLE
        PS C:\> Get-MBSApiUrl
        Explanation of what the example does
    .INPUTS
        None
    .OUTPUTS
        System.Management.Automation.PSCustomObject
    .NOTES
         
    #>


    param ($obj)

    $obj = New-Object -TypeName psobject
    $obj | Add-Member -MemberType NoteProperty -Name Users -Value 'https://api.mspbackups.com/api/Users'
    $obj | Add-Member -MemberType NoteProperty -Name UsersAuthenticate -Value 'https://api.mspbackups.com/api/Users/Authenticate'
    $obj | Add-Member -MemberType NoteProperty -Name ProviderLogin -Value 'https://api.mspbackups.com/api/Provider/Login'
    $obj | Add-Member -MemberType NoteProperty -Name Packages -Value 'https://api.mspbackups.com/api/Packages'
    $obj | Add-Member -MemberType NoteProperty -Name Monitoring -Value 'https://api.mspbackups.com/api/Monitoring'
    $obj | Add-Member -MemberType NoteProperty -Name Companies -Value 'https://api.mspbackups.com/api/Companies'
    $obj | Add-Member -MemberType NoteProperty -Name Licenses -Value 'https://api.mspbackups.com/api/Licenses'
    $obj | Add-Member -MemberType NoteProperty -Name Destinations -Value 'https://api.mspbackups.com/api/Destinations'
    $obj | Add-Member -MemberType NoteProperty -Name Accounts -Value 'https://api.mspbackups.com/api/Accounts'
    $obj | Add-Member -MemberType NoteProperty -Name Billing -Value 'https://api.mspbackups.com/api/Billing'
    $obj | Add-Member -MemberType NoteProperty -Name Builds -Value 'https://api.mspbackups.com/api/Builds'
    $obj | Add-Member -MemberType NoteProperty -Name Administrators -Value 'https://api.mspbackups.com/api/Administrators'
    $obj | Add-Member -MemberType NoteProperty -Name ReportIssue -Value 'https://api.mspbackups.com/api/ReportIssue'
    return $obj
}

function Write-HostAndLog {
    param(
    $Message,
    [String]$FilePath,
    [boolean]$showMessage = $true
    )
    if($showMessage){Write-Host "$Message"}
    (Get-Date -Format g) + " $Message" | Out-File -FilePath $FilePath -Append
}

function Import-MBSUsers{
    <#
    .Synopsis
    The cmdlet imports users from CSV file to MBS via API 2.0
    .DESCRIPTION
    The cmdlet imports users from CSV file to MBS via API 2.0
    .PARAMETER APIlogin
    Mandatory parameter. Specify MSB API login name. You can generate new one in General settings https://mspbackups.com/Admin/Settings.aspx
 
    .PARAMETER APIpassword
    Mandatory parameter. Specify MSB API password. You can generate new one in General settings https://mspbackups.com/Admin/Settings.aspx
 
    .PARAMETER LogFilePath
    Optional parameter. Specify log file path. The script uses \api.log by default.
 
    .PARAMETER UserFile
    Optional parameter. Specify user csv file path. The script uses \Users.csv by default.
 
    .EXAMPLE
        .\Import-Users.ps1 -APIlogin VFBB634wKpHQ -APIpassword ggH9ng6ertrB445BPDQQwU3
    .EXAMPLE
        .\Import-Users.ps1 -APIlogin VFBB634wKpHQ -APIpassword ggH9ng6ertrB445BPDQQwU3 -UserFile Users.csv -LogFilePath Mylog.txt
    #>

    [CmdletBinding()]
    param(
        [Parameter(Mandatory=$True)]
        [string]$APIlogin,
        [Parameter(Mandatory=$True)]
        [string]$APIpassword,
        [string]$LogFilePath = "api.log",
        [string]$UserFile = "Users.csv")

    $versionMinimum = [Version]'3.0'

    if ($versionMinimum -le $PSVersionTable.PSVersion)
    { 
        Write-HostAndLog -Message "*********** The script has started ****************" -FilePath $LogFilePath
        
        #Magic
        if (Test-Path $UserFile){
            $UrlUsers = (Get-MBSApiUrl).Users
            $UrlProviderLogin = (Get-MBSApiUrl).ProviderLogin
            $BodyProviderLogin = @{
                UserName = $APIlogin 
                Password = $APIpassword
            }
            $Login = Invoke-RestMethod -Method 'Post' -Uri $UrlProviderLogin -Body $BodyProviderLogin 
            $headers = @{
                'Authorization' = "Bearer " + $Login.access_token
                'Accept' = "application/json"
            }
            Write-HostAndLog -Message ($headers|ConvertTo-Json) -FilePath $LogFilePath -showMessage $false
            $UsersCSV = Import-Csv -Path $UserFile
            $i=0
            $UsersCSV | ForEach-Object{
                Write-Progress -Activity "Adding users to MBS" -Id 1 -PercentComplete (($i/$UsersCSV.Length)*100) -CurrentOperation $_.Email
                Write-HostAndLog -Message ("Adding user "+$_.Email) -FilePath $LogFilePath
                $NotificationEmailsArray = $_.'NotificationEmails' -split ';'
                $UsersPost = @{
                    Email = $_.'Email'.Trim()
                    FirstName =  $_.'FirstName'
                    LastName =  $_.'LastName'
                    NotificationEmails = @($NotificationEmailsArray)
                    Company =  $_.'Company'.Trim()
                    Enabled =  $_.'Enabled'
                    Password =  $_.'Password'
                    SendEmailInstruction =  $_.'SendEmailInstruction'
                }
                Write-HostAndLog -Message ($UsersPost|ConvertTo-Json) -FilePath $LogFilePath -showMessage $false
                $UsersResponse = Invoke-RestMethod -Uri $UrlUsers -Method POST -Headers $headers -Body ($UsersPost|ConvertTo-Json) -ContentType 'application/json'
                Write-HostAndLog -Message ("Response: "+$UsersResponse) -FilePath $LogFilePath
                $i++
            }
        }else{
            Write-HostAndLog -Message "Cannot find file $UserFile" -FilePath $LogFilePath
        }
        
        Write-HostAndLog -Message "*********** The script has finished ****************" -FilePath $LogFilePath
    }else{
        "This script requires PowerShell $versionMinimum. Update PowerSheel https://docs.microsoft.com/en-us/powershell/scripting/install/installing-windows-powershell?view=powershell-6#upgrading-existing-windows-powershell"
        
    }
}

function Get-MBSStorageAccount {
    <#
    .SYNOPSIS
        Get MBS storage accounts assigned to the MBS agent
    .DESCRIPTION
        Get MBS storage accounts assigned to the MBS agent
    .EXAMPLE
        PS C:\> Get-MBSStorageAccount | ft
        Get all assigned storage accounts
    .EXAMPLE
        PS C:\> Get-MBSStorageAccount -ID 92ad7b17-9e2a-41bb-b0e6-c11d60fe9c63
        Get storage account by ID
    .EXAMPLE
        PS C:\> Get-MBSStorageAccount -Name "Oracle Cloud"
        Get all assigned storage accounts
    .INPUTS
        None
    .OUTPUTS
        System.Management.Automation.PSCustomObject
    .NOTES
         
    #>


    param(
        [Parameter(Mandatory=$false, HelpMessage="Storage account ID")]
        [string]$ID,
        [Parameter(Mandatory=$false, HelpMessage="Storage account Name")]
        [string]$Name
    )

    function Add-AccountContent ($Account) {
        $StorageAccount  = New-Object -TypeName psobject
        $StorageAccount | Add-Member -MemberType NoteProperty -Name DisplayName -Value $Account.DisplayName
        $StorageAccount | Add-Member -MemberType NoteProperty -Name ID -Value $Account.ID
        if ($Account.Type -eq "FileSystemConnection") {
            $StorageAccount | Add-Member -MemberType NoteProperty -Name SGCloudTypeValue -Value "FileSystemConnection"
        }else {
            $StorageAccount | Add-Member -MemberType NoteProperty -Name SGCloudTypeValue -Value $Account.SGCloudTypeValue
        }
        
        $StorageAccount | Add-Member -MemberType NoteProperty -Name Bucket -Value $Account.Bucket
        $StorageAccount | Add-Member -MemberType NoteProperty -Name SGFolderPath -Value $Account.SGFolderPath
        $StorageAccount | Add-Member -MemberType NoteProperty -Name IsRestoreOnly -Value $Account.IsRestoreOnly
        $StorageAccount | Add-Member -MemberType NoteProperty -Name UseSSL -Value $Account.UseSSL
        $StorageAccount | Add-Member -MemberType NoteProperty -Name BackupPath -Value $Account.BackupPath
        $StorageAccount | Add-Member -MemberType NoteProperty -Name SGAccountID -Value $Account.SGAccountID
        return $StorageAccount
    }

    if (Get-MBSAgent) {
        $CBBProgramData = (Get-MBSAgent).CBBProgramData
        $StorageAccountsArray = @()
        $enginesettings = [xml](Get-Content ("$CBBProgramData\enginesettings.list"))
        foreach ($Account in ($enginesettings.EngineSettings.Accounts.BaseConnection)){
            if($ID){
                if($ID -eq $Account.ID){
                    $StorageAccountsArray += Add-AccountContent $Account
                }
            }elseif($Name){
                if($Name -eq $Account.DisplayName){
                    $StorageAccountsArray += Add-AccountContent $Account
                }
            }else{
                $StorageAccountsArray += Add-AccountContent $Account
            }
        }    
        return $StorageAccountsArray
    }
}

function Get-MBSBackupPlan {
    <#
    .SYNOPSIS
        Get backup plans from MBS backup agent.
    .EXAMPLE
        PS C:\> Get-MBSBackupPlan -StorageType All -PlanType All
        Lists all backup plans
    .EXAMPLE
        PS C:\> Get-MBSBackupPlan -StorageType Local -PlanType All
        Lists only backup plans with a local destination.
    .EXAMPLE
        PS C:\> Get-MBSBackupPlan -StorageType Cloud -PlanType All
        Lists only backup plans with a cloud destination.
    .EXAMPLE
        PS C:\> Get-MBSBackupPlan -StorageType All -PlanType File-Level
        Lists all File-level backup plans.
    .EXAMPLE
        PS C:\> Get-MBSBackupPlan -StorageType All -PlanType Image-Based
        Lists all Image-Based backup plans.
    .EXAMPLE
        PS C:\> Get-MBSBackupPlan -StorageType Local -PlanType Image-Based
        Lists Image-Based backup plans with a local destination.
    .INPUTS
        None
    .OUTPUTS
        System.Management.Automation.PSCustomObject
    .NOTES
         
    #>

    [CmdletBinding()]
    param (
        #
        [Parameter(Mandatory=$false, HelpMessage="Backup destination storage type.")]
        [ValidateSet("All", "Local", "Cloud", "Hybrid")]
        [string]
        $StorageType = "All",
        #
        [Parameter(Mandatory=$false, HelpMessage="Backup plan type.")]
        [ValidateSet("All", "File-Level", "Image-Based", "MSSQL","MSExchange","VMware","Hyper-V")]
        [string]
        $PlanType = "All"
    )

    function Add-BackupPlanContent ($BasePlan) {
        $BackupPlans  = New-Object -TypeName psobject
        $BackupPlans | Add-Member -MemberType NoteProperty -Name Name -Value $BasePlan.Name
        $BackupPlans | Add-Member -MemberType NoteProperty -Name ID -Value $BasePlan.ID
        $BackupPlans | Add-Member -MemberType NoteProperty -Name Type -Value $BasePlan.Type
        $BackupPlans | Add-Member -MemberType NoteProperty -Name Bucket -Value $BasePlan.Bucket
        
        $Items  = @()
        $ExcludedItems  = @()
        if ($BackupPlan.BasePlan.type -eq "Plan") {
            $element = $BasePlan.SelectSingleNode("//Items")
            $element.PlanItem | ForEach-Object{
                $Items  += $_.Path
            }
            
            $element = $BasePlan.SelectSingleNode("//ExcludedItems")
            $element.PlanItem | ForEach-Object{
                $ExcludedItems  += $_.Path
            }
        }
        $BackupPlans | Add-Member -MemberType NoteProperty -Name Items -Value $Items
        $BackupPlans | Add-Member -MemberType NoteProperty -Name ExcludedItems -Value $ExcludedItems
        
        $Disks  = @()
        if ($BackupPlan.BasePlan.type -eq "BackupDiskImagePlan") {
            $element = $BasePlan.SelectSingleNode("//DiskInfo")
            $element.DiskInfoCommunication | ForEach-Object{
                $Disk  = New-Object -TypeName psobject
                $Disk | Add-Member -MemberType NoteProperty -Name Enabled -Value $_.Enabled
                $Disk | Add-Member -MemberType NoteProperty -Name DiskNumber -Value $_.DiskNumber
                $Disk | Add-Member -MemberType NoteProperty -Name DiskId -Value $_.DiskId
                $Disk | Add-Member -MemberType NoteProperty -Name Capacity -Value $_.Capacity
                $Disk | Add-Member -MemberType NoteProperty -Name DriveType -Value $_.DriveType
                $Disk | Add-Member -MemberType NoteProperty -Name Model -Value $_.Model
                $Disk | Add-Member -MemberType NoteProperty -Name PartitionTableType -Value $_.PartitionTableType
                $Volumes  = @()
                $_.Volumes.VolumeInfoCommunication | ForEach-Object {
                    $Volume  = New-Object -TypeName psobject
                    $Volume | Add-Member -MemberType NoteProperty -Name Enabled -Value $_.Enabled
                    $Volume | Add-Member -MemberType NoteProperty -Name Supported -Value $_.Supported
                    $Volume | Add-Member -MemberType NoteProperty -Name Dynamic -Value $_.Dynamic
                    $Volume | Add-Member -MemberType NoteProperty -Name Identity -Value $_.Identity
                    $Volume | Add-Member -MemberType NoteProperty -Name DiskId -Value $_.DiskId
                    $Volume | Add-Member -MemberType NoteProperty -Name WindowsVolumeIdentity -Value $_.WindowsVolumeIdentity
                    $Volume | Add-Member -MemberType NoteProperty -Name FileSystemType -Value $_.FileSystemType
                    $Volume | Add-Member -MemberType NoteProperty -Name Label -Value $_.Label
                    $Volume | Add-Member -MemberType NoteProperty -Name DriveType -Value $_.DriveType
                    $Volume | Add-Member -MemberType NoteProperty -Name UsedSpace -Value $_.UsedSpace
                    $Volume | Add-Member -MemberType NoteProperty -Name RequiredBySystem -Value $_.RequiredBySystem
                    $Volume | Add-Member -MemberType NoteProperty -Name IsBoot -Value $_.IsBoot
                    $Volume | Add-Member -MemberType NoteProperty -Name IsBitLocker -Value $_.IsBitLocker
                    $Volumes  += $Volume
                }
                $Disk | Add-Member -MemberType NoteProperty -Name Volumes -Value $Volumes
                $Disks  += $Disk
            }
        }
        $BackupPlans | Add-Member -MemberType NoteProperty -Name Disks -Value $Disks
        return $BackupPlans
    }

    function Compare-StorageTypes {
        param (
            $Account,
            [string]$StorageType
        )

        $result = $false
        switch -exact ($StorageType) {
            "All" {$result = $true}
            "Cloud" { 
                if($Account.SGCloudTypeValue -ne "FileSystemConnection" -and $Account.SGCloudTypeValue -ne "PhysicalFile" -and $BackupPlan.BasePlan.HybridID -eq "00000000-0000-0000-0000-000000000000"){
                    $result = $true 
                }else {
                    $result = $false
                }
            }
            "Local" {
                if($Account.SGCloudTypeValue -eq "FileSystemConnection" -or $Account.SGCloudTypeValue -eq "PhysicalFile"){
                    $result = $true 
                }else {
                    $result = $false
                }
            }
            "Hybrid" {
                if ($BackupPlan.BasePlan.HybridID -ne "00000000-0000-0000-0000-000000000000") {
                    $result = $true 
                }else {
                    $result = $false
                }
            }
            Default {}
        }
        return $result
    }

    if (Get-MBSAgent) {
        Write-Verbose -Message "Arguments: -StorageType $StorageType -PlanType $PlanType"
        $CBBProgramData = (Get-MBSAgent).CBBProgramData

        $BackupPlansArray = @()

        foreach ($_ in (Get-ChildItem ("$CBBProgramData") -Filter "*.cbb" -ErrorAction SilentlyContinue)){ 
            if (Get-Content $_.FullName){
                $BackupPlan = [xml](Get-Content ($_.FullName))
                switch ($PlanType) {
                    All 
                    { 
                        if ($BackupPlan.BasePlan.type -notlike "*Restore*" -and $BackupPlan.BasePlan.type -ne "ConsistencyCheckPlan"){
                            if(Compare-StorageTypes -Account (Get-MBSStorageAccount -ID $BackupPlan.BasePlan.ConnectionID) -StorageType $StorageType){
                                $BackupPlansArray += Add-BackupPlanContent ($BackupPlan.BasePlan)
                            }
                        }
                    }
                    File-Level 
                    { 
                        if ($BackupPlan.BasePlan.type -eq "Plan"){
                            if(Compare-StorageTypes -Account (Get-MBSStorageAccount -ID $BackupPlan.BasePlan.ConnectionID) -StorageType $StorageType){
                                $BackupPlansArray += Add-BackupPlanContent ($BackupPlan.BasePlan)
                            }
                        }
                    }
                    Image-Based 
                    {
                        if ($BackupPlan.BasePlan.type -eq "BackupDiskImagePlan") {
                            if(Compare-StorageTypes -Account (Get-MBSStorageAccount -ID $BackupPlan.BasePlan.ConnectionID) -StorageType $StorageType){
                                $BackupPlansArray += Add-BackupPlanContent ($BackupPlan.BasePlan)
                            }
                        }
                    }
                    MSSQL 
                    {
                        if ($BackupPlan.BasePlan.type -eq "BackupDatabasePlan") {
                            if(Compare-StorageTypes -Account (Get-MBSStorageAccount -ID $BackupPlan.BasePlan.ConnectionID) -StorageType $StorageType){
                                $BackupPlansArray += Add-BackupPlanContent ($BackupPlan.BasePlan)
                            }
                        }
                    }
                    MSExchange 
                    {
                        if ($BackupPlan.BasePlan.type -eq "BackupExchangePlan") {
                            if(Compare-StorageTypes -Account (Get-MBSStorageAccount -ID $BackupPlan.BasePlan.ConnectionID) -StorageType $StorageType){
                                $BackupPlansArray += Add-BackupPlanContent ($BackupPlan.BasePlan)
                            }
                        }
                    }
                    VMware 
                    {
                        if ($BackupPlan.BasePlan.type -eq "BackupVirtualMachinesESXiPlan") {
                            if(Compare-StorageTypes -Account (Get-MBSStorageAccount -ID $BackupPlan.BasePlan.ConnectionID) -StorageType $StorageType){
                                $BackupPlansArray += Add-BackupPlanContent ($BackupPlan.BasePlan)
                            }
                        }
                    }
                    Hyper-V 
                    {
                        if ($BackupPlan.BasePlan.type -eq "BackupVirtualMachinesHyperVPlan") {
                            if(Compare-StorageTypes -Account (Get-MBSStorageAccount -ID $BackupPlan.BasePlan.ConnectionID) -StorageType $StorageType){
                                $BackupPlansArray += Add-BackupPlanContent ($BackupPlan.BasePlan)
                            }
                        }
                    }
                    Default {Write-Error -message "Incorrect PlanType parameter"}
                }
            }
        }
        return $BackupPlansArray
    }
}

function Get-MBSRestorePlan {
    <#
    .SYNOPSIS
        Get restore plans from MBS backup agent.
    .EXAMPLE
        PS C:\> Get-MBSRestorePlan -StorageType All -PlanType All
        Lists all restore plans
    .EXAMPLE
        PS C:\> Get-MBSRestorePlan -StorageType Local -PlanType All
        Lists only restore plans with a local destination.
    .EXAMPLE
        PS C:\> Get-MBSRestorePlan -StorageType Cloud -PlanType All
        Lists only restore plans with a cloud destination.
    .EXAMPLE
        PS C:\> Get-MBSRestorePlan -StorageType All -PlanType File-Level
        Lists all File-level restore plans.
    .EXAMPLE
        PS C:\> Get-MBSRestorePlan -StorageType All -PlanType Image-Based
        Lists all Image-Based restore plans.
    .EXAMPLE
        PS C:\> Get-MBSRestorePlan -StorageType Local -PlanType Image-Based
        Lists Image-Based restore plans with a local destination.
    .INPUTS
        None
    .OUTPUTS
        System.Management.Automation.PSCustomObject
    .NOTES
         
    #>

    [CmdletBinding()]
    param (
        #
        [Parameter(Mandatory=$false, HelpMessage="Destination storage type.")]
        [ValidateSet("All", "Local", "Cloud")]
        [string]
        $StorageType = "All",
        #
        [Parameter(Mandatory=$false, HelpMessage="Restore plan type.")]
        [ValidateSet("All", "File-Level", "Image-Based", "MSSQL","MSExchange","VMware","Hyper-V")]
        [string]
        $PlanType = "All"
    )

    function Add-PlanContent ($BasePlan) {
        $Plans  = New-Object -TypeName psobject
        $Plans | Add-Member -MemberType NoteProperty -Name Name -Value $BasePlan.Name
        $Plans | Add-Member -MemberType NoteProperty -Name ID -Value $BasePlan.ID
        $Plans | Add-Member -MemberType NoteProperty -Name Type -Value $BasePlan.Type
        $Plans | Add-Member -MemberType NoteProperty -Name Bucket -Value $BasePlan.Bucket
        return $Plans
    }

    function Compare-StorageTypes {
        param (
            $Account,
            [string]$StorageType
        )

        $result = $false
        switch -exact ($StorageType) {
            "All" {$result = $true}
            "Cloud" { 
                if($Account.SGCloudTypeValue -ne "FileSystemConnection" -and $Account.SGCloudTypeValue -ne "PhysicalFile"){
                    $result = $true 
                }else {
                    $result = $false
                }
            }
            "Local" {
                if($Account.SGCloudTypeValue -eq "FileSystemConnection" -or $Account.SGCloudTypeValue -eq "PhysicalFile"){
                    $result = $true 
                }else {
                    $result = $false
                }
            }
            Default {}
        }
        return $result
    }

    if (Get-MBSAgent) {
        $CBBProgramData = (Get-MBSAgent).CBBProgramData

        $PlansArray = @()

        foreach ($_ in (Get-ChildItem ("$CBBProgramData") -Filter "*.cbb" -ErrorAction SilentlyContinue)){ 
            if (Get-Content $_.FullName){
                $Plan = [xml](Get-Content ($_.FullName))
                switch ($PlanType) {
                    All 
                    { 
                        if ($Plan.BasePlan.type -notlike "Backup*" -and $Plan.BasePlan.type -ne "ConsistencyCheckPlan" -and $Plan.BasePlan.type -ne "Plan"){
                            if(Compare-StorageTypes -Account (Get-MBSStorageAccount -ID $Plan.BasePlan.ConnectionID) -StorageType $StorageType){
                                $PlansArray += Add-PlanContent ($Plan.BasePlan)
                            }
                        }
                    }
                    File-Level 
                    { 
                        if ($Plan.BasePlan.type -eq "RestorePlan"){
                            if(Compare-StorageTypes -Account (Get-MBSStorageAccount -ID $Plan.BasePlan.ConnectionID) -StorageType $StorageType){
                                $PlansArray += Add-PlanContent ($Plan.BasePlan)
                            }
                        }
                    }
                    Image-Based 
                    {
                        if ($Plan.BasePlan.type -eq "RestoreDiskImagePlan") {
                            if(Compare-StorageTypes -Account (Get-MBSStorageAccount -ID $Plan.BasePlan.ConnectionID) -StorageType $StorageType){
                                $PlansArray += Add-PlanContent ($Plan.BasePlan)
                            }
                        }
                    }
                    MSSQL 
                    {
                        if ($Plan.BasePlan.type -eq "RestoreDatabasePlan") {
                            if(Compare-StorageTypes -Account (Get-MBSStorageAccount -ID $Plan.BasePlan.ConnectionID) -StorageType $StorageType){
                                $PlansArray += Add-PlanContent ($Plan.BasePlan)
                            }
                        }
                    }
                    MSExchange 
                    {
                        if ($Plan.BasePlan.type -eq "RestoreExchangePlan") {
                            if(Compare-StorageTypes -Account (Get-MBSStorageAccount -ID $Plan.BasePlan.ConnectionID) -StorageType $StorageType){
                                $PlansArray += Add-PlanContent ($Plan.BasePlan)
                            }
                        }
                    }
                    VMware 
                    {
                        if ($Plan.BasePlan.type -eq "RestoreVirtualMachinesESXiPlan") {
                            if(Compare-StorageTypes -Account (Get-MBSStorageAccount -ID $Plan.BasePlan.ConnectionID) -StorageType $StorageType){
                                $PlansArray += Add-PlanContent ($Plan.BasePlan)
                            }
                        }
                    }
                    Hyper-V 
                    {
                        if ($Plan.BasePlan.type -eq "RestoreVirtualMachinesHyperVPlan") {
                            if(Compare-StorageTypes -Account (Get-MBSStorageAccount -ID $Plan.BasePlan.ConnectionID) -StorageType $StorageType){
                                $PlansArray += Add-PlanContent ($Plan.BasePlan)
                            }
                        }
                    }
                    Default {Write-Error -message "Incorrect PlanType parameter"}
                }
            }
        }
        return $PlansArray
    }
}

function Get-MBSConsistencyCheckPlan {
    <#
    .SYNOPSIS
        Lists consistency check plans.
    .DESCRIPTION
        Lists consistency check plans.
    .EXAMPLE
        PS C:\> Get-MBSConsistencyCheckPlan -StorageType All
        List all consistency checks
    .EXAMPLE
        PS C:\> Get-MBSConsistencyCheckPlan -StorageType Local
        List only consistency checks for local storages
    .EXAMPLE
        PS C:\> Get-MBSConsistencyCheckPlan -StorageType Cloud
        List only consistency checks for cloud storages
    .INPUTS
        None
    .OUTPUTS
        System.Management.Automation.PSCustomObject
    .NOTES
         
    #>

    [CmdletBinding()]
    param (
        #
        [Parameter(Mandatory=$false)]
        [ValidateSet("All", "Local", "Cloud")]
        [string]
        $StorageType = "All"
    )
    
    
    function Add-PlanContent ($BasePlan) {
        $Plans  = New-Object -TypeName psobject
        $Plans | Add-Member -MemberType NoteProperty -Name Name -Value $BasePlan.Name
        $Plans | Add-Member -MemberType NoteProperty -Name ID -Value $BasePlan.ID
        $Plans | Add-Member -MemberType NoteProperty -Name Type -Value $BasePlan.Type
        $Plans | Add-Member -MemberType NoteProperty -Name Bucket -Value $BasePlan.Bucket
        $Schedule  = New-Object -TypeName psobject
        $Schedule | Add-Member -MemberType NoteProperty -Name Enabled -Value $BasePlan.Schedule.Enabled
        $Schedule | Add-Member -MemberType NoteProperty -Name RecurType -Value $BasePlan.Schedule.RecurType
        $Schedule | Add-Member -MemberType NoteProperty -Name RepeatEvery -Value $BasePlan.Schedule.RepeatEvery
        $Schedule | Add-Member -MemberType NoteProperty -Name OnceDate -Value $BasePlan.Schedule.OnceDate
        $Schedule | Add-Member -MemberType NoteProperty -Name DailyRecurrence -Value $BasePlan.Schedule.DailyRecurrence
        $Schedule | Add-Member -MemberType NoteProperty -Name DailyRecurrencePeriod -Value $BasePlan.Schedule.DailyRecurrencePeriod
        $Schedule | Add-Member -MemberType NoteProperty -Name DailyFromHour -Value $BasePlan.Schedule.DailyFromHour
        $Schedule | Add-Member -MemberType NoteProperty -Name DailyFromMinutes -Value $BasePlan.Schedule.DailyFromMinutes
        $Schedule | Add-Member -MemberType NoteProperty -Name DailyTillHour -Value $BasePlan.Schedule.DailyTillHour
        $Schedule | Add-Member -MemberType NoteProperty -Name DailyTillMinutes -Value $BasePlan.Schedule.DailyTillMinutes
        $Schedule | Add-Member -MemberType NoteProperty -Name Hour -Value $BasePlan.Schedule.Hour
        $Schedule | Add-Member -MemberType NoteProperty -Name Minutes -Value $BasePlan.Schedule.Minutes
        $Schedule | Add-Member -MemberType NoteProperty -Name Seconds -Value $BasePlan.Schedule.Seconds
        $Schedule | Add-Member -MemberType NoteProperty -Name WeekDays -Value $BasePlan.Schedule.WeekDays
        $Schedule | Add-Member -MemberType NoteProperty -Name DayOfWeek -Value $BasePlan.Schedule.DayOfWeek
        $Schedule | Add-Member -MemberType NoteProperty -Name WeekNumber -Value $BasePlan.Schedule.WeekNumber
        $Schedule | Add-Member -MemberType NoteProperty -Name DayOfMonth -Value $BasePlan.Schedule.DayOfMonth
        $Schedule | Add-Member -MemberType NoteProperty -Name StopAfterTicks -Value $BasePlan.Schedule.StopAfterTicks
      
        #$obj = ($BasePlan.SelectNodes("Schedule/*") | Select-Object -Expand Name)
        ##$obj = $obj.split()
        #$obj -split ' '| get-member
        #ForEach-Object -InputObject ($obj -split ' ') -Process {
        # #$objname = "Schedule/"+$_.'#text'
        # $_
        # $Schedule | Add-Member -MemberType NoteProperty -Name $_ -Value 'test'
        #}
        #$Schedule | Add-Member -MemberType NoteProperty -Name Enabled -Value $BasePlan.Schedule.Enabled
        #$BasePlan.SelectNodes("Schedule/*") | Select-Object -Expand Name, '#text'
        $Plans | Add-Member -MemberType NoteProperty -Name Schedule -Value $Schedule
        return $Plans
    }

    function Compare-StorageTypes {
        param (
            $Account,
            [string]$StorageType
        )

        $result = $false
        switch -exact ($StorageType) {
            "All" {$result = $true}
            "Cloud" { 
                if($Account.SGCloudTypeValue -ne "FileSystemConnection" -and $Account.SGCloudTypeValue -ne "PhysicalFile"){
                    $result = $true 
                }else {
                    $result = $false
                }
            }
            "Local" {
                if($Account.SGCloudTypeValue -eq "FileSystemConnection" -or $Account.SGCloudTypeValue -eq "PhysicalFile"){
                    $result = $true 
                }else {
                    $result = $false
                }
            }
            Default {}
        }
        return $result
    }

    if (Get-MBSAgent) {
        $CBBProgramData = (Get-MBSAgent).CBBProgramData
        $PlansArray = @()

        foreach ($_ in (Get-ChildItem ("$CBBProgramData") -Filter "*.cbb" -ErrorAction SilentlyContinue)){ 
            if (Get-Content $_.FullName){
                $Plan = [xml](Get-Content ($_.FullName))
                if ($Plan.BasePlan.type -eq "ConsistencyCheckPlan"){
                    if(Compare-StorageTypes -Account (Get-MBSStorageAccount -ID $Plan.BasePlan.ConnectionID) -StorageType $StorageType){
                        $PlansArray += Add-PlanContent ($Plan.BasePlan)
                    }
                }
            }
        }
        return $PlansArray
    }
}

function Edit-MBSBackupPlan {
    <#
    .SYNOPSIS
        Edit MBS backup plan.
    .DESCRIPTION
        Edit MBS suported backup plan. File-Level and Image-Based backup plan type are supported.
    .EXAMPLE
        PS C:\> Get-MBSBackupPlan | Edit-MBSBackupPlan -CommonParameterSet -Compression $true
        Enable compression option for all supported backup plans.
    .EXAMPLE
        PS C:\> Get-MBSBackupPlan -PlanType File-Level | Edit-MBSBackupPlan -FileLevelParameterSet -ntfs $true
        Enable backup NTFS permissions option for all file-level backup plans.
    .EXAMPLE
        PS C:\> Get-MBSBackupPlan -PlanType Image-Based | Edit-MBSBackupPlan -ImageBasedParameterSet -BackupVolumes SystemRequired
        Add the only system required volumes to all image-based backup plans.
    .EXAMPLE
        PS C:\> Get-MBSBackupPlan -StorageType Cloud -PlanType Image-Based | Edit-MBSBackupPlan -ImageBasedParameterSet -BackupVolumes SystemRequired
        Add the only system required volumes to cloud image-based backup plans.
    .INPUTS
        System.String[]
        System.String
    .OUTPUTS
        System.Management.Automation.PSCustomObject
    .NOTES
         
    #>


    [CmdletBinding(DefaultParameterSetName='Common')]
    param (
        #[Parameter(Mandatory=$false,ValueFromPipeline=$true)]
        #[pscustomobject]
        #$BackupPlan,
        #
        [Parameter(Mandatory=$True, HelpMessage="Backup plan settings related to File-Level backup plan type", ParameterSetName='FileLevel')]
        [switch]
        $FileLevelParameterSet,
        #
        [Parameter(Mandatory=$True, HelpMessage="Backup plan settings related to Image-Based backup plan type", ParameterSetName='ImageBased')]
        [switch]
        $ImageBasedParameterSet,
        #
        [Parameter(Mandatory=$True, HelpMessage="Backup plan settings related to any backup plan type. Like Encryption, Compression, Retention policy, Schedule, etc.", ParameterSetName='Common')]
        [switch]
        $CommonParameterSet,
        #
        [Parameter(ValueFromPipelineByPropertyName)]
        [string]
        $ID,
        #
        [Parameter(ValueFromPipelineByPropertyName)]
        [string]
        $Name,
        #
        [Parameter(Mandatory=$False, HelpMessage="Specify to change storage account. Use Get-MBSStorageAccount to list storages", ParameterSetName='ImageBased')]
        [Parameter(Mandatory=$False, HelpMessage="Specify to change storage account. Use Get-MBSStorageAccount to list storages", ParameterSetName='FileLevel')]
        [ValidateSet("ExcludeEncryptedFiles", "ExcludeTempWindowsAppsFolders","AddFixedDrivesToIBB")]
        [string]
        $SpecialFunction,
        #
        [Parameter(Mandatory=$False, HelpMessage="Specify to change storage account. Use Get-MBSStorageAccount to list storages", ParameterSetName='Common')]
        [Parameter(Mandatory=$False, HelpMessage="Specify to change storage account. Use Get-MBSStorageAccount to list storages", ParameterSetName='ImageBased')]
        [Parameter(Mandatory=$False, HelpMessage="Specify to change storage account. Use Get-MBSStorageAccount to list storages", ParameterSetName='FileLevel')]
        [string]
        $StorageAccountID,
        #
        [Parameter(Mandatory=$False, HelpMessage="Specify to rename plan", ParameterSetName='Common')]
        [Parameter(Mandatory=$False, HelpMessage="Specify to rename plan", ParameterSetName='ImageBased')]
        [Parameter(Mandatory=$False, HelpMessage="Specify to rename plan", ParameterSetName='FileLevel')]
        [String]
        $NewName,
        #
        [Parameter(Mandatory=$False, HelpMessage="Specify to disable encryption", ParameterSetName='Common')]
        [Parameter(Mandatory=$False, HelpMessage="Specify to disable encryption", ParameterSetName='ImageBased')]
        [Parameter(Mandatory=$False, HelpMessage="Specify to disable encryption", ParameterSetName='FileLevel')]
        [switch]
        $DisableEncryption,
        #
        [Parameter(Mandatory=$False, HelpMessage="Specify to disable schedule", ParameterSetName='Common')]
        [Parameter(Mandatory=$False, HelpMessage="Specify to disable schedule", ParameterSetName='ImageBased')]
        [Parameter(Mandatory=$False, HelpMessage="Specify to disable schedule", ParameterSetName='FileLevel')]
        [switch]
        $DisableSchedule,
        #
        [Parameter(Mandatory=$False, HelpMessage="Sync before run.", ParameterSetName='Common')]
        [Parameter(Mandatory=$False, HelpMessage="Sync before run.", ParameterSetName='ImageBased')]
        [Parameter(Mandatory=$False, HelpMessage="Sync before run.", ParameterSetName='FileLevel')]
        [Nullable[boolean]]
        $SyncBeforeRun,
        #
        [Parameter(Mandatory=$False, HelpMessage="Use server side encryption (valid only for Amazon S3)", ParameterSetName='Common')]
        [Parameter(Mandatory=$False, HelpMessage="Use server side encryption (valid only for Amazon S3)", ParameterSetName='ImageBased')]
        [Parameter(Mandatory=$False, HelpMessage="Use server side encryption (valid only for Amazon S3)", ParameterSetName='FileLevel')]
        [Nullable[boolean]]
        $ServerSideEncryption,
        #
        [Parameter(Mandatory=$False, HelpMessage="Encryption algorithm. Possible values: AES128-256", ParameterSetName='Common')]
        [Parameter(Mandatory=$False, HelpMessage="Encryption algorithm. Possible values: AES128-256", ParameterSetName='ImageBased')]
        [Parameter(Mandatory=$False, HelpMessage="Encryption algorithm. Possible values: AES128-256", ParameterSetName='FileLevel')]
        [ValidateSet("AES128", "AES192","AES256")]
        [String]
        $EncryptionAlgorithm,
        #
        [Parameter(Mandatory=$False, HelpMessage="Encryption password. Use -EncryptionPassword (ConvertTo-SecureString -string ""Your_Password"" -AsPlainText -Force)", ParameterSetName='Common')]
        [Parameter(Mandatory=$False, HelpMessage="Encryption password. Use -EncryptionPassword (ConvertTo-SecureString -string ""Your_Password"" -AsPlainText -Force)", ParameterSetName='ImageBased')]
        [Parameter(Mandatory=$False, HelpMessage="Encryption password. Use -EncryptionPassword (ConvertTo-SecureString -string ""Your_Password"" -AsPlainText -Force)", ParameterSetName='FileLevel')]
        [SecureString]
        $EncryptionPassword,
        #
        [Parameter(Mandatory=$False, HelpMessage="Compress files", ParameterSetName='Common')]
        [Parameter(Mandatory=$False, HelpMessage="Compress files", ParameterSetName='ImageBased')]
        [Parameter(Mandatory=$False, HelpMessage="Compress files", ParameterSetName='FileLevel')]
        [Nullable[boolean]]
        $Compression,
        #
        [Parameter(Mandatory=$False, HelpMessage="Storage Class (valid only for Amazon S3)", ParameterSetName='Common')]
        [Parameter(Mandatory=$False, HelpMessage="Storage Class (valid only for Amazon S3)", ParameterSetName='ImageBased')]
        [Parameter(Mandatory=$False, HelpMessage="Storage Class (valid only for Amazon S3)", ParameterSetName='FileLevel')]
        [ValidateSet("Standard", "IntelligentTiering", "StandardIA", "OneZoneIA", "Glacier", "GlacierDeepArchive")]
        [String]
        $StorageClass,
        #
        [Parameter(Mandatory=$False, HelpMessage="Save backup plan configuration to the backup storage", ParameterSetName='Common')]
        [Parameter(Mandatory=$False, HelpMessage="Save backup plan configuration to the backup storage", ParameterSetName='ImageBased')]
        [Parameter(Mandatory=$False, HelpMessage="Save backup plan configuration to the backup storage", ParameterSetName='FileLevel')]
        [Nullable[boolean]]
        $SaveBPConfiguration,
        #
        [Parameter(Mandatory=$False, HelpMessage="Output format. Possible values: short, full(default)", ParameterSetName='Common')]
        [Parameter(Mandatory=$False, HelpMessage="Output format. Possible values: short, full(default)", ParameterSetName='ImageBased')]
        [Parameter(Mandatory=$False, HelpMessage="Output format. Possible values: short, full(default)", ParameterSetName='FileLevel')]
        [ValidateSet("short", "full")]
        [String]
        $output,
        #
        [Parameter(Mandatory=$False, HelpMessage="Master password. Should be specified if configuration is protected by master password. Use -MasterPassword (ConvertTo-SecureString -string ""Your_Password"" -AsPlainText -Force)", ParameterSetName='Common')]
        [Parameter(Mandatory=$False, HelpMessage="Master password. Should be specified if configuration is protected by master password. Use -MasterPassword (ConvertTo-SecureString -string ""Your_Password"" -AsPlainText -Force)", ParameterSetName='ImageBased')]
        [Parameter(Mandatory=$False, HelpMessage="Master password. Should be specified if configuration is protected by master password. Use -MasterPassword (ConvertTo-SecureString -string ""Your_Password"" -AsPlainText -Force)", ParameterSetName='FileLevel')]
        [SecureString]
        $MasterPassword,
        # ------------------------- Schedule -----------------------------
        [Parameter(Mandatory=$False, HelpMessage="Specify schedule recurring type", ParameterSetName='Common')]
        [Parameter(Mandatory=$False, HelpMessage="Specify schedule recurring type", ParameterSetName='ImageBased')]
        [Parameter(Mandatory=$False, HelpMessage="Specify schedule recurring type", ParameterSetName='FileLevel')]
        [ValidateSet("day", "week", "month", "dayofmonth", "real-time")]
        [String]
        $RecurringType,
        #
        [Parameter(Mandatory=$False, HelpMessage="Specify datetime or time of schedule. Example -at ""06/09/19 7:43 AM"" , or -at ""7:43 AM"" for every day schedule", ParameterSetName='Common')]
        [Parameter(Mandatory=$False, HelpMessage="Specify datetime or time of schedule. Example -at ""06/09/19 7:43 AM"" , or -at ""7:43 AM"" for every day schedule", ParameterSetName='ImageBased')]
        [Parameter(Mandatory=$False, HelpMessage="Specify datetime or time of schedule. Example -at ""06/09/19 7:43 AM"" , or -at ""7:43 AM"" for every day schedule", ParameterSetName='FileLevel')]
        [String]
        $At,
        #
        [Parameter(Mandatory=$False, HelpMessage="Specify day for 'dayofmonth' schedule (1..31)", ParameterSetName='Common')]
        [Parameter(Mandatory=$False, HelpMessage="Specify day for 'dayofmonth' schedule (1..31)", ParameterSetName='ImageBased')]
        [Parameter(Mandatory=$False, HelpMessage="Specify day for 'dayofmonth' schedule (1..31)", ParameterSetName='FileLevel')]
        [Int32][ValidateRange(0,31)]
        $DayOfMonth,
        #
        [Parameter(Mandatory=$False, HelpMessage="Specify day(s) of week for weekly schedule. Example: ""su, mo, tu, we, th, fr, sa"". Or specify day of week for monthly schedule", ParameterSetName='Common')]
        [Parameter(Mandatory=$False, HelpMessage="Specify day(s) of week for weekly schedule. Example: ""su, mo, tu, we, th, fr, sa"". Or specify day of week for monthly schedule", ParameterSetName='ImageBased')]
        [Parameter(Mandatory=$False, HelpMessage="Specify day(s) of week for weekly schedule. Example: ""su, mo, tu, we, th, fr, sa"". Or specify day of week for monthly schedule", ParameterSetName='FileLevel')]
        [ValidateSet("su", "mo", "tu", "we", "th", "fr", "sa")]
        [string[]]
        $WeekDay,
        #
        [Parameter(Mandatory=$False, HelpMessage="Specify number of week. Possible values: First, Second, Third, Fourth, Penultimate, Last", ParameterSetName='Common')]
        [Parameter(Mandatory=$False, HelpMessage="Specify number of week. Possible values: First, Second, Third, Fourth, Penultimate, Last", ParameterSetName='ImageBased')]
        [Parameter(Mandatory=$False, HelpMessage="Specify number of week. Possible values: First, Second, Third, Fourth, Penultimate, Last", ParameterSetName='FileLevel')]
        [ValidateSet("First", "Second", "Third", "Fourth", "Penultimate", "Last")]
        [string]
        $WeekDumber,
        #
        [Parameter(Mandatory=$False, HelpMessage="Specify daily recurring from value", ParameterSetName='Common')]
        [Parameter(Mandatory=$False, HelpMessage="Specify daily recurring from value", ParameterSetName='ImageBased')]
        [Parameter(Mandatory=$False, HelpMessage="Specify daily recurring from value", ParameterSetName='FileLevel')]
        [string]
        $DailyFrom,
        #
        [Parameter(Mandatory=$False, HelpMessage="Specify daily recurring till value", ParameterSetName='Common')]
        [Parameter(Mandatory=$False, HelpMessage="Specify daily recurring till value", ParameterSetName='ImageBased')]
        [Parameter(Mandatory=$False, HelpMessage="Specify daily recurring till value", ParameterSetName='FileLevel')]
        [string]
        $DailyTill,
        #
        [Parameter(Mandatory=$False, HelpMessage="Specify recurring period type. Possible values: hour, min", ParameterSetName='Common')]
        [Parameter(Mandatory=$False, HelpMessage="Specify recurring period type. Possible values: hour, min", ParameterSetName='ImageBased')]
        [Parameter(Mandatory=$False, HelpMessage="Specify recurring period type. Possible values: hour, min", ParameterSetName='FileLevel')]
        [ValidateSet("hour", "min")]
        [string]
        $Occurs,
        #
        [Parameter(Mandatory=$False, HelpMessage="Specify recurring period value", ParameterSetName='Common')]
        [Parameter(Mandatory=$False, HelpMessage="Specify recurring period value", ParameterSetName='ImageBased')]
        [Parameter(Mandatory=$False, HelpMessage="Specify recurring period value", ParameterSetName='FileLevel')]
        [string]
        $OccursValue,
        #
        [Parameter(Mandatory=$False, HelpMessage="Specify repeat period value. Possible values: 1..31", ParameterSetName='Common')]
        [Parameter(Mandatory=$False, HelpMessage="Specify repeat period value. Possible values: 1..31", ParameterSetName='ImageBased')]
        [Parameter(Mandatory=$False, HelpMessage="Specify repeat period value. Possible values: 1..31", ParameterSetName='FileLevel')]
        [Int32][ValidateRange(0,31)]
        $RepeatEvery,
        #
        [Parameter(Mandatory=$False, HelpMessage="Specify start date of repetitions", ParameterSetName='Common')]
        [Parameter(Mandatory=$False, HelpMessage="Specify start date of repetitions", ParameterSetName='ImageBased')]
        [Parameter(Mandatory=$False, HelpMessage="Specify start date of repetitions", ParameterSetName='FileLevel')]
        [string]
        $repeatStartDate,
        #
        [Parameter(Mandatory=$False, HelpMessage="Specify time in HH:MM to stop the plan if it runs for HH hours MM minutes. Example -stopAfter ""20:30"" or -stopAfter ""100:00"" etc.", ParameterSetName='Common')]
        [Parameter(Mandatory=$False, HelpMessage="Specify time in HH:MM to stop the plan if it runs for HH hours MM minutes. Example -stopAfter ""20:30"" or -stopAfter ""100:00"" etc.", ParameterSetName='ImageBased')]
        [Parameter(Mandatory=$False, HelpMessage="Specify time in HH:MM to stop the plan if it runs for HH hours MM minutes. Example -stopAfter ""20:30"" or -stopAfter ""100:00"" etc.", ParameterSetName='FileLevel')]
        [string]
        $stopAfter,
        # ------------------ Pre / Post actions ----------------------------
        [Parameter(Mandatory=$False, HelpMessage="Specify command to be executed before backup completes.", ParameterSetName='Common')]
        [Parameter(Mandatory=$False, HelpMessage="Specify command to be executed before backup completes.", ParameterSetName='ImageBased')]
        [Parameter(Mandatory=$False, HelpMessage="Specify command to be executed before backup completes.", ParameterSetName='FileLevel')]
        [string]
        $preAction,
        #
        [Parameter(Mandatory=$False, HelpMessage='Specify to continue backup plan if pre-backup action failed. Possible values: $true/$false', ParameterSetName='Common')]
        [Parameter(Mandatory=$False, HelpMessage='Specify to continue backup plan if pre-backup action failed. Possible values: $true/$false', ParameterSetName='ImageBased')]
        [Parameter(Mandatory=$False, HelpMessage='Specify to continue backup plan if pre-backup action failed. Possible values: $true/$false', ParameterSetName='FileLevel')]
        [Nullable[boolean]]
        $pac,
        #
        [Parameter(Mandatory=$False, HelpMessage="Specify command to be executed after backup has been successfully completed.", ParameterSetName='Common')]
        [Parameter(Mandatory=$False, HelpMessage="Specify command to be executed after backup has been successfully completed.", ParameterSetName='ImageBased')]
        [Parameter(Mandatory=$False, HelpMessage="Specify command to be executed after backup has been successfully completed.", ParameterSetName='FileLevel')]
        [string]
        $postAction,
        #
        [Parameter(Mandatory=$False, HelpMessage='Specify to execute post-backup action in any case (regardless the backup result). Possible values: $true/$false', ParameterSetName='Common')]
        [Parameter(Mandatory=$False, HelpMessage='Specify to execute post-backup action in any case (regardless the backup result). Possible values: $true/$false', ParameterSetName='ImageBased')]
        [Parameter(Mandatory=$False, HelpMessage='Specify to execute post-backup action in any case (regardless the backup result). Possible values: $true/$false', ParameterSetName='FileLevel')]
        [Nullable[boolean]]
        $paa,
        #
        [Parameter(Mandatory=$False, HelpMessage="Specify to recieve notification email when backup fails (errorOnly) or in all cases (on). Prior to turn on the notification settings must be configured. Possible values: errorOnly, on, off", ParameterSetName='Common')]
        [Parameter(Mandatory=$False, HelpMessage="Specify to recieve notification email when backup fails (errorOnly) or in all cases (on). Prior to turn on the notification settings must be configured. Possible values: errorOnly, on, off", ParameterSetName='ImageBased')]
        [Parameter(Mandatory=$False, HelpMessage="Specify to recieve notification email when backup fails (errorOnly) or in all cases (on). Prior to turn on the notification settings must be configured. Possible values: errorOnly, on, off", ParameterSetName='FileLevel')]
        [ValidateSet("errorOnly", "on", "off")]
        [string]
        $notification,
        # ---------------------------- Retention Policy -------------------------
        [Parameter(Mandatory=$False, HelpMessage="Specify to add entry to Windows Event Log when backup fails (errorOnly) or in all cases (on). Possible values: errorOnly, on, off", ParameterSetName='Common')]
        [Parameter(Mandatory=$False, HelpMessage="Specify to add entry to Windows Event Log when backup fails (errorOnly) or in all cases (on). Possible values: errorOnly, on, off", ParameterSetName='ImageBased')]
        [Parameter(Mandatory=$False, HelpMessage="Specify to add entry to Windows Event Log when backup fails (errorOnly) or in all cases (on). Possible values: errorOnly, on, off", ParameterSetName='FileLevel')]
        [ValidateSet("errorOnly", "on", "off")]
        [string]
        $winLog,
        #
        [Parameter(Mandatory=$False, HelpMessage="Purge versions that are older than period (except lastest version). Possible values: no, 1d(day), 1w(week), 1m(month)", ParameterSetName='Common')]
        [Parameter(Mandatory=$False, HelpMessage="Purge versions that are older than period (except lastest version). Possible values: no, 1d(day), 1w(week), 1m(month)", ParameterSetName='ImageBased')]
        [Parameter(Mandatory=$False, HelpMessage="Purge versions that are older than period (except lastest version). Possible values: no, 1d(day), 1w(week), 1m(month)", ParameterSetName='FileLevel')]
        [string]
        $purge,
        #
        [Parameter(Mandatory=$False, HelpMessage="Keep limited number of versions. Possible values: all, number", ParameterSetName='Common')]
        [Parameter(Mandatory=$False, HelpMessage="Keep limited number of versions. Possible values: all, number", ParameterSetName='ImageBased')]
        [Parameter(Mandatory=$False, HelpMessage="Keep limited number of versions. Possible values: all, number", ParameterSetName='FileLevel')]
        [string]
        $keep,
        #
        [Parameter(Mandatory=$False, HelpMessage='Always keep the last version. Possible values: $true/$false', ParameterSetName='Common')]
        [Parameter(Mandatory=$False, HelpMessage='Always keep the last version. Possible values: $true/$false', ParameterSetName='ImageBased')]
        [Parameter(Mandatory=$False, HelpMessage='Always keep the last version. Possible values: $true/$false', ParameterSetName='FileLevel')]
        [Nullable[boolean]]
        $keepLastVersion,
        #
        [Parameter(Mandatory=$False, HelpMessage="Specify purge delay. Possible values: no, 1d(day), 1w(week), 1m(month)", ParameterSetName='Common')]
        [Parameter(Mandatory=$False, HelpMessage="Specify purge delay. Possible values: no, 1d(day), 1w(week), 1m(month)", ParameterSetName='ImageBased')]
        [Parameter(Mandatory=$False, HelpMessage="Specify purge delay. Possible values: no, 1d(day), 1w(week), 1m(month)", ParameterSetName='FileLevel')]
        [string]
        $delayPurge,
        #-------------------------Full schedule -----------------------------------
        [Parameter(Mandatory=$False, HelpMessage='Run missed scheduled backup immediately when computer starts up.. Possible values: $true/$false', ParameterSetName='Common')]
        [Parameter(Mandatory=$False, HelpMessage='Run missed scheduled backup immediately when computer starts up.. Possible values: $true/$false', ParameterSetName='ImageBased')]
        [Parameter(Mandatory=$False, HelpMessage='Run missed scheduled backup immediately when computer starts up.. Possible values: $true/$false', ParameterSetName='FileLevel')]
        [Nullable[boolean]]
        $runMissed,
        #
        [Parameter(Mandatory=$False, HelpMessage="Specify force full schedule recurring type. Possible values: day, week, month, dayofmonth, real-time", ParameterSetName='Common')]
        [Parameter(Mandatory=$False, HelpMessage="Specify force full schedule recurring type. Possible values: day, week, month, dayofmonth, real-time", ParameterSetName='ImageBased')]
        [Parameter(Mandatory=$False, HelpMessage="Specify force full schedule recurring type. Possible values: day, week, month, dayofmonth, real-time", ParameterSetName='FileLevel')]
        [ValidateSet("day", "week", "month", "dayofmonth", "real-time")]
        [string]
        $RecurringTypeForceFull,
        #
        [Parameter(Mandatory=$False, HelpMessage="Specify datetime or time of force full schedule. Example -atForceFull ""06/09/19 7:43 AM"" , or -atForceFull ""7:43 AM"" for every day force full schedule", ParameterSetName='Common')]
        [Parameter(Mandatory=$False, HelpMessage="Specify datetime or time of force full schedule. Example -atForceFull ""06/09/19 7:43 AM"" , or -atForceFull ""7:43 AM"" for every day force full schedule", ParameterSetName='ImageBased')]
        [Parameter(Mandatory=$False, HelpMessage="Specify datetime or time of force full schedule. Example -atForceFull ""06/09/19 7:43 AM"" , or -atForceFull ""7:43 AM"" for every day force full schedule", ParameterSetName='FileLevel')]
        [string]
        $atForceFull,
        #
        [Parameter(Mandatory=$False, HelpMessage="Specify day for 'dayofmonth' force full schedule (1..31)", ParameterSetName='Common')]
        [Parameter(Mandatory=$False, HelpMessage="Specify day for 'dayofmonth' force full schedule (1..31)", ParameterSetName='ImageBased')]
        [Parameter(Mandatory=$False, HelpMessage="Specify day for 'dayofmonth' force full schedule (1..31)", ParameterSetName='FileLevel')]
        [Int32][ValidateRange(0,31)]
        $dayForceFull,
        #
        [Parameter(Mandatory=$False, HelpMessage="listOfWeekDays. Specify day(s) of week for weekly force full schedule. Example: ""su, mo, tu, we, th, fr, sa"". Or specify day of week for monthly force full schedule", ParameterSetName='Common')]
        [Parameter(Mandatory=$False, HelpMessage="listOfWeekDays. Specify day(s) of week for weekly force full schedule. Example: ""su, mo, tu, we, th, fr, sa"". Or specify day of week for monthly force full schedule", ParameterSetName='ImageBased')]
        [Parameter(Mandatory=$False, HelpMessage="listOfWeekDays. Specify day(s) of week for weekly force full schedule. Example: ""su, mo, tu, we, th, fr, sa"". Or specify day of week for monthly force full schedule", ParameterSetName='FileLevel')]
        [string]
        $weekdayForceFull,
        #
        [Parameter(Mandatory=$False, HelpMessage="Specify number of week. Possible values: First, Second, Third, Fourth, Penultimate, Last", ParameterSetName='Common')]
        [Parameter(Mandatory=$False, HelpMessage="Specify number of week. Possible values: First, Second, Third, Fourth, Penultimate, Last", ParameterSetName='ImageBased')]
        [Parameter(Mandatory=$False, HelpMessage="Specify number of week. Possible values: First, Second, Third, Fourth, Penultimate, Last", ParameterSetName='FileLevel')]
        [ValidateSet("First", "Second", "Third", "Fourth", "Penultimate", "Last")]
        [string]
        $weeknumberForceFull,
        #
        [Parameter(Mandatory=$False, HelpMessage="Specify daily force full recurring from value", ParameterSetName='Common')]
        [Parameter(Mandatory=$False, HelpMessage="Specify daily force full recurring from value", ParameterSetName='ImageBased')]
        [Parameter(Mandatory=$False, HelpMessage="Specify daily force full recurring from value", ParameterSetName='FileLevel')]
        [string]
        $dailyFromForceFull,
        #
        [Parameter(Mandatory=$False, HelpMessage="Specify daily force full recurring till value", ParameterSetName='Common')]
        [Parameter(Mandatory=$False, HelpMessage="Specify daily force full recurring till value", ParameterSetName='ImageBased')]
        [Parameter(Mandatory=$False, HelpMessage="Specify daily force full recurring till value", ParameterSetName='FileLevel')]
        [string]
        $dailyTillForceFull,
        #
        [Parameter(Mandatory=$False, HelpMessage="Specify force full recurring period type. Possible values: hour, min", ParameterSetName='Common')]
        [Parameter(Mandatory=$False, HelpMessage="Specify force full recurring period type. Possible values: hour, min", ParameterSetName='ImageBased')]
        [Parameter(Mandatory=$False, HelpMessage="Specify force full recurring period type. Possible values: hour, min", ParameterSetName='FileLevel')]
        [ValidateSet("hour", "min")]
        [string]
        $occursForceFull,
        #
        [Parameter(Mandatory=$False, HelpMessage="Specify force full recurring period value", ParameterSetName='Common')]
        [Parameter(Mandatory=$False, HelpMessage="Specify force full recurring period value", ParameterSetName='ImageBased')]
        [Parameter(Mandatory=$False, HelpMessage="Specify force full recurring period value", ParameterSetName='FileLevel')]
        [string]
        $occurValueForceFull,
        #
        [Parameter(Mandatory=$False, HelpMessage="Specify force full repeat period value. Possible values: 1..31", ParameterSetName='Common')]
        [Parameter(Mandatory=$False, HelpMessage="Specify force full repeat period value. Possible values: 1..31", ParameterSetName='ImageBased')]
        [Parameter(Mandatory=$False, HelpMessage="Specify force full repeat period value. Possible values: 1..31", ParameterSetName='FileLevel')]
        [Int32][ValidateRange(0,31)]
        $repeatEveryForceFull,
        #
        [Parameter(Mandatory=$False, HelpMessage="Specify force full start date of repetitions", ParameterSetName='Common')]
        [Parameter(Mandatory=$False, HelpMessage="Specify force full start date of repetitions", ParameterSetName='ImageBased')]
        [Parameter(Mandatory=$False, HelpMessage="Specify force full start date of repetitions", ParameterSetName='FileLevel')]
        [string]
        $repeatStartDateForceFull,
        #
        [Parameter(Mandatory=$False, HelpMessage="Specify force full time in HH:MM to stop the plan if it runs for HH hours MM minutes. Example -stopAfterForceFull ""20:30"" or -stopAfterForceFull ""100:00"" etc.", ParameterSetName='Common')]
        [Parameter(Mandatory=$False, HelpMessage="Specify force full time in HH:MM to stop the plan if it runs for HH hours MM minutes. Example -stopAfterForceFull ""20:30"" or -stopAfterForceFull ""100:00"" etc.", ParameterSetName='ImageBased')]
        [Parameter(Mandatory=$False, HelpMessage="Specify force full time in HH:MM to stop the plan if it runs for HH hours MM minutes. Example -stopAfterForceFull ""20:30"" or -stopAfterForceFull ""100:00"" etc.", ParameterSetName='FileLevel')]
        [string]
        $stopAfterForceFull,
        #
        [Parameter(Mandatory=$False, HelpMessage="Specify rebackup datetime. Example: ""06/09/19 7:43 AM""", ParameterSetName='Common')]
        [Parameter(Mandatory=$False, HelpMessage="Specify rebackup datetime. Example: ""06/09/19 7:43 AM""", ParameterSetName='ImageBased')]
        [Parameter(Mandatory=$False, HelpMessage="Specify rebackup datetime. Example: ""06/09/19 7:43 AM""", ParameterSetName='FileLevel')]
        [string]
        $rebackupDate,
        #
        [Parameter(Mandatory=$False, HelpMessage="Specify to disable schedule force full", ParameterSetName='Common')]
        [Parameter(Mandatory=$False, HelpMessage="Specify to disable schedule force full", ParameterSetName='ImageBased')]
        [Parameter(Mandatory=$False, HelpMessage="Specify to disable schedule force full", ParameterSetName='FileLevel')]
        [switch]
        $DisableForceFullSchedule,
        #---------------------------- Block Level ------------------
        [Parameter(Mandatory=$False, HelpMessage='Use block level backup. Possible values: $true/$false', ParameterSetName='Common')]
        [Parameter(Mandatory=$False, HelpMessage='Use block level backup. Possible values: $true/$false', ParameterSetName='ImageBased')]
        [Parameter(Mandatory=$False, HelpMessage='Use block level backup. Possible values: $true/$false', ParameterSetName='FileLevel')]
        [Nullable[boolean]]
        $useBlockLevelBackup,
        # --------------------------- File Backup settings ------------

        [Parameter(Mandatory=$False, HelpMessage="Backup NTFS permissions", ParameterSetName='FileLevel')]
        [Nullable[boolean]]
        $ntfs,
        #
        [Parameter(Mandatory=$False, HelpMessage='Force using VSS (Volume Shadow Copy Service). Possible values: $true/$false', ParameterSetName='FileLevel')]
        [Nullable[boolean]]
        $ForceUsingVSS,
        #
        [Parameter(Mandatory=$False, HelpMessage='Use share read/write mode on errors. Can help if file is open in share read/write mode. Possible values: $true/$false', ParameterSetName='FileLevel')]
        [Nullable[boolean]]
        $sharerw,
        #
        [Parameter(Mandatory=$False, HelpMessage="Delete files that have been deleted locally after specified number of days. Example: ""-df 30""", ParameterSetName='FileLevel')]
        [string]
        $df,
        #
        [Parameter(Mandatory=$False, HelpMessage='Backup empty folders. Possible values: $true/$false', ParameterSetName='FileLevel')]
        [Nullable[boolean]]
        $BackupEmptyFolders,
        #
        [Parameter(Mandatory=$False, HelpMessage="Backup files only after specific date. Example: ""06/09/19 7:43 AM""", ParameterSetName='FileLevel')]
        [string]
        $oa,
        #
        [Parameter(Mandatory=$False, HelpMessage='Except system and hidden files. Possible values: $true/$false', ParameterSetName='FileLevel')]
        [Nullable[boolean]]
        $es,
        #
        [Parameter(Mandatory=$False, HelpMessage="Skip folders. Example: -skipfolder ""bin;*temp*;My*""", ParameterSetName='FileLevel')]
        [string]
        $SkipFolders,
        #
        [Parameter(Mandatory=$False, HelpMessage="Include files mask. Example: -ifm ""*.doc;*.xls""", ParameterSetName='FileLevel')]
        [string]
        $IncludeFilesMask,
        #
        [Parameter(Mandatory=$False, HelpMessage="Exclude files mask. Example: -efm ""*.bak;*.tmp""", ParameterSetName='FileLevel')]
        [string]
        $ExcludeFilesMask,
        #
        [Parameter(Mandatory=$False, HelpMessage='Ignore errors path not found. Possible values: $true/$false', ParameterSetName='FileLevel')]
        [Nullable[boolean]]
        $iepnf,
        #
        [Parameter(Mandatory=$False, HelpMessage='Track deleted files data. Possible values: $true/$false', ParameterSetName='FileLevel')]
        [Nullable[boolean]]
        $TrackDeletedFiles,
        #
        [Parameter(Mandatory=$False, HelpMessage="Add a new file to backup plan", ParameterSetName='FileLevel')]
        [string]
        $AddNewFile,
        #
        [Parameter(Mandatory=$False, HelpMessage="Add a new directory to backup plan", ParameterSetName='FileLevel')]
        [string]
        $AddNewFolder,
        #
        [Parameter(Mandatory=$False, HelpMessage="Exclude a file from backup plan", ParameterSetName='FileLevel')]
        [string]
        $ExcludeFile,
        #
        [Parameter(Mandatory=$False, HelpMessage="Exclude a directory from backup plan", ParameterSetName='FileLevel')]
        [string]
        $ExcludeDirectory,
        #
        [Parameter(Mandatory=$False, HelpMessage="Backup file", ParameterSetName='FileLevel')]
        [string]
        $BackupFile,
        #
        [Parameter(Mandatory=$False, HelpMessage="Backup directory", ParameterSetName='FileLevel')]
        [string]
        $BackupDirectory,
        #
        [Parameter(Mandatory=$False, HelpMessage='Specify to generate detailed report. Possible values: $true/$false', ParameterSetName='FileLevel')]
        [Nullable[boolean]]
        $GenerateDetailedReport,
        # ------------------------- Image-Based --------------------------------------
        [Parameter(Mandatory=$False, HelpMessage="Backup Volumes type", ParameterSetName='ImageBased')]
        [ValidateSet("AllVolumes", "SystemRequired", "SelectedVolumes")]
        [string]
        $BackupVolumes,
        #
        [Parameter(Mandatory=$False, HelpMessage="Backup selected volume ids only.", ParameterSetName='ImageBased')]
        [string[]]
        $Volumes,
        #
        [Parameter(Mandatory=$False, HelpMessage='Disable VSS, use direct access to NTFS volume. Possible values: $true/$false', ParameterSetName='ImageBased')]
        [Nullable[boolean]]
        $disableVSS,
        #
        [Parameter(Mandatory=$False, HelpMessage='Ignore bad sectors. Possible values: $true/$false', ParameterSetName='ImageBased')]
        [Nullable[boolean]]
        $ignoreBadSectors,
        #
        [Parameter(Mandatory=$False, HelpMessage='Use system VSS provider . Possible values: $true/$false', ParameterSetName='ImageBased')]
        [Nullable[boolean]]
        $useSystemVSS,
        #
        [Parameter(Mandatory=$False, HelpMessage="Prefetch block count (0 - 100, 0 without prefetch)", ParameterSetName='ImageBased')]
        [Int32][ValidateRange(0,100)]
        $prefetchBlockCount,
        #
        [Parameter(Mandatory=$False, HelpMessage="Block size. Possible values: 128, 256, 512, 1024", ParameterSetName='ImageBased')]
        [ValidateSet("128", "256", "512", "1024")]
        [string]
        $blockSize
    )

    
    
    begin {
        $CBB = Get-MBSAgent
    }
    
    process {
        function Set-Arguments {
            if ($StorageAccountID){$Arguments += " -aid $StorageAccountID"}
            if ($NewName){$Arguments += " -nn ""$NewName"""}
            if ($SyncBeforeRun -ne $null){
                if ($SyncBeforeRun) {
                    $Arguments += " -sync yes"
                }else{
                    $Arguments += " -sync no"
                }
            }
            if ($Compression -ne $null){
                if ($Compression) {
                    $Arguments += " -c yes"
                }else{
                    $Arguments += " -c no"
                }
            }
            if ($DisableEncryption){$Arguments += " -ed"}
            if ($DisableSchedule){$Arguments += " -sd"}
            if ($ServerSideEncryption -ne $null){
                if ($ServerSideEncryption) {
                    $Arguments += " -sse yes"
                }else{
                    $Arguments += " -sse no"
                }
            }
            if ($EncryptionAlgorithm){$Arguments += " -ea $EncryptionAlgorithm"}
            if ($EncryptionPassword){$Arguments += " -ep """+([System.Runtime.InteropServices.Marshal]::PtrToStringAuto([System.Runtime.InteropServices.Marshal]::SecureStringToBSTR($EncryptionPassword)))+""""}
            if ($StorageClass){$Arguments += " -sc $StorageClass"}
            if ($SaveBPConfiguration -ne $null){
                if ($SaveBPConfiguration) {
                    $Arguments += " -sp yes"
                }else{
                    $Arguments += " -sp no"
                }
            }
            if ($SaveBPRecurringTypeConfiguration){$Arguments += " -every $RecurringType"}
            if ($At){$Arguments += " -at $At"}
            if ($DayOfMonth){$Arguments += " -day $DayOfMonth"}
            if ($Weekday){$Arguments += " -weekday "+($Weekday -join ",")}
            if ($Weeknumber){$Arguments += " -weeknumber $Weeknumber"}
            if ($DailyFrom){$Arguments += " -dailyFrom $DailyFrom"}
            if ($DailyTill){$Arguments += " -dailyTill $DailyTill"}
            if ($Occurs){$Arguments += " -occurs $Occurs"}
            if ($OccurValue){$Arguments += " -occurValue $OccurValue"}
            if ($repeatStartDate){$Arguments += " -repeatStartDate $repeatStartDate"}
            if ($stopAfter){$Arguments += " -stopAfter $stopAfter"}
            if ($preAction){$Arguments += " -preAction $preAction"}
            if ($pac -ne $null){
                if ($pac) {
                    $Arguments += " -pac yes"
                }else{
                    $Arguments += " -pac no"
                }
            }
            if ($postAction){$Arguments += " -postAction $postAction"}
            if ($paa -ne $null){
                if ($paa) {
                    $Arguments += " -paa yes"
                }else{
                    $Arguments += " -paa no"
                }
            }
            if ($notification){$Arguments += " -notification $notification"}
            if ($winLog){$Arguments += " -winLog $winLog"}
            if ($purge){$Arguments += " -purge $purge"}
            if ($keep){$Arguments += " -keep $keep"}
            if ($keepLastVersion -ne $null){
                if ($keepLastVersion) {
                    $Arguments += " -keepLastVersion yes"
                }else{
                    $Arguments += " -keepLastVersion no"
                }
            }
            if ($delayPurge){$Arguments += " -delayPurge $delayPurge"}
            if ($runMissed -ne $null){
                if ($runMissed) {
                    $Arguments += " -runMissed yes"
                }else{
                    $Arguments += " -runMissed no"
                }
            }
            if ($RecurringTypeForceFull){$Arguments += " -everyForceFull $RecurringTypeForceFull"}
            if ($atForceFull){$Arguments += " -atForceFull $atForceFull"}
            if ($dayForceFull){$Arguments += " -dayForceFull $dayForceFull"}
            if ($weekdayForceFull){$Arguments += " -weekdayForceFull $weekdayForceFull"}
            if ($weeknumberForceFull){$Arguments += " -weeknumberForceFull $weeknumberForceFull"}
            if ($dailyFromForceFull){$Arguments += " -dailyFromForceFull $dailyFromForceFull"}
            if ($dailyTillForceFull){$Arguments += " -dailyTillForceFull $dailyTillForceFull"}
            if ($occursForceFull){$Arguments += " -occursForceFull $occursForceFull"}
            if ($occurValueForceFull){$Arguments += " -occurValueForceFull $occurValueForceFull"}
            if ($repeatEveryForceFull){$Arguments += " -repeatEveryForceFull $repeatEveryForceFull"}
            if ($repeatStartDateForceFull){$Arguments += " -repeatStartDateForceFull $repeatStartDateForceFull"}
            if ($stopAfterForceFull){$Arguments += " -stopAfterForceFull $stopAfterForceFull"}
            if ($rebackupDate){$Arguments += " -rebackupDate $rebackupDate"}
            if ($DisableForceFullSchedule){$Arguments += " -sdForce"}
            if ($useBlockLevelBackup -ne $null){
                if ($useBlockLevelBackup) {
                    $Arguments += " -useBlockLevelBackup yes"
                }else{
                    $Arguments += " -useBlockLevelBackup no"
                }
            }

            # --------- File-Level ------------
            if ($ntfs -ne $null){
                if ($ntfs) {
                    $Arguments += " -ntfs yes"
                }else{
                    $Arguments += " -ntfs no"
                }
            }
            if ($ForceUsingVSS -ne $null){
                if ($ForceUsingVSS) {
                    $Arguments += " -vss yes"
                }else{
                    $Arguments += " -vss no"
                }
            }
            if ($sharerw -ne $null){
                if ($sharerw) {
                    $Arguments += " -sharerw yes"
                }else{
                    $Arguments += " -sharerw no"
                }
            }
            if ($df){$Arguments += " -df $df"}
            if ($BackupEmptyFolders -ne $null){
                if ($BackupEmptyFolders) {
                    $Arguments += " -bef yes"
                }else{
                    $Arguments += " -bef no"
                }
            }
            if ($oa){$Arguments += " -oa $oa"}
            if ($es -ne $null){
                if ($es) {
                    $Arguments += " -es yes"
                }else{
                    $Arguments += " -es no"
                }
            }
            if ($SkipFolders){$Arguments += " -skipf $SkipFolders"}
            if ($IncludeFilesMask){$Arguments += " -ifm $IncludeFilesMask"}
            if ($iepnf -ne $null){
                if ($iepnf) {
                    $Arguments += " -iepnf yes"
                }else{
                    $Arguments += " -iepnf no"
                }
            }
            if ($TrackDeletedFiles -ne $null){
                if ($TrackDeletedFiles) {
                    $Arguments += " -trackdeleted yes"
                }else{
                    $Arguments += " -trackdeleted no"
                }
            }
            if ($AddNewFile){$Arguments += " -af $AddFile"}
            if ($AddNewFolder){$Arguments += " -ad $AddFolder"}
            if ($ExcludeFile){$Arguments += " -rf $ExcludeFile"}
            if ($ExcludeDirectory){$Arguments += " -rd $ExcludeDirectory"}
            if ($BackupFile){$Arguments += " -f $BackupFile"}
            if ($BackupDirectory){$Arguments += " -d $BackupDirectory"}
            if ($GenerateDetailedReport -ne $null){
                if ($GenerateDetailedReport) {
                    $Arguments += " -dr yes"
                }else{
                    $Arguments += " -dr no"
                }
            }
            if ($output){$Arguments += " -output $output"}
            if ($MasterPassword){$Arguments += " -mp """+([System.Runtime.InteropServices.Marshal]::PtrToStringAuto([System.Runtime.InteropServices.Marshal]::SecureStringToBSTR($MasterPassword)))+""""}

            # ------------- Image-Based -------------

            switch ($BackupVolumes) {
                'AllVolumes' {$Arguments += " -av"}
                'SystemRequired' {$Arguments += " -r"}
                'SelectedVolumes' {
                    ForEach-Object -InputObject $Volumes -Process {
                        $Arguments += " -v $_"
                    }
                }
                Default {}
            }

            if ($disableVSS -ne $null){
                if ($disableVSS) {
                    $Arguments += " -disableVSS yes"
                }else{
                    $Arguments += " -disableVSS no"
                }
            }
            if ($ignoreBadSectors -ne $null){
                if ($ignoreBadSectors) {
                    $Arguments += " -ignoreBadSectors yes"
                }else{
                    $Arguments += " -ignoreBadSectors no"
                }
            }
            if ($useSystemVSS -ne $null){
                if ($useSystemVSS) {
                    $Arguments += " -useSystemVSS yes"
                }else{
                    $Arguments += " -useSystemVSS no"
                }
            }
            if ($prefetchBlockCount){$Arguments += " -prefetchBlockCount $prefetchBlockCount"}
            if ($blockSize){$Arguments += " -blockSize $blockSize"}
            
            Return $Arguments
        }

        if ($CBB = Get-MBSAgent){
            if ($SpecialFunction) {
                if ($_){
                    $BackupPlan = $_
                }else{
                    if($ID){
                        $BackupPlan = Get-MBSBackupPlan | Where-Object {$_.ID -eq $ID}
                    }else{
                        $BackupPlan = Get-MBSBackupPlan | Where-Object {$_.Name -eq $Name}
                    }
                }
                
                switch ($SpecialFunction) {
                    "ExcludeEncryptedFiles" {
                        if ($BackupPlan.Type -eq "Plan") {
                            Write-Host "Searching for encrypted files in plan:" $BackupPlan.Name -ForegroundColor Green
                            $Arguments = "editBackupPlan -id "+$ID
                            if ($MasterPassword) {
                                if ($MasterPassword){$Arguments += " -mp """+([System.Runtime.InteropServices.Marshal]::PtrToStringAuto([System.Runtime.InteropServices.Marshal]::SecureStringToBSTR($MasterPassword)))+""""}
                            }
                            $FoundFlag = $false
                            foreach ($Item in $BackupPlan.Items)
                            {
                                
                                foreach ($File in (get-childitem ($Item) -Recurse -Force -ErrorAction SilentlyContinue | Where-Object {$_.Attributes -ge "Encrypted"}))
                                {
                                    Write-Host "File "$File.FullName "is encrypted and added to exclusion list"
                                    $Arguments += " -rf """+$File.FullName+""""
                                    $FoundFlag = $True
                                }
                                
                            }
                            if ($FoundFlag) {
                                Write-Verbose -Message "Arguments: $Arguments"
                                Start-Process -FilePath $CBB.CBBCLIPath -ArgumentList $Arguments -NoNewWindow -Wait
                            }
                        }else{
                            Write-Host "ExcludeEncryptedFiles option supports only File-Level backup plans."
                        }
                    }
                    "ExcludeTempWindowsAppsFolders" {
                        $versionMinimum = [Version]'3.0'
                        if ($versionMinimum -le $PSVersionTable.PSVersion){
                            if ($BackupPlan.Type -eq "Plan") {
                                $Exclusions = '%USERPROFILE%\AppData\Local\Microsoft\WindowsApps', '%USERPROFILE%\AppData\Local\Packages', '%USERPROFILE%\AppData\Local\Temp'
                                $BackupPlanXml = [xml](Get-Content ($CBB.CBBProgramData+"\"+$BackupPlan.ID+".cbb"))
                                Write-Host "Adding exclusions to plan:" $BackupPlan.Name -ForegroundColor Green
                                foreach($exclusion in $Exclusions){
                                    $element = ((($BackupPlanXml.BasePlan.SelectSingleNode("//ExcludedItems")).AppendChild($BackupPlanXml.CreateElement("PlanItem"))).AppendChild($BackupPlanXml.CreateElement("Path"))).AppendChild($BackupPlanXml.CreateTextNode($exclusion))
                                }
                                Import-Configuration -BackupPlanXml $BackupPlanXml -MasterPassword $MasterPassword
                            }else{
                                Write-Host "ExcludeTempWindowsAppsFolders option supports only File-Level backup plans."
                            }else{
                                "This script requires PowerShell $versionMinimum. Update PowerSheel https://docs.microsoft.com/en-us/powershell/scripting/install/installing-windows-powershell?view=powershell-6#upgrading-existing-windows-powershell"
                            }
                        }
                    }
                    "AddFixedDrivesToIBB" {
                        $versionMinimum = [Version]'3.0'
                        if ($versionMinimum -le $PSVersionTable.PSVersion){
                            if ($BackupPlan.Type -eq "BackupDiskImagePlan") {
                                $BackupPlanXml = [xml](Get-Content ($CBB.CBBProgramData+"\"+$BackupPlan.ID+".cbb"))
                                $BackupPlanXml.BasePlan.DiskInfo.DiskInfoCommunication | ForEach-Object {
                                    if ($_.DriveType -eq "Fixed"){
                                        $_.Enabled = "true"
                                        $_.Volumes.VolumeInfoCommunication | ForEach-Object { $_.Enabled = "true"}
                                    }
                                }
                                $BackupPlanXml.BasePlan.DiskInfo.DiskInfoCommunication | ForEach-Object {
                                    if ($_.DriveType -eq "Removable"){
                                        $_.Enabled = "false"
                                        $_.Volumes.VolumeInfoCommunication | ForEach-Object { $_.Enabled = "false"}
                                    }
                                }
                                Import-Configuration -BackupPlanXml $BackupPlanXml -MasterPassword $MasterPassword
                            }else{
                                Write-Host "AddFixedDrivesToIBB option supports only Image-Based backup plans."
                            }
                        }else{
                            "This script requires PowerShell $versionMinimum. Update PowerSheel https://docs.microsoft.com/en-us/powershell/scripting/install/installing-windows-powershell?view=powershell-6#upgrading-existing-windows-powershell"
                        }
                    }
                    Default {}
                }
            }else{

                if($_ -ne $null){
                    if($_.Type -eq "Plan" -and $FileLevelParameterSet){
                        $Arguments = " editBackupPlan"
                    }elseif ($_.Type -eq "BackupDiskImagePlan" -and $ImageBasedParameterSet) {
                        $Arguments = " editBackupIBBPlan"
                    }elseif ($CommonParameterSet) {
                        switch ($_.Type) {
                            'Plan' {$Arguments = " editBackupPlan"}
                            'BackupDiskImagePlan' {$Arguments = " editBackupIBBPlan"}
                            Default {
                                Write-host "$_ type is not supported by the Cmdlet" -ForegroundColor Red
                                return 
                        }

                        }
                    }else{
                        Write-host "Backup plan """($_.Name)""" is skipped" -ForegroundColor Red 
                        return 
                    }
                }else{
                    if ($FileLevelParameterSet) {
                        $Arguments = " editBackupPlan"
                    }elseif ($ImageBasedParameterSet) {
                        $Arguments = " editBackupIBBPlan"
                    }
                }
                
            
                if ($ID){
                    $Arguments += " -id $ID"
                    $Arguments += Set-Arguments # -Arguments $Arguments
                }else{
                    $Arguments += " -n ""$Name"""
                    $Arguments += Set-Arguments #($Arguments)
                }
                Write-Verbose -Message "Arguments: $Arguments"
                Start-Process -FilePath $CBB.CBBCLIPath -ArgumentList $Arguments -NoNewWindow -Wait
            }
        }
    }
    
    end {
    }
}

function Start-MBSBackupPlan {
    <#
    .SYNOPSIS
        Run backup plans.
    .DESCRIPTION
        Run backup plans.
    .EXAMPLE
        PS C:\> Start-MBSBackupPlan -Name "Backup VMware"
        Start backup plan by name.
    .EXAMPLE
        PS C:\> Start-MBSBackupPlan -ID ed2e0d37-5ec2-49e1-a381-d2246b3108ec
        Start backup plan by the plan ID.
    .EXAMPLE
        PS C:\> Get-MBSBackupPlan -StorageType Local -PlanType VMware | Start-MBSBackupPlan
        Start VMware backup plans with local backup storages type.
    .EXAMPLE
        PS C:\> Get-MBSBackupPlan -StorageType All -PlanType VMware | Start-MBSBackupPlan
        Start VMware backup plans with all backup storages type.
    .EXAMPLE
        PS C:\>Start-MBSBackupPlan -ID 3a2fde55-9ecd-4940-a75c-d1499b43abda -ForceFull -ForceFullDayOfWeek Friday, Monday
        Run force full on specific day of the week.
    .INPUTS
        System.String[]
        System.String
    .OUTPUTS
        System.String[]
    #>


    [CmdletBinding()]
    param (
        [Parameter(ValueFromPipelineByPropertyName)]
        [string]
        $ID,
        #
        [Parameter(ValueFromPipelineByPropertyName)]
        [string]
        $Name,
        #
        [switch]
        $ForceFull,
        #
        [ValidateSet("Monday", "Tuesday","Wednesday","Thursday","Friday","Saturday","Sunday")]
        [string[]]
        $ForceFullDayOfWeek,
        #
        [Parameter(Mandatory=$False, HelpMessage="Master password. Should be specified if configuration is protected by master password. Use -MasterPassword (ConvertTo-SecureString -string ""Your_Password"" -AsPlainText -Force)")]
        [SecureString]
        $MasterPassword
    )
    
    begin {
        $CBB = Get-MBSAgent
    }
    
    process {
        if (Get-MBSAgent) {        
            if ($ID){
                $Arguments += "plan -r $ID"
            }else{
                $Arguments += "plan -r ""$Name"""
            }
            
            if($ForceFull){
                if ($ForceFullDayOfWeek){
                    if((get-date).DayOfWeek -in $ForceFullDayOfWeek){
                        $Arguments += " -ForceFull"
                    }
                }else {
                    $Arguments += " -ForceFull"
                }
            }
            if ($MasterPassword){$Arguments += " -mp """+([System.Runtime.InteropServices.Marshal]::PtrToStringAuto([System.Runtime.InteropServices.Marshal]::SecureStringToBSTR($MasterPassword)))+""""}

            Write-Verbose -Message "Arguments: $Arguments"
            Start-Process -FilePath $CBB.CBBCLIPath -ArgumentList $Arguments -NoNewWindow -Wait
        }
    }
    
    end {
    }
}

function Stop-MBSBackupPlan {
    <#
    .SYNOPSIS
        Stop running backup plans.
    .DESCRIPTION
        Stop running backup plans.
    .EXAMPLE
        PS C:\> Stop-MBSBackupPlan -Name "Backup VMware"
        Stop running backup plan by name.
    .EXAMPLE
        PS C:\> Stop-MBSBackupPlan -ID ed2e0d37-5ec2-49e1-a381-d2246b3108ec
        Stop running backup plan by the plan ID.
    .EXAMPLE
        PS C:\> Get-MBSBackupPlan -StorageType Local -PlanType VMware | Stop-MBSBackupPlan
        Stop running VMware backup plans with local backup storages type.
    .EXAMPLE
        PS C:\> Get-MBSBackupPlan -StorageType All -PlanType VMware | Stop-MBSBackupPlan
        Stop running VMware backup plans with all backup storages type.
    .INPUTS
        System.String[]
        System.String
    .OUTPUTS
        System.String[]
    #>

    [CmdletBinding()]
    param (
        [Parameter(ValueFromPipelineByPropertyName)]
        [string]
        $ID,
        #
        [Parameter(ValueFromPipelineByPropertyName)]
        [string]
        $Name,
        #
        [Parameter(Mandatory=$False, HelpMessage="Master password. Should be specified if configuration is protected by master password. Use -MasterPassword (ConvertTo-SecureString -string ""Your_Password"" -AsPlainText -Force)")]
        [SecureString]
        $MasterPassword
    )
    
    begin {
        $CBB = Get-MBSAgent
    }
    
    process {
        if (Get-MBSAgent) {
            if ($ID){
                $Arguments += "plan -s $ID"
            }else{
                $Arguments += "plan -s ""$Name"""
            }
            if ($MasterPassword){$Arguments += " -mp """+([System.Runtime.InteropServices.Marshal]::PtrToStringAuto([System.Runtime.InteropServices.Marshal]::SecureStringToBSTR($MasterPassword)))+""""}

            Write-Verbose -Message "Arguments: $Arguments"
            Start-Process -FilePath $CBB.CBBCLIPath -ArgumentList $Arguments -NoNewWindow -Wait
            Start-Process -FilePath $CBB.CBBCLIPath -ArgumentList $Arguments -NoNewWindow -Wait
        }
    }
    
    end {
    }
}

function Get-MBSAgentSettings {
    [CmdletBinding()]
    param (
        
    )
    
    begin {
        
    }
    
    process {
        if (Get-MBSAgent) {
            $CBBProgramData = (Get-MBSAgent).CBBProgramData
            $StorageAccountsArray = @()
            $enginesettings = [xml](Get-Content ("$CBBProgramData\enginesettings.list"))

            $MBSAgentSettings  = New-Object -TypeName psobject
            $MBSAgentSettings | Add-Member -MemberType NoteProperty -Name MBSUser -Value $enginesettings.EngineSettings.MBSUser
            $MBSAgentSettings | Add-Member -MemberType NoteProperty -Name MBSFolderPath -Value $enginesettings.EngineSettings.MBSFolderPath
            $MBSAgentSettings | Add-Member -MemberType NoteProperty -Name EngineVersion -Value $enginesettings.EngineSettings.EngineVersion
            $MBSAgentSettings | Add-Member -MemberType NoteProperty -Name LogFolder -Value $enginesettings.EngineSettings.LogFolder
            $MBSAgentSettings | Add-Member -MemberType NoteProperty -Name LoggingLevel -Value $enginesettings.EngineSettings.LoggingLevel
            $MBSAgentSettings | Add-Member -MemberType NoteProperty -Name MSSQLAlternativeFolder -Value $enginesettings.EngineSettings.MSSQLAlternativeFolder
            $MBSAgentSettings | Add-Member -MemberType NoteProperty -Name MaximumSimultaneousTransfers -Value $enginesettings.EngineSettings.MaximumSimultaneousTransfers
            $MBSAgentSettings | Add-Member -MemberType NoteProperty -Name Priority -Value $enginesettings.EngineSettings.Priority
            $MBSAgentSettings | Add-Member -MemberType NoteProperty -Name DefaultRetentionNumberOfHistoryRecords -Value $enginesettings.EngineSettings.DefaultRetentionNumberOfHistoryRecords
            $MBSAgentSettings | Add-Member -MemberType NoteProperty -Name PreventSleepMode -Value $enginesettings.EngineSettings.PreventSleepMode
            $MBSAgentSettings | Add-Member -MemberType NoteProperty -Name CheckFileConsistency -Value $enginesettings.EngineSettings.CheckFileConsistency
            $MBSAgentSettings | Add-Member -MemberType NoteProperty -Name RetryAttempts -Value $enginesettings.EngineSettings.RetryAttempts
            $MBSAgentSettings | Add-Member -MemberType NoteProperty -Name RetryInterval -Value $enginesettings.EngineSettings.RetryInterval
            $MBSAgentSettings | Add-Member -MemberType NoteProperty -Name ChunkSizeKB -Value $enginesettings.EngineSettings.ChunkSizeKB
            $MBSAgentSettings | Add-Member -MemberType NoteProperty -Name DisableAutoUpdate -Value $enginesettings.EngineSettings.DisableAutoUpdate
            $MBSAgentSettings | Add-Member -MemberType NoteProperty -Name DefaultRetentionNumberOfVersions -Value $enginesettings.EngineSettings.DefaultRetentionNumberOfVersions
            $MBSAgentSettings | Add-Member -MemberType NoteProperty -Name DefaultRetentionUseBackupDate -Value $enginesettings.EngineSettings.DefaultRetentionUseBackupDate
            $MBSAgentSettings | Add-Member -MemberType NoteProperty -Name DefaultRetentionDeleteLastVersion -Value $enginesettings.EngineSettings.DefaultRetentionDeleteLastVersion
            $MBSAgentSettings | Add-Member -MemberType NoteProperty -Name UseMasterPasswordForCLI -Value $enginesettings.EngineSettings.UseMasterPasswordForCLI


            $Bandwidth  = New-Object -TypeName psobject
            $Bandwidth | Add-Member -MemberType NoteProperty -Name BandwidthLimitEnabled -Value $enginesettings.EngineSettings.Bandwidth.BandwidthLimitEnabled
            $Bandwidth | Add-Member -MemberType NoteProperty -Name BandwidthLimit -Value $enginesettings.EngineSettings.Bandwidth.BandwidthLimit
            $Bandwidth | Add-Member -MemberType NoteProperty -Name BandwidthLocalLimitEnabled -Value $enginesettings.EngineSettings.Bandwidth.BandwidthLocalLimitEnabled
            $Bandwidth | Add-Member -MemberType NoteProperty -Name BandwidthLocalLimit -Value $enginesettings.EngineSettings.Bandwidth.BandwidthLocalLimit
            if($enginesettings.EngineSettings.UseBandwidthSchedule -eq "true"){
                $BandwidthSchedule  = New-Object -TypeName psobject
                $DayOfWeek = @()
                $enginesettings.EngineSettings.BandwidthSchedule.BandwidthSchedule.WeekDays | ForEach-Object {
                    $DayOfWeek += $_.DayOfWeek
                }
                $BandwidthSchedule | Add-Member -MemberType NoteProperty -Name WeekDays -Value $DayOfWeek
                $BandwidthSchedule | Add-Member -MemberType NoteProperty -Name DayStartTime -Value $DayStartTime
                $BandwidthSchedule | Add-Member -MemberType NoteProperty -Name DayFinishTime -Value $DayFinishTime
                $BandwidthSchedule | Add-Member -MemberType NoteProperty -Name BandwidthLimitEnabled -Value $enginesettings.EngineSettings.BandwidthSchedule.BandwidthSchedule.BandwidthLimitEnabled
                $BandwidthSchedule | Add-Member -MemberType NoteProperty -Name BandwidthLimit -Value $enginesettings.EngineSettings.BandwidthSchedule.BandwidthSchedule.BandwidthLimit
                $BandwidthSchedule | Add-Member -MemberType NoteProperty -Name BandwidthLocalLimitEnabled -Value $enginesettings.EngineSettings.BandwidthSchedule.BandwidthSchedule.BandwidthLocalLimitEnabled
                $BandwidthSchedule | Add-Member -MemberType NoteProperty -Name BandwidthLocalLimit -Value $enginesettings.EngineSettings.BandwidthSchedule.BandwidthSchedule.BandwidthLocalLimit
                $MBSAgentSettings | Add-Member -MemberType NoteProperty -Name BandwidthSchedule -Value $BandwidthSchedule
            }
            $MBSAgentSettings | Add-Member -MemberType NoteProperty -Name Bandwidth -Value $Bandwidth
            
            return $MBSAgentSettings
        
        }
    }
    
    end {
        
    }
}

function Set-MBSAgentSettings {
    <#
    .SYNOPSIS
        Change MBS backup agent options.
    .DESCRIPTION
        Change MBS backup agent options.
    .EXAMPLE
        PS C:\> Set-MBSAgentSettings -ThreadCount 10
        Set thread count to 10.
    .EXAMPLE
        PS C:\> Set-MBSAgentSettings -Keep 5 -Logging high
        Change default retention policy to keep 5 versions and set logging level to high.
    .INPUTS
        None
    .OUTPUTS
        System.String[]
    .NOTES
     
    #>

    [CmdletBinding()]
    param (
        #
        [Parameter(Mandatory=$False, HelpMessage="Specify Edition.")]
        [ValidateSet("desktop", "baremetal", "mssql", "msexchange", "mssqlexchange", "ultimate", "vmedition")]
        [String]
        $Edition,
        #
        [Parameter(Mandatory=$False, HelpMessage="Bandwidth for a plan. Possible values: u(unlimited), value in kB")]
        [String]
        $Bandwidth,
        #
        [Parameter(Mandatory=$False, HelpMessage="Proxy type. Possible values: no, auto, manual")]
        [ValidateSet("no", "auto","monual")]
        [String]
        $Proxy,
        #
        [Parameter(Mandatory=$False, HelpMessage="Proxy address")]
        [String]
        $ProxyAddress,
        #
        [Parameter(Mandatory=$False, HelpMessage="Proxy port")]
        [Int32][ValidateRange(1,65535)]
        $ProxyPort,
        #
        [Parameter(Mandatory=$False, HelpMessage="Proxy authentication.")]
        [Nullable[boolean]]
        $ProxyAuthentication,
        #
        [Parameter(Mandatory=$False, HelpMessage="Proxy domain")]
        [String]
        $ProxyDomain,
        #
        [Parameter(Mandatory=$False, HelpMessage="Proxy user")]
        [String]
        $ProxyUser,
        #
        [Parameter(Mandatory=$False, HelpMessage="Proxy password")]
        [String]
        $ProxyPassword,
        #
        [Parameter(Mandatory=$False, HelpMessage="Specify chunk size in KBs. Possible values: 1024-5242880")]
        [Int32][ValidateRange(1024,5242880)]
        $ChunkSize,
        #
        [Parameter(Mandatory=$False, HelpMessage="Thread count. Possible values: 1-99")]
        [Int32][ValidateRange(1,99)]
        $ThreadCount,
        #
        [Parameter(Mandatory=$False, HelpMessage="Purge versions that are older than period (except lastest version). Possible values: no, 1d(day), 1w(week), 1m(month)")]
        [String]
        $Purge,
        #
        [Parameter(Mandatory=$False, HelpMessage="Specify purge delay.. Possible values: no, 1d(day), 1w(week), 1m(month)")]
        [String]
        $DelayPurge,
        #
        [Parameter(Mandatory=$False, HelpMessage="Keep limited number of versions. Possible values: all, number")]
        [String]
        $Keep,
        #
        [Parameter(Mandatory=$False, HelpMessage="Purge history records that are older than value. Possible values: no, 1d(day), 1w(week), 1m(month)")]
        [String]
        $HistoryPurge,
        #
        [Parameter(Mandatory=$False, HelpMessage="Keep limited number of records in history. Possible values: all, number")]
        [String]
        $HistoryLimit,
        #
        [Parameter(Mandatory=$False, HelpMessage="Logging level.")]
        [ValidateSet("no", "low","high","debug")]
        [String]
        $Logging,
        #
        [Parameter(Mandatory=$False, HelpMessage="Change database location. By default database is located in user profile. Database will be moved to specified directory for saving space on system drive or other reasons.")]
        [Alias("DatabaseLocation")]
        [String]
        $RepositoryLocation,
        #
        [Parameter(Mandatory=$False, HelpMessage="Ignore SSL validation.")]
        [Nullable[boolean]]
        $IgnoreSSLValidation,
        #
        [Parameter(Mandatory=$False, HelpMessage="Output format. Possible values: short, full(default)")]
        [ValidateSet("short", "full")]
        [String]
        $Output,
        #
        [Parameter(Mandatory=$False, HelpMessage="Master password. Should be specified if configuration is protected by master password. Use -MasterPassword (ConvertTo-SecureString -string ""Your_Password"" -AsPlainText -Force)")]
        [SecureString]
        $MasterPassword
        
    )
    
    begin {
    }
    
    process {
        if (Get-MBSAgent) {
            $CBB = Get-MBSAgent 
            $Arguments = " option"
            
            if ($Edition){$Arguments += " -edition $Edition"}
            if ($Bandwidth){$Arguments += " -bandwidth $Bandwidth"}
            if ($Proxy){$Arguments += " -proxy $Proxy"}
            if ($ProxyAddress){$Arguments += " -pa $ProxyAddress"}
            if ($ProxyPort){$Arguments += " -pp $ProxyPort"}
            if ($ProxyAuthentication){$Arguments += " -pt $ProxyAuthentication"}
            if ($ProxyDomain){$Arguments += " -pd $ProxyDomain"}
            if ($ProxyUser){$Arguments += " -pu $ProxyUser"}
            if ($ProxyPassword){$Arguments += " -ps $ProxyPassword"}
            if ($ChunkSize){$Arguments += " -cs $ChunkSize"}
            if ($ThreadCount){$Arguments += " -threads $ThreadCount"}
            if ($Purge){$Arguments += " -purge $Purge"}
            if ($DelayPurge){$Arguments += " -delayPurge $DelayPurge"}
            if ($Keep){$Arguments += " -keep $Keep"}
            if ($HistoryPurge){$Arguments += " -hp $HistoryPurge"}
            if ($HistoryLimit){$Arguments += " -hk $HistoryLimit"}
            if ($Logging){$Arguments += " -logging $Logging"}

            if ($RepositoryLocation){$Arguments += " -repositoryLocation $RepositoryLocation"}
            if ($IgnoreSSLValidation -ne $null){
                if ($IgnoreSSLValidation) {
                    $Arguments += " -ignoreSSLValidation yes"
                }else{
                    $Arguments += " -ignoreSSLValidation no"
                }
            }
            if ($output){$Arguments += " -output $output"}
            if ($MasterPassword){$Arguments += " -mp """+([System.Runtime.InteropServices.Marshal]::PtrToStringAuto([System.Runtime.InteropServices.Marshal]::SecureStringToBSTR($MasterPassword)))+""""}
            Write-Verbose -Message "Arguments: $Arguments"
            Start-Process -FilePath $CBB.CBBCLIPath -ArgumentList $Arguments -NoNewWindow -Wait
        }
    }
    
    end {
    }
}

#----------------- MBS Utils -------------------------------
function Test-MBSConnection {
    <#
    .SYNOPSIS
        TCP port connection test to MBS servers
    .DESCRIPTION
        TCP port connection test to MBS servers
    .EXAMPLE
        PS C:\> Test-MBSConnection
 
        Running connection test to MBS. It will take up to 5 minutes. Please wait...
        Testing connection to 52.6.7.137 : 443 : OK
        Testing connection to 52.5.40.159 : 443 : OK
        Testing connection to 52.20.40.101 : 443 : OK
        Testing connection to 3.216.171.162 : 443 : OK
        Testing connection to 3.216.236.203 : 443 : OK
        Connection test is completed
    .INPUTS
        None
    .OUTPUTS
        System.String[]
    .NOTES
        Connection test allows you to check connection from your computer to MBS servers. Connection failing indicates firewall misconfiguration.
    #>


    [CmdletBinding()]
    param (
        
    )

    begin {
        $MBSServers = @( 
            ("52.6.7.137","443"),
            ("52.5.40.159","443"),
            ("52.20.40.101","443"),
            ("3.216.171.162","443"),
            ("3.216.236.203","443")
        )

        Write-Host "Running connection test to MBS. It will take up to 5 minutes. Please wait..." 
        Write-HostAndLog -Message "*********************************$env:computername************************" -FilePath tnc.txt -showMessage $False
    }
    
    process {
        function Check-MBSConnectionTestResult ($MBSServer) {
            Write-Host "Testing connection to " $MBSServer[0]":"$MBSServer[1]": " -NoNewline
            $Result = Test-NetConnection $MBSServer[0] -Port $MBSServer[1]
            if ($Result.TcpTestSucceeded){
                Write-Host "OK" -ForegroundColor Green
            } 
            else {
                Write-Host "Fail" -ForegroundColor Red
            }
            Write-HostAndLog -Message $Result -FilePath tnc.txt -showMessage $False
        }
        foreach ($MBSServer in $MBSServers) {
            Check-MBSConnectionTestResult ($MBSServer)
        }
    }
    
    end {
        Write-Host "Connection test is completed"
    }
}

function Import-Configuration {
    [CmdletBinding()]
    param (
        [xml]$BackupPlanXml,
        [Parameter(Mandatory=$False, HelpMessage="Master password. Should be specified if configuration is protected by master password. Use -MasterPassword (ConvertTo-SecureString -string ""Your_Password"" -AsPlainText -Force)")]
        [SecureString]
        $MasterPassword
    )
    
    begin {
        
    }
    
    process {
        $TempFolder = New-Item -Path "$env:TMP" -Name $BackupPlanXml.BasePlan.ID -ItemType "directory" -ErrorAction SilentlyContinue
        $BackupPlanFolder = $env:TMP+"\"+$BackupPlanXml.BasePlan.ID
        $BackupPlanPath = $env:TMP+"\"+$BackupPlanXml.BasePlan.ID+"\"+$BackupPlanXml.BasePlan.ID+".cbb"
        $BackupPlanConfiguration = $env:TMP+"\"+$BackupPlanXml.BasePlan.ID+".cbbconfiguration"
        $Arguments = "importConfig -f "+$BackupPlanConfiguration
        if ($MasterPassword) {
            if ($MasterPassword){$Arguments += " -mp """+([System.Runtime.InteropServices.Marshal]::PtrToStringAuto([System.Runtime.InteropServices.Marshal]::SecureStringToBSTR($MasterPassword)))+""""}
        }
        $BackupPlanXml.Save($BackupPlanPath)
        Add-Type -Assembly System.IO.Compression.FileSystem
        [System.IO.Compression.ZipFile]::CreateFromDirectory($BackupPlanFolder,
        $BackupPlanConfiguration, [System.IO.Compression.CompressionLevel]::Optimal, $false)
        Write-Verbose -Message "Arguments: $Arguments"
        $ProcessOutput = Start-Process -FilePath (Get-MBSAgent).CBBCLIPath -ArgumentList $Arguments -NoNewWindow -Wait 
        Remove-Item -Path $BackupPlanFolder -Force -Recurse
        Remove-Item -Path $BackupPlanConfiguration -Force -Recurse
    }
    
    end {
        
    }
}

#----------------- MBS API ---------------------------------
function Set-MBSAPICredential {
    <#
    .SYNOPSIS
        Short description
    .DESCRIPTION
        Long description
    .EXAMPLE
        PS C:\> <example usage>
        Explanation of what the example does
    .INPUTS
        Inputs (if any)
    .OUTPUTS
        Output (if any)
    .NOTES
        General notes
    #>


    [CmdletBinding()]
    param (
        #
        [Parameter(Mandatory=$true, HelpMessage="API User Name")]
        [string]
        $UserName,
        #
        [Parameter(Mandatory=$true, HelpMessage="API Password")]
        [String]
        $Password,
        #
        [Parameter(Mandatory=$false, HelpMessage="The profile name, which must be unique.")]
        [string]
        $StoreAs
    )
    
    begin {
        
    }
    
    process {
        $Global:APICred = New-Object -typename PSCredential -ArgumentList @($UserName,(ConvertTo-SecureString -String $Password -AsPlainText -Force))

        if ($StoreAs) {
            if (-not (Test-Path "$env:USERPROFILE\.mbs")){
                $Folder = New-Item -Path "$env:USERPROFILE" -Name ".mbs" -ItemType "directory" -ErrorAction SilentlyContinue
            }
            $Global:APICred | Select Username,@{Name="Password";Expression = { $_.password | ConvertFrom-SecureString }} | ConvertTo-Json | Out-File "$env:USERPROFILE\.mbs\$StoreAs.json" -Force
        }
    }
    
    end {
        
    }
}

function Get-MBSAPIHeader {
    [CmdletBinding()]
    param (
        
    )
    
    begin {
        
    }
    
    process {
        $BodyProviderLogin = @{
            UserName = $APICred.GetNetworkCredential().UserName
            Password = $APICred.GetNetworkCredential().Password
        }
        $Login = Invoke-RestMethod -Method 'Post' -Uri (Get-MBSApiUrl).ProviderLogin -Body $BodyProviderLogin
        $headers = @{
            'Authorization' = "Bearer " + $Login.access_token
            'Accept' = "application/json"
        }
        return $headers
    }
    
    end {
        
    }
}

function Get-MBSAPIUsers {
    <#
    .SYNOPSIS
        Short description
    .DESCRIPTION
        Long description
    .EXAMPLE
        PS C:\> Get-MBSAPIUsers | ft
         
        ID Email FirstName LastName NotificationEmails Company Enabled LicenseManagmentMode DestinationList
        -- ----- --------- -------- ------------------ ------- ------- -------------------- -----------
        bf3206df-ad73-4cdc-96ad-d4e3afa66ebc backupuser Alex V2 {} Red Dragon HQ True 2 {@{ID=2f...
        bac8f288-6785-4bd0-897e-9cb859ed336e John@api.com John Down {john@api.com, notification@api.com} ApiTest True 2 {@{ID=48...
    .INPUTS
        Inputs (if any)
    .OUTPUTS
        Output (if any)
    .NOTES
        General notes
    #>


    [CmdletBinding()]
    param (
        [Parameter(Mandatory=$false, HelpMessage="User ID")]
        [string]$ID
    )
    
    begin {
        
    }
    
    process {
        if ($ID) {
            $Users = Invoke-RestMethod -Uri ((Get-MBSApiUrl).Users+"/"+$ID) -Method Get -Headers (Get-MBSAPIHeader)
        }else{
            $Users = Invoke-RestMethod -Uri (Get-MBSApiUrl).Users -Method Get -Headers (Get-MBSAPIHeader)
        }
        return $Users
    }
    
    end {
        
    }
}

function Add-MBSAPIUser {
    [CmdletBinding()]
    param (
        [Parameter(Mandatory=$true, HelpMessage="Email")]
        [string]$Email,
        [Parameter(Mandatory=$false, HelpMessage="FirstName")]
        [string]$FirstName,
        [Parameter(Mandatory=$false, HelpMessage="LastName")]
        [string]$LastName,
        [Parameter(Mandatory=$false, HelpMessage="NotificationEmails")]
        [string[]]$NotificationEmails,
        [Parameter(Mandatory=$false, HelpMessage="Company")]
        [string]$Company,
        [Parameter(Mandatory=$false, HelpMessage="Enabled")]
        [bool]$Enabled = $true,
        [Parameter(Mandatory=$true, HelpMessage="Password")]
        [string]$Password,
        [Parameter(Mandatory=$false, HelpMessage="DestinationList")]
        [string]$DestinationList,
        [Parameter(Mandatory=$false, HelpMessage="SendEmailInstruction")]
        [bool]$SendEmailInstruction,
        [Parameter(Mandatory=$false, HelpMessage="LicenseManagmentMode")]
        [string]$LicenseManagmentMode
    )
    
    begin {
        $headers = Get-MBSAPIHeader
    }
    
    process {
        $UsersPost = @{
            Email = $Email.Trim()
            FirstName = $FirstName
            LastName = $LastName
            NotificationEmails = $NotificationEmails
            Company = $Company.Trim()
            Enabled = $Enabled
            Password = $Password
            DestinationList = $DestinationList
            SendEmailInstruction = $SendEmailInstruction
            LicenseManagmentMode = $LicenseManagmentMode
        }
        $UserID = Invoke-RestMethod -Uri (Get-MBSApiUrl).Users -Method Post -Headers $headers -Body ($UsersPost|ConvertTo-Json) -ContentType 'application/json'
        return $UserID
    }
    
    end {
        
    }
}

function Get-MBSAPICompany {
    [CmdletBinding()]
    param (
        
    )
    
    begin {
       
    }
    
    process {
        $Companies = Invoke-RestMethod -Uri (Get-MBSApiUrl).Companies -Method Get -Headers (Get-MBSAPIHeader)
        return $Companies
    }
    
    end {
        
    }
}

Export-ModuleMember -Function Install-MBSAgent
Set-Alias Uninstall-MBSAgent Remove-MBSAgent
Export-ModuleMember -Function Remove-MBSAgent -Alias Uninstall-MBSAgent
Export-ModuleMember -Function Import-MBSUsers
Export-ModuleMember -Function Get-MBSApiUrl
Export-ModuleMember -Function Edit-MBSBackupPlan
Export-ModuleMember -Function Get-MBSBackupPlan
Export-ModuleMember -Function Get-MBSRestorePlan
Export-ModuleMember -Function Get-MBSConsistencyCheckPlan
Export-ModuleMember -Function Get-MBSStorageAccount
Export-ModuleMember -Function Start-MBSBackupPlan
Export-ModuleMember -Function Stop-MBSBackupPlan
Export-ModuleMember -Function Set-MBSAgentSettings
Export-ModuleMember -Function Test-MBSConnection
Set-Alias gma Get-MBSAgent
Export-ModuleMember -Function Get-MBSAgent -Alias gma
#Export-ModuleMember -Function Compress-Configuration
Export-ModuleMember -Function Get-MBSAgentSettings
#---------------------- API ----------------------------------------------
#Export-ModuleMember -Function Set-MBSAPICredential
#Export-ModuleMember -Function Get-MBSAPIUsers
#Export-ModuleMember -Function Get-MBSAPICompany
#Export-ModuleMember -Function Add-MBSAPIUser