Public/Invoke-MSPBackupClientTool.ps1

Function Invoke-MSPBackupClientTool {
<#
    .SYNOPSIS
        Run MSP Backup ClientTool with a specified command.
    .DESCRIPTION
        Run MSP Backup ClientTool with a specified command.
    .PARAMETER Command
        The command to execute.
    .INPUTS
        System.String
    .EXAMPLE
        Invoke-MSPBackupClientTool -Command some.command
    .LINK
        about_functions_advanced
    .LINK
        about_CommonParameters
    #>

    [CmdletBinding()]
    [OutputType('System.String')]
    Param(
        [Parameter(
            Mandatory = $true,
            ValueFromPipeline = $true,
            HelpMessage = "The command to execute"
        )]
        [string]$Command
    )

    Begin {
        $BMPath = [Environment]::GetFolderPath('ProgramFiles') + "\Backup Manager"
        $CmdPath = $BMPath + "\ClientTool.exe"
        # $ConfigPath = "`"" + $BMPath + "\config.ini" + "`""
        $TestPath = Test-Path $CmdPath
        $stdOutTempFile = [System.IO.Path]::GetTempFileName()
        $stdErrTempFile = [System.IO.Path]::GetTempFileName()

        $RemoveItemParams = @{
            Path        = "$stdOutTempFile, $stdErrTempFile"
            Force       = $true
            ErrorAction = "SilentlyContinue"
        }
    }

    Process {
        If ($TestPath -eq "True") {
            $StartProcessParams = @{
                FilePath               = $CmdPath
                ArgumentList           = $ArgArray = @(
                    "-non-interactive",
                    $Command
                )
                Wait                   = $true
                NoNewWindow            = $true
                PassThru               = $true
                RedirectStandardOutput = $stdOutTempFile
                RedirectStandardError  = $stdErrTempFile
                ErrorAction            = "SilentlyContinue"
            }

            $StartExe = Start-Process @StartProcessParams
            $ClientToolExitCode = $StartExe.ExitCode
            $ClientToolStandardOutput = Get-Content -Path $stdOutTempFile | Out-String
            $ClientToolStandardOutput = $ClientToolStandardOutput.Trim()
            $ClientToolStandardError = Get-Content -Path $stdErrTempFile | Out-String
            $ClientToolStandardError = $ClientToolStandardError.Trim()

            If ($stdOutTempFile -or $stdErrTempFile) {
                Remove-Item @RemoveItemParams
            }
            $ArgArray | Out-Null
            $ClientToolExitCode | Out-Null

        } Else {
            $ClientToolStandardOutput = Get-Content -Path $stdOutTempFile | Out-String
            $ClientToolStandardOutput = $ClientToolStandardOutput.Trim()
            $ClientToolStandardError = "[ERROR]: ClientTool not found!"
            If ($stdOutTempFile -or $stdErrTempFile) {
                Remove-Item @RemoveItemParams
            }
        }
    }

    End {
    }
}