-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathCheck-Links.ps1
88 lines (71 loc) · 2.67 KB
/
Check-Links.ps1
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
Param(
[Parameter(Mandatory = $true)]
[string]$MarkdownFile
)
# ファイルの存在確認
if (-not (Test-Path $MarkdownFile)) {
Write-Error "エラー: ファイルが見つかりません - '$MarkdownFile'"
exit 1
}
# ファイル内容の読み込み
$content = Get-Content -Path $MarkdownFile -Raw
# ハイパーリンクの正規表現パターン
$pattern = '\[(.*?)\]\((http[s]?://.*?)\)'
# ハイパーリンクの抽出
$matches = [regex]::Matches($content, $pattern)
if ($matches.Count -eq 0) {
Write-Host "情報: ハイパーリンクが見つかりませんでした。"
exit 0
}
$errors = @()
$totalLinks = $matches.Count
$currentLink = 1
# User-Agent ヘッダーを設定
$headers = @{
'User-Agent' = 'Mozilla/5.0 (Windows NT 10.0; Win64; x64)'
}
foreach ($match in $matches) {
$linkText = $match.Groups[1].Value
$url = $match.Groups[2].Value
# リンクテキストに「(リンク切れ)」が含まれる場合はスキップ
if ($linkText -like "*`(リンク切れ`)*") {
Write-Host "[$currentLink/$totalLinks] スキップ: $url (リンクテキストに「(リンク切れ)」を含むため)"
$currentLink++
continue
}
Write-Host "[$currentLink/$totalLinks] チェック中: $url"
$success = $false
# メソッドのリスト(HEAD を試してから GET)
$methods = @('HEAD', 'GET')
foreach ($method in $methods) {
try {
$response = Invoke-WebRequest -Uri $url -Method $method -Headers $headers -UseBasicParsing -TimeoutSec 15 -ErrorAction Stop
# ステータスコードが 400 未満なら成功とみなす
if ($response.StatusCode -lt 400) {
Write-Host " 結果: OK ($($response.StatusCode)) - メソッド: $method" -ForegroundColor Green
$success = $true
break
} else {
Write-Host " 結果: エラー ($($response.StatusCode)) - メソッド: $method" -ForegroundColor Yellow
}
} catch {
Write-Host " 結果: エラー ($($_.Exception.Message)) - メソッド: $method" -ForegroundColor Red
}
}
if (-not $success) {
$errors += @{
URL = $url
Message = "アクセスに失敗しました。"
}
}
$currentLink++
}
if ($errors.Count -gt 0) {
Write-Host "`n以下のリンクでエラーが発生しました:" -ForegroundColor Yellow
foreach ($linkError in $errors) {
Write-Host "- $($linkError.URL): $($linkError.Message)" -ForegroundColor Red
}
exit 1
} else {
Write-Host "`nすべてのリンクが有効です。" -ForegroundColor Green
}