param( [Parameter(Mandatory=$true)] [ValidateNotNullOrEmpty()] [string]$RootPath, [Parameter(Mandatory=$true)] [ValidatePattern('^https?://')] [string]$BaseUrl, [string]$OutputFile = "sitemap.xml", [ValidateSet('always','hourly','daily','weekly','monthly','yearly','never')] [string]$ChangeFreq = 'weekly', [ValidateRange(0,1)] [double]$Priority = 0.5 ) function Write-ErrorAndExit { param([string]$Message) Write-Error $Message exit 1 } if (-not (Test-Path -LiteralPath $RootPath -PathType Container)) { Write-ErrorAndExit "RootPath '$RootPath' does not exist or is not a directory." } # Ensure BaseUrl ends with a slash if ($BaseUrl[-1] -ne '/') { $BaseUrl = "$BaseUrl/" } # Resolve full paths $rootFullPath = (Resolve-Path -LiteralPath $RootPath).Path # Gather files to include in sitemap $extensions = @('*.html','*.htm','*.php','*.asp','*.aspx') $files = Get-ChildItem -Path $rootFullPath -Recurse -File -Include $extensions -ErrorAction Stop # Create XML document $xmlDoc = New-Object System.Xml.XmlDocument $xmlDeclaration = $xmlDoc.CreateXmlDeclaration('1.0','UTF-8',$null) $xmlDoc.AppendChild($xmlDeclaration) | Out-Null $urlset = $xmlDoc.CreateElement('urlset') $xmlnsAttr = $xmlDoc.CreateAttribute('xmlns') $xmlnsAttr.Value = 'http://www.sitemaps.org/schemas/sitemap/0.9' $urlset.Attributes.Append($xmlnsAttr) | Out-Null $xmlDoc.AppendChild($urlset) | Out-Null foreach ($file in $files) { $relativePath = $file.FullName.Substring($rootFullPath.Length).TrimStart('\','/') $urlPath = $relativePath -replace '\\','/' $loc = $BaseUrl + $urlPath $urlNode = $xmlDoc.CreateElement('url') $locNode = $xmlDoc.CreateElement('loc') $locNode.InnerText = $loc $urlNode.AppendChild($locNode) | Out-Null $lastModNode = $xmlDoc.CreateElement('lastmod') $lastModNode.InnerText = $file.LastWriteTime.ToString('yyyy-MM-dd') $urlNode.AppendChild($lastModNode) | Out-Null $changeFreqNode = $xmlDoc.CreateElement('changefreq') $changeFreqNode.InnerText = $ChangeFreq $urlNode.AppendChild($changeFreqNode) | Out-Null $priorityNode = $xmlDoc.CreateElement('priority') $priorityNode.InnerText = $Priority.ToString('0.##') $urlNode.AppendChild($priorityNode) | Out-Null $urlset.AppendChild($urlNode) | Out-Null } # Save to file try { $outputPath = Join-Path -Path (Get-Location) -ChildPath $OutputFile $xmlDoc.Save($outputPath) Write-Host "Sitemap generated successfully at: $outputPath" } catch { Write-Error "Failed to save sitemap: $_" exit 1 }