Functions of Word

#Functions_Word
$pathTop = [Environment]::GetFolderPath('Desktop')

. .\Func_Files.ps1

function sampleWord{
    $wordApp = New-Object -ComObject Word.Application
    $wordApp.Visible = $true
    $doc = $wordApp.Documents.Add()
    $doc.Content.Text = "foo, bar"
    $doc.SaveAs($fullOut)
    $doc.Close()
    $wordApp.Quit()
    $wordApp = $null
    #Start-Sleep -s 1
}

function DocOpen{
    param(
        $nmDoc,
        $AppIn,
        [switch]$ReadOnly,
        [switch]$WindowMinimized,[switch]$WindowNomal,
        [switch]$UnVisible,
        [switch]$Silence
        )
    if($AppIn -ne $null){
        [Microsoft.Office.Interop.Word.ApplicationClass]$App = $AppIn 
    }else{
        $App = New-Object -ComObject Word.Application
    }
    $App.Visible = $true
    $App.WindowState=[Windows.Forms.FormWindowState]::Normal

    $full= Convert-Path $nmDoc
    try{
        [Microsoft.Office.Interop.Word.DocumentClass]$doc = $App.Documents.Open( `
            $full,$false,[bool]$ReadOnly,$true,"","",$false,"","",0,50001,-Not([bool]$UnVisible)) 
            #FileName,confirmconversions,ReadOnly,addtorecentfiles,passworddocument,
            #passworddocument,Revert,writepassworddocument,writepassworddocument,__Format,
            #Encoding,Visible,OpenConflictDocument,openandrepair,documentdirection,NoEncodingDialog)
    }
    catch{
        if($Silence -eq $false){ Write-Host "Error - Fail Open $nmDoc" }
        return $null
    }
    
    if($WindowNomal){
        $App.ActiveWindow.Height=700
        $App.ActiveWindow.Width=800   
    }
    if($WindowMinimized){
        $App.ActiveWindow.Height=50
        $App.ActiveWindow.Width=200       
        $App.WindowState=[Windows.Forms.FormWindowState]::Maximized #名前変
    }

    $App = $null
    return $doc
}

# pathOut 指定無しなら同一フォルダ
function DocToPdf{
    param(
        [Microsoft.Office.Interop.Word.DocumentClass]$doc,
        $pathOut,
        [switch]$OverWriteByDate        
    )

    if([bool]$pathOut -eq $true){
        $fullOut= Join-Path $pathOut $doc.Name

        $fullOut= [System.IO.Path]::ChangeExtension($fullOut, ".pdf")
    }else{
        $fullOut= [System.IO.Path]::ChangeExtension($doc.FullName, ".pdf")
    }

    ExitByPasteDrive $fullOut

    if(Test-Path $fullOut){
        if($OverWriteByDate){
            $dateMoto = (Get-ItemProperty $doc.FullName).LastWriteTime
            $dateSaki = (Get-ItemProperty $fullOut).LastWriteTime
            if($dateMoto -lt $dateSaki){
                return "Cancel: NoExec by date $fullOut ."
            }
        }
        $ret = "Exec: OverWrite $fullOut ."
    }else{
        $ret = "Exec: Create $fullOut ."
    }
    $doc.ExportAsFixedFormat(     # void
        [string]$fullOut, #OutputFileName  nameだけならドキュメントに保存
        [Microsoft.Office.Interop.Word.WdExportFormat]::wdExportFormatPDF,
        [bool]$false ,#OpenAfterExport
        [Microsoft.Office.Interop.Word.WdExportOptimizeFor]::wdExportOptimizeForPrint,
        [Microsoft.Office.Interop.Word.WdExportRange]::wdExportAllDocument,
        [int]1, [int]1, 
        [Microsoft.Office.Interop.Word.WdExportItem]::wdExportDocumentContent,
        [bool]$false, #IncludeDocProps
        [bool]$false, # KeepIRM
        [Microsoft.Office.Interop.Word.WdExportCreateBookmarks]::wdExportCreateNoBookmarks,
        [bool]$true, # DocStructureTags
        [bool]$true, # BitmapMissingFonts
        [bool]$true) # UseISO19005_1

    return $ret
}

function DocsToPdfAtCurDir($pathOut,$pathLog){
    $boLog = MyTestPath $pathLog
    if($boLog){WriteLog "Start Doc-to-Pdf." $pathLog}
    else{Write-Host "Start Doc-to-Pdf."}    

    [Microsoft.Office.Interop.Word.ApplicationClass]$App = `
        New-Object -ComObject Word.Application
    $App.Visible = $true

    $nms = Get-ChildItem -Name | where{$_ -like "*.doc*"} | sort

    $nmsExec =@()
    foreach($nm in $nms){
        $fullOut= Join-Path $pathOut $nm
        $fullOut= [System.IO.Path]::ChangeExtension($fullOut, ".pdf")

        if(Test-Path $fullOut){
            $dateMoto = (Get-ItemProperty $nm).LastWriteTime
            $dateSaki = (Get-ItemProperty $fullOut).LastWriteTime
            if($dateMoto -gt $dateSaki){
                $nmsExec += $nm
            } 
        }else{
            $nmsExec += $nm
        }
    }
    $cntExec = $nmsExec.Length 
    $rate = 0.4
    $msg = "$cntExec files will exec. Wait. Remain " + (MyRound ($rate*$cntExec/60) -1) +" minutes."
    if($boLog){WriteLog $msg $pathLog}else{Write-Host $msg}
    $tSta = Get-Date

    if($cntExec -gt 0){
        $cnt = 0
        foreach($nm in $nmsExec){
            [Microsoft.Office.Interop.Word.DocumentClass]$doc = DocOpen $nm $App -ReadOnly -UnVisible -Silence
            if([bool]$doc){
                $ret = DocToPdf $doc $pathOut -OverWriteByDate
                if($boLog){WriteLog $ret $pathLog}else{Write-Host $ret}
                $doc.Close()

                $cnt++
                if($cnt % 20 -eq 0){
                    $tNow = Get-Date
                    if($cnt -gt 0){ $rate = (($tNow-$tSta).TotalSeconds)/$cnt }else{$rate = 0.4 }
                    Write-Host ([string]$cnt + "/" + [string]$cntExec + " files execed. Remain " `
                                    + (MyRound ($rate*($cntExec-$cnt)/60) -1) +" minutes.")
                }
            }else{
                WriteLog "Error: Fail to OpenDoc $nm ."
                $flagErrOpen=$true
            }
        }
        $tNow = Get-Date
        if($cnt -gt 0){ $rate = (($tNow-$tSta).TotalSeconds)/$cnt }else{$rate = 0.4 }
    }
    $App.Quit()
    $App=$null
    [System.GC]::Collect()

    $msg = ("Finished Doc-to-Pdf. Taked " + (MyRound (($tNow-$tSta).TotalSeconds/60) -1) `
                + " minutes. Rate is " + (MyRound $rate -1) + " seconds.")
    if($boLog){WriteLog $msg $pathLog}
    else{Write-Host $msg }

    if($flagErrOpen){
        $msg="OpenDocエラー有り。以下の何れかを試して。`r`n `
                ・Wordのオプション⇒セキュリティセンターでファイル制限機能のチェックを外す。`r`n・Docを最新形式で保存する。"
        ResByMsgbox $msg 
    }


}