param( [Parameter(Mandatory=$true, Position=0)] [ValidateNotNullOrEmpty()] [string]$SiteRootPath, [Parameter(Mandatory=$true, Position=1)] [ValidatePattern('^https?://')] [string]$BaseUrl, [ValidateSet('always','hourly','daily','weekly','monthly','yearly','never')] [string]$DefaultChangeFreq = 'weekly', [ValidateRange(0.0,1.0)] [double]$DefaultPriority = 0.5 ) function Get-RelativeWebPath { param( [string]$FullPath, [string]$RootPath ) $relative = Resolve-Path -Path $FullPath -Relative -BasePath $RootPath $relative = $relative -replace '\\','/' if (-not $relative.StartsWith('/')) { $relative = '/' + $relative } return $relative } # Ensure the root path exists if (-not (Test-Path -LiteralPath $SiteRootPath -PathType Container)) { Write-Error "Site root path '$SiteRootPath' does not exist or is not a directory." exit 1 } # Gather all files considered as web pages $extensions = '.html', '.htm', '.php', '.aspx', '.asp', '.jsp', '.jspx', '.cfm', '.xml' $webFiles = Get-ChildItem -Path $SiteRootPath -Recurse -File -Include $extensions | Where-Object { $_.Name -notmatch '^sitemap\.xml$' } # Prepare XML writer settings $xmlSettings = New-Object System.Xml.XmlWriterSettings $xmlSettings.Indent = $true $xmlSettings.Encoding = [System.Text.Encoding]::UTF8 $sitemapPath = Join-Path -Path $SiteRootPath -ChildPath 'sitemap.xml' $writer = [System.Xml.XmlWriter]::Create($sitemapPath, $xmlSettings) try { $writer.WriteStartDocument() $writer.WriteStartElement('urlset') $writer.WriteAttributeString('xmlns', 'http://www.sitemaps.org/schemas/sitemap/0.9') foreach ($file in $webFiles) { $relativeWebPath = Get-RelativeWebPath -FullPath $file.FullName -RootPath $SiteRootPath $url = $BaseUrl.TrimEnd('/') + $relativeWebPath $writer.WriteStartElement('url') $writer.WriteElementString('loc', $url) $lastMod = $file.LastWriteTimeUtc.ToString('yyyy-MM-ddTHH:mm:sszzz') $writer.WriteElementString('lastmod', $lastMod) $writer.WriteElementString('changefreq', $DefaultChangeFreq) $writer.WriteElementString('priority', ('{0:N1}' -f $DefaultPriority)) $writer.WriteEndElement() # } $writer.WriteEndElement() # $writer.WriteEndDocument() } finally { $writer.Flush() $writer.Close() $writer.Dispose() } Write-Host "Sitemap generated at: $sitemapPath" -ForegroundColor Green