Param( [Parameter(Mandatory=$false)] [string]$RootPath = ".", [Parameter(Mandatory=$false)] [string]$BaseUrl = "https://example.com", [Parameter(Mandatory=$false)] [string]$OutputFile = "sitemap.xml", [Parameter(Mandatory=$false)] [string[]]$Extensions = @(".html", ".htm", ".php", ".asp", ".aspx") ) # Ensure the root path exists if (-not (Test-Path -Path $RootPath -PathType Container)) { Write-Error "RootPath '$RootPath' does not exist or is not a directory." exit 1 } # Normalize paths $RootPath = (Resolve-Path -Path $RootPath).Path.TrimEnd('\') $BaseUrl = $BaseUrl.TrimEnd('/') # Build a hashset of extensions for fast look‑up $extSet = [System.Collections.Generic.HashSet[string]]::new([StringComparer]::OrdinalIgnoreCase) foreach ($e in $Extensions) { $extSet.Add($e.TrimStart('.')) | Out-Null } # Gather all matching files $files = Get-ChildItem -Path $RootPath -Recurse -File | Where-Object { $extSet.Contains($_.Extension.TrimStart('.')) } # Prepare XML writer settings $settings = New-Object System.Xml.XmlWriterSettings $settings.Indent = $true $settings.Encoding = [System.Text.Encoding]::UTF8 $settings.NewLineOnAttributes = $false # Create writer $writer = [System.Xml.XmlWriter]::Create($OutputFile, $settings) # Start document $writer.WriteStartDocument() $writer.WriteStartElement("urlset") $writer.WriteAttributeString("xmlns", "http://www.sitemaps.org/schemas/sitemap/0.9") foreach ($file in $files) { # Compute relative URL path $relativePath = $file.FullName.Substring($RootPath.Length).TrimStart('\','/') $relativePath = $relativePath -replace '\\','/' $url = "$BaseUrl/$relativePath" # Format last modification date in UTC (W3C Datetime) $lastMod = $file.LastWriteTimeUtc.ToString("yyyy-MM-ddTHH:mm:ssZ") $writer.WriteStartElement("url") $writer.WriteElementString("loc", $url) $writer.WriteElementString("lastmod", $lastMod) # Optional: changefreq and priority (static defaults; adjust as needed) # $writer.WriteElementString("changefreq", "weekly") # $writer.WriteElementString("priority", "0.5") $writer.WriteEndElement() # } # Close root element and document $writer.WriteEndElement() # $writer.WriteEndDocument() $writer.Flush() $writer.Close() Write-Host "Sitemap generated at: $OutputFile"