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) {
            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
        }else{
            if (-not(Test-Path -Path 'HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall\{07BCB989-197A-4E3D-852D-DE8363860401}'))
            {
                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
            }else{
                Write-Host "The backup agent is already installed."
            }
        }
    }
    
    end {

    }
}

Function Get-MBSAgent {
    <#
    .SYNOPSIS
        Get MBS agent parameters (version 0.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, (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.
    #>

    
    $UninstallKey = (Get-ItemProperty -Path "Registry::HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall\{07BCB989-197A-4E3D-852D-DE8363860401}" -Name "UninstallKey")."UninstallKey"
    $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}$"
    $CBBCLIPath = $CBBPath+"\cbb.exe"
    
    $MBSAgent = New-Object -TypeName psobject
    $MBSAgent | Add-Member -MemberType NoteProperty -Name UninstallKey -Value $UninstallKey
    $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
    
    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"
    }
}

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
    }

    $ProductName = (Get-MBSAgent).CBBName
    $StorageAccountsArray = @()
    $enginesettings = [xml](Get-Content ("$env:ProgramData\$ProductName\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
        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
    }

    Write-Verbose -Message "Arguments: -StorageType $StorageType -PlanType $PlanType"
    $ProductName = (Get-MBSAgent).CBBName

    $BackupPlansArray = @()

    foreach ($_ in (Get-ChildItem ("$env:ProgramData\$ProductName") -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
    }

    $ProductName = (Get-MBSAgent).CBBName

    $PlansArray = @()

    foreach ($_ in (Get-ChildItem ("$env:ProgramData\$ProductName") -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
    }

    $ProductName = (Get-MBSAgent).CBBName

    $PlansArray = @()

    foreach ($_ in (Get-ChildItem ("$env:ProgramData\$ProductName") -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=$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='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')]
        #[ValidateSet("yes", "no")]
        [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')]
        #[ValidateSet("yes", "no")]
        [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"")", ParameterSetName='Common')]
        [Parameter(Mandatory=$False, HelpMessage="Encryption password. Use -EncryptionPassword (ConvertTo-SecureString -string ""Your_Password"")", ParameterSetName='ImageBased')]
        [Parameter(Mandatory=$False, HelpMessage="Encryption password. Use -EncryptionPassword (ConvertTo-SecureString -string ""Your_Password"")", 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')]
        #[ValidateSet("yes", "no")]
        [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')]
        #[ValidateSet("yes", "no")]
        [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"")", 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"")", 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"")", 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')]
        #[ValidateSet("yes", "no")]
        [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')]
        #[ValidateSet("no", "1d", "1w", "1m")]
        [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')]
        #[ValidateSet("yes", "no")]
        [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')]
        #[ValidateSet("yes", "no")]
        [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')]
        #[ValidateSet("yes", "no")]
        [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')]
        #[ValidateSet("yes", "no")]
        [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')]
        #[ValidateSet("yes", "no")]
        [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')]
        #[ValidateSet("yes", "no")]
        [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')]
        #[ValidateSet("yes", "no")]
        [Nullable[boolean]]
        $iepnf,
        #
        [Parameter(Mandatory=$False, HelpMessage='Track deleted files data. Possible values: $true/$false', ParameterSetName='FileLevel')]
        #[ValidateSet("yes", "no")]
        [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="Remove a file from backup plan", ParameterSetName='FileLevel')]
        [string]
        $RemoveFile,
        #
        [Parameter(Mandatory=$False, HelpMessage="Remove a directory from backup plan", ParameterSetName='FileLevel')]
        [string]
        $RemoveDirectory,
        #
        [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')]
        #[ValidateSet("yes", "no")]
        [Nullable[boolean]]
        $disableVSS,
        #
        [Parameter(Mandatory=$False, HelpMessage='Ignore bad sectors. Possible values: $true/$false', ParameterSetName='ImageBased')]
        #[ValidateSet("yes", "no")]
        [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 {
    }
    
    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){$Arguments += " -sse $ServerSideEncryption"}
            if ($ServerSideEncryption -ne $null){
                if ($ServerSideEncryption) {
                    $Arguments += " -sse yes"
                }else{
                    $Arguments += " -sse no"
                }
            }
            if ($EncryptionAlgorithm){$Arguments += " -ea $EncryptionAlgorithm"}
            if ($EncryptionPassword){$Arguments += " -ep """+(ConvertFrom-SecureString $EncryptionPassword)+""""}
            if ($StorageClass){$Arguments += " -sc $StorageClass"}
            if ($SaveBPConfiguration -ne $null){
                if ($SaveBPConfiguration) {
                    $Arguments += " -sp yes"
                }else{
                    $Arguments += " -sp no"
                }
            }
            #if ($SaveBPConfiguration){$Arguments += " -sp $SaveBPConfiguration"}
            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){$Arguments += " -pac $pac"}
            if ($pac -ne $null){
                if ($pac) {
                    $Arguments += " -pac yes"
                }else{
                    $Arguments += " -pac no"
                }
            }
            if ($postAction){$Arguments += " -postAction $postAction"}
            #if ($paa){$Arguments += " -paa $paa"}
            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){$Arguments += " -keepLastVersion $keepLastVersion"}
            if ($keepLastVersion -ne $null){
                if ($keepLastVersion) {
                    $Arguments += " -keepLastVersion yes"
                }else{
                    $Arguments += " -keepLastVersion no"
                }
            }
            if ($delayPurge){$Arguments += " -delayPurge $delayPurge"}
            #if ($runMissed){$Arguments += " -runMissed $runMissed"}
            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){$Arguments += " -useBlockLevelBackup $useBlockLevelBackup"}
            if ($useBlockLevelBackup -ne $null){
                if ($useBlockLevelBackup) {
                    $Arguments += " -useBlockLevelBackup yes"
                }else{
                    $Arguments += " -useBlockLevelBackup no"
                }
            }

            # --------- File-Level ------------
            #if ($ntfs){$Arguments += " -ntfs $ntfs"}
            if ($ntfs -ne $null){
                if ($ntfs) {
                    $Arguments += " -ntfs yes"
                }else{
                    $Arguments += " -ntfs no"
                }
            }
            #if ($ForceUsingVSS){$Arguments += " -vss $ForceUsingVSS"}
            if ($ForceUsingVSS -ne $null){
                if ($ForceUsingVSS) {
                    $Arguments += " -vss yes"
                }else{
                    $Arguments += " -vss no"
                }
            }
            #if ($sharerw){$Arguments += " -sharerw $sharerw"}
            if ($sharerw -ne $null){
                if ($sharerw) {
                    $Arguments += " -sharerw yes"
                }else{
                    $Arguments += " -sharerw no"
                }
            }
            if ($df){$Arguments += " -df $df"}
            #if ($BackupEmptyFolders){$Arguments += " -bef $BackupEmptyFolders"}
            if ($BackupEmptyFolders -ne $null){
                if ($BackupEmptyFolders) {
                    $Arguments += " -bef yes"
                }else{
                    $Arguments += " -bef no"
                }
            }
            if ($oa){$Arguments += " -oa $oa"}
            #if ($es){$Arguments += " -es $es"}
            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){$Arguments += " -iepnf $iepnf"}
            if ($iepnf -ne $null){
                if ($iepnf) {
                    $Arguments += " -iepnf yes"
                }else{
                    $Arguments += " -iepnf no"
                }
            }
            #if ($TrackDeletedFiles){$Arguments += " -trackdeleted $TrackDeletedFiles"}
            if ($TrackDeletedFiles -ne $null){
                if ($TrackDeletedFiles) {
                    $Arguments += " -trackdeleted yes"
                }else{
                    $Arguments += " -trackdeleted no"
                }
            }
            if ($AddNewFile){$Arguments += " -af $AddFile"}
            if ($AddNewFolder){$Arguments += " -ad $AddFolder"}
            if ($RemoveFile){$Arguments += " -rf $RemoveFile"}
            if ($RemoveDirectory){$Arguments += " -rd $RemoveDirectory"}
            if ($BackupFile){$Arguments += " -f $BackupFile"}
            if ($BackupDirectory){$Arguments += " -d $BackupDirectory"}
            #if ($GenerateDetailedReport){$Arguments += " -dr $GenerateDetailedReport"}
            if ($GenerateDetailedReport -ne $null){
                if ($GenerateDetailedReport) {
                    $Arguments += " -dr yes"
                }else{
                    $Arguments += " -dr no"
                }
            }
            if ($output){$Arguments += " -output $output"}
            if ($MasterPassword){$Arguments += " -mp """+(ConvertFrom-SecureString $MasterPassword)+""""}

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

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

            #if ($disableVSS){$Arguments += " -disableVSS $disableVSS"}
            if ($disableVSS -ne $null){
                if ($disableVSS) {
                    $Arguments += " -disableVSS yes"
                }else{
                    $Arguments += " -disableVSS no"
                }
            }
            #if ($ignoreBadSectors){$Arguments += " -ignoreBadSectors $ignoreBadSectors"}
            if ($ignoreBadSectors -ne $null){
                if ($ignoreBadSectors) {
                    $Arguments += " -ignoreBadSectors yes"
                }else{
                    $Arguments += " -ignoreBadSectors no"
                }
            }
            #if ($useSystemVSS){$Arguments += " -useSystemVSS $useSystemVSS"}
            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
        }
        #Write-Progress -Activity "Triming user name" -Id 1 -PercentComplete (($i/$Users.Length)*100) -CurrentOperation $_.Email
        $CBB = Get-MBSAgent 
        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.
    .INPUTS
        System.String[]
        System.String
    .OUTPUTS
        System.String[]
    #>


    [CmdletBinding()]
    param (
        [Parameter(ValueFromPipelineByPropertyName)]
        [string]
        $ID,
        #
        [Parameter(ValueFromPipelineByPropertyName)]
        [string]
        $Name,
        [switch]
        $ForceFull,
        #
        [Parameter(Mandatory=$False, HelpMessage="Master password. Should be specified if configuration is protected by master password. Use -MasterPassword (ConvertTo-SecureString -string ""Your_Password"")")]
        [SecureString]
        $MasterPassword
    )
    
    begin {
        $CBB = Get-MBSAgent
    }
    
    process {
        if ($ID){
            $Arguments += "plan -r $ID"
        }else{
            $Arguments += "plan -r ""$Name"""
        }
        if($ForceFull){$Arguments += " -ForceFull"}
        if ($MasterPassword){$Arguments += " -mp """+(ConvertFrom-SecureString $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"")")]
        [SecureString]
        $MasterPassword
    )
    
    begin {
        $CBB = Get-MBSAgent
    }
    
    process {
        if ($ID){
            $Arguments += "plan -s $ID"
        }else{
            $Arguments += "plan -s ""$Name"""
        }
        if ($MasterPassword){$Arguments += " -mp """+(ConvertFrom-SecureString $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 {
    }
}

Export-ModuleMember -Function Install-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
Set-Alias gma Get-MBSAgent
Export-ModuleMember -Function Get-MBSAgent -Alias gma