param( [Parameter(Mandatory=$true)] [string]$RootPath, [Parameter(Mandatory=$true)] [string]$BaseUrl, [string]$OutputFile = "sitemap.xml", [ValidateSet('html','htm','aspx','php','jsp','cfm')] [string[]]$IncludeExtensions = @('html','htm','aspx','php') ) # Ensure root path ends without trailing backslash $RootPath = (Resolve-Path -Path $RootPath).Path.TrimEnd('\') # Normalize BaseUrl to end with slash if (-not $BaseUrl.EndsWith('/')) { $BaseUrl += '/' } # Prepare list of files $searchPattern = "*.*" $files = Get-ChildItem -Path $RootPath -Recurse -File -Include $IncludeExtensions | ForEach-Object { $_ } if ($files.Count -eq 0) { Write-Warning "No files with the specified extensions were found under '$RootPath'." exit 1 } # Create the 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) try { $writer.WriteStartDocument() $writer.WriteStartElement("urlset") $writer.WriteAttributeString("xmlns", "http://www.sitemaps.org/schemas/sitemap/0.9") foreach ($file in $files) { # Build relative path $relativePath = $file.FullName.Substring($RootPath.Length).TrimStart('\','/').Replace('\','/') # URL encode special characters in the path $encodedPath = [System.Web.HttpUtility]::UrlPathEncode($relativePath) $loc = $BaseUrl + $encodedPath $writer.WriteStartElement("url") $writer.WriteElementString("loc", $loc) # Optional elements: lastmod, changefreq, priority $lastMod = $file.LastWriteTimeUtc.ToString("yyyy-MM-ddTHH:mm:ssZ") $writer.WriteElementString("lastmod", $lastMod) # You can customize these defaults as needed $writer.WriteElementString("changefreq", "weekly") $writer.WriteElementString("priority", "0.5") $writer.WriteEndElement() # } $writer.WriteEndElement() # $writer.WriteEndDocument() } finally { $writer.Flush() $writer.Close() } Write-Host "Sitemap generated at: $(Resolve-Path -Path $OutputFile).Path"