param( [Parameter(Mandatory=$true, Position=0)] [string]$RootPath, [Parameter(Mandatory=$true, Position=1)] [ValidatePattern('^https?://')] [string]$BaseUrl, [string]$OutputFile = "sitemap.xml", [string[]]$IncludeExtensions = @('*.html','*.htm','*.php','*.asp','*.aspx') ) Set-StrictMode -Version Latest function Get-RelativeUrl { param( [string]$FullPath, [string]$RootPath ) $relative = $FullPath.Substring($RootPath.Length) $relative = $relative.TrimStart('\','/') $relative = $relative -replace '\\','/' return $relative } function Escape-Xml { param([string]$Text) $xmlSettings = New-Object System.Xml.XmlWriterSettings $xmlSettings.OmitXmlDeclaration = $true $stringWriter = New-Object System.IO.StringWriter $writer = [System.Xml.XmlWriter]::Create($stringWriter, $xmlSettings) $writer.WriteString($Text) $writer.Flush() $writer.Close() return $stringWriter.ToString() } # Resolve full path and ensure it ends with a directory separator $rootFullPath = (Resolve-Path -Path $RootPath).ProviderPath if (-not $rootFullPath.EndsWith([System.IO.Path]::DirectorySeparatorChar)) { $rootFullPath += [System.IO.Path]::DirectorySeparatorChar } # Prepare XmlWriter $settings = New-Object System.Xml.XmlWriterSettings $settings.Indent = $true $settings.Encoding = [System.Text.Encoding]::UTF8 $settings.NewLineOnAttributes = $false $writer = [System.Xml.XmlWriter]::Create($OutputFile, $settings) $writer.WriteStartDocument() $writer.WriteStartElement('urlset') $writer.WriteAttributeString('xmlns', 'http://www.sitemaps.org/schemas/sitemap/0.9') # Retrieve files $files = Get-ChildItem -Path $rootFullPath -Recurse -File -Include $IncludeExtensions -ErrorAction SilentlyContinue foreach ($file in $files) { $relativeUrl = Get-RelativeUrl -FullPath $file.FullName -RootPath $rootFullPath $escapedRelative = [System.Web.HttpUtility]::UrlPathEncode($relativeUrl) $loc = "$BaseUrl/$escapedRelative".TrimEnd('/') $lastMod = $file.LastWriteTimeUtc.ToString('yyyy-MM-ddTHH:mm:sszzz') $writer.WriteStartElement('url') $writer.WriteElementString('loc', $loc) $writer.WriteElementString('lastmod', $lastMod) # Optional: changefreq and priority can be added here if desired $writer.WriteEndElement() # } $writer.WriteEndElement() # $writer.WriteEndDocument() $writer.Flush() $writer.Close() Write-Host "Sitemap generated at: $OutputFile" -ForegroundColor Green