PowerShellでExcelの全シートをシート保護、シート保護解除

バッチファイル

# シート保護解除
powershell -NoProfile -ExecutionPolicy Unrestricted .\excel-unlock.ps1 %1

# シート保護
powershell -NoProfile -ExecutionPolicy Unrestricted .\excel-lock.ps1 %1
if ( $args -eq $null ) {
    Write-Error '引数がありません'
}

if (Test-Path $args[0]) {
    $excel = New-Object -ComObject Excel.Application
    $excel.Visible = $false

    try {
        $book = $excel.Workbooks.Open($args[0])

        foreach ($sheet in $book.Worksheets) {

            $sheet.Activate()

            # シート保護解除
            $sheet.Unprotect()

            # シート保護
            $sheet.Protect()
        }


        # 上書き保存
        $book.Save()

    }
    catch {
        Write-Error 'エラーが発生しました'
    }
    finally {
        $excel.Quit()
        $excel = $null
        [GC]::Collect()
    }

}
else {
    Write-Error 'ファイルが見つかりません'
}