Param( [Parameter(Mandatory=$true)] [string]$RootPath, [Parameter(Mandatory=$true)] [ValidatePattern('^https?://')] [string]$BaseUrl, [string]$OutputFile = (Join-Path -Path $RootPath -ChildPath 'sitemap.xml'), [string[]]$IncludePatterns = @('*.html','*.htm','*.aspx','*.php') ) function Convert-ToUrlPath { param([string]$Path) $segments = $Path -split '[\\/]' | ForEach-Object { [System.Uri]::EscapeDataString($_) } return ($segments -join '/') } # Ensure paths are full and normalized $RootPath = (Resolve-Path -Path $RootPath).Path if (-not (Test-Path -Path $RootPath -PathType Container)) { Write-Error "RootPath '$RootPath' does not exist or is not a directory." exit 1 } $BaseUrl = $BaseUrl.TrimEnd('/') # Collect files $files = Get-ChildItem -Path $RootPath -Recurse -File -Include $IncludePatterns # Prepare XML writer settings $settings = New-Object System.Xml.XmlWriterSettings $settings.Indent = $true $settings.Encoding = [System.Text.Encoding]::UTF8 $writer = [System.Xml.XmlWriter]::Create($OutputFile, $settings) $writer.WriteStartDocument() $writer.WriteStartElement('urlset') $writer.WriteAttributeString('xmlns', 'http://www.sitemaps.org/schemas/sitemap/0.9') foreach ($file in $files) { # Relative path from root $relativePath = $file.FullName.Substring($RootPath.Length).TrimStart('\','/') $urlPath = Convert-ToUrlPath -Path $relativePath $loc = "$BaseUrl/$urlPath" # lastmod in ISO 8601 (date only) $lastMod = $file.LastWriteTimeUtc.ToString('yyyy-MM-dd') $writer.WriteStartElement('url') $writer.WriteElementString('loc', $loc) $writer.WriteElementString('lastmod', $lastMod) # Optional elements can be added, e.g., changefreq, priority # $writer.WriteElementString('changefreq', 'weekly') # $writer.WriteElementString('priority', '0.5') $writer.WriteEndElement() # } $writer.WriteEndElement() # $writer.WriteEndDocument() $writer.Flush() $writer.Close() Write-Host "Sitemap generated at: $OutputFile"