# パラメータ
$server = "https://<サーバーアドレス>"
$tenant = "<テナント名>"
$user = "<ユーザー名>"
$password = "<パスワード>"
#ログを保存するフォルダーへのパス
$folder = "C:\Temp\Logs\Stage" 
$reportFileName = "Project_SecurityEvents-{0:yyMMdd-HHmmss}.csv" -f (Get-Date)
# ログパラメータ
$requestBody = @"
filter={
    "Name": "Filter By Date",
    "GeneralOperator": "AND",
    "FilterItems": [
        {
            "PropertyKey": "Date",
            "PropertyOperator": "BETWEEN",
            "PropertyValues": [
                "2021-08-28",
                "00:00:00",
                "2023-09-28",
                "23:59:59"
            ]
        }
    ]
}
&columnsOrder=Id,Date,EventType,Details,RemoteHost,Principal,TenantName,Writer,WriterTenantName,
&sortColumnindex=1
&sortOrder=true
"@
#------------------------------------------------------------------------------
$methodUri = "/Project/GetSecurityEventsCSV"
$authServer = $server
$ServerSitePath = "/FlexiCapture12/Monitoring"
function Write-Line($str, $color = "White")
{
    Write-Host $str -ForegroundColor $color
}
function Join-Uri
{
    param([Parameter(Mandatory, ValueFromPipeline)] [string]$parent, [string]$child)
    if ($parent -eq "") {return $child;}
    if ($child -eq ""){return $parent}
    if ($parent.endswith("/") -or $parent.endswith("\\")) {$parent = $parent.substring(0,$parent.Length-1)}
    if ($child.startswith("/") -or $child.startswith("\\")) {$child = $child.substring(1,$child.Length-1)}
    return "$parent/$child"
}
function Get-AuthTicket($server, $user, $password, $tenant)
{
    $tenantSuffix=""
    if ($tenant -ne ''){ $tenantSuffix = "?tenant=$tenant"}
    $URL = Join-Uri $authServer "/FlexiCapture12/Server/FCAuth/API/Soap$tenantSuffix"
    $SOAPRequest = '<?xml version="1.0" encoding="utf-8"?><soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema"><soap:Body><FindUser xmlns="urn:http://www.abbyy.com/FlexiCapture"><userLogin>user</userLogin></FindUser></soap:Body></soap:Envelope>'
    $Headers = @{
        'SOAPAction' = '"#FindUser"'
        'Content-Type' = 'text/xml; charset=utf-8'
        'Authorization' = "Basic $([System.Convert]::ToBase64String([System.Text.Encoding]::ASCII.GetBytes("$($user):$($password)")))"}
    try
    {
        $response1 = Invoke-WebRequest -Uri $URL -Headers $Headers -Body $SOAPRequest -Method 'POST'
        return $response1.Headers['AuthTicket']
    }
    catch{
        Write-Line -str "Couldn't get 'AuthTicket': $_" -color "Red" 
        return ""
    }
}
function Download-CSVReport($server, $tenant, $authTicket, $methodUri, $requestBody, $folder, $reportFileName)
{
    $reportFullFilePath = Join-Path $folder $reportFileName
# フォルダーをサイレントで作成(存在しない場合)
    New-Item -ItemType Directory -Force -Path $folder | Out-Null
    if ($authTicket -eq "" -or $authTicket -eq $null)
    {
        Write-Line -str "Couldn't get 'CSV-Report'" -color "Red"
    }
    else
    {
        $header = @{ "Accept" = "*/*"} 
        $session = [Microsoft.PowerShell.Commands.WebRequestSession]::new()
        $session.Cookies.Add($server, [System.Net.Cookie]::new("FlexiCaptureTmpPrn$tenant", "Ticket=$authTicket"))
        $tenantInUrl=""
        if ($tenant -ne '') { $tenantInUrl = "/$tenant"}
        $uri = Join-Uri $server $ServerSitePath | Join-Uri -child $tenantInUrl | Join-Uri -child $methodUri
        try{
            $response = Invoke-WebRequest -Uri $uri -Method 'POST' -Headers $header -WebSession $session -Body $requestBody -OutFile $reportFullFilePath -MaximumRedirection 0 -ErrorAction Ignore -PassThru
            if ($response.StatusCode -lt 300)
            {
                Write-Line "CSV-Report done: $reportFullFilePath" "Green"
            }
            else
            {
                Write-Line -str "HttpStatus $($response.StatusCode) in getting CSV-Report." -color "Red"
            }
        }
        catch{
            Write-Line -str "Couldn't get CSV-Report: $_" -color "Red" 
            return ""
        }
    }
}
$authTicket = Get-AuthTicket -server $server -user $user -password $password -tenant $tenant
Download-CSVReport -server $server -tenant $tenant -authTicket $authTicket -methodUri $methodUri -requestBody $requestBody -folder $folder -reportFileName $reportFileName