param( [Parameter(Mandatory=$true, HelpMessage="Root folder containing the website files.")] [ValidateNotNullOrEmpty()] [string]$RootPath, [Parameter(Mandatory=$true, HelpMessage="Base URL of the website (e.g., https://example.com).")] [ValidatePattern('^https?://')] [string]$BaseUrl, [Parameter(Mandatory=$false, HelpMessage="Output sitemap file path.")] [string]$OutputFile = (Join-Path -Path $RootPath -ChildPath "sitemap.xml"), [Parameter(Mandatory=$false, HelpMessage="File extensions to include (comma‑separated).")] [string[]]$IncludeExtensions = @("html","htm","aspx","php","jsp","jspx"), [Parameter(Mandatory=$false, HelpMessage="Exclude paths (regex).")] [string]$ExcludePattern = $null, [Parameter(Mandatory=$false, HelpMessage="Change frequency for all URLs (optional).")] [ValidateSet("always","hourly","daily","weekly","monthly","yearly","never")] [string]$ChangeFreq = $null, [Parameter(Mandatory=$false, HelpMessage="Priority for all URLs (0.0‑1.0).")] [ValidateRange(0.0,1.0)] [float]$Priority = $null ) function Convert-PathToUrl { param( [Parameter(Mandatory=$true)][string]$FilePath, [Parameter(Mandatory=$true)][string]$RootPath, [Parameter(Mandatory=$true)][string]$BaseUrl ) # Normalise separators $relative = Resolve-Path -Path $FilePath -Relative -BasePath $RootPath $relative = $relative -replace '[\\]+','/' # Ensure leading slash if (-not $relative.StartsWith('/')) { $relative = '/' + $relative } return ($BaseUrl.TrimEnd('/') + $relative) } # Ensure root exists if (-not (Test-Path -Path $RootPath -PathType Container)) { Write-Error "RootPath '$RootPath' does not exist or is not a folder." exit 1 } # Prepare XML writer settings $settings = New-Object System.Xml.XmlWriterSettings $settings.Indent = $true $settings.Encoding = [System.Text.UTF8Encoding]::new($false) # no BOM $writer = [System.Xml.XmlWriter]::Create($OutputFile, $settings) try { $writer.WriteStartDocument() $writer.WriteStartElement("urlset", "http://www.sitemaps.org/schemas/sitemap/0.9") # Build a filter for file extensions $extFilter = $IncludeExtensions | ForEach-Object { "*.$_" } Get-ChildItem -Path $RootPath -Recurse -File -Include $extFilter | Where-Object { $include = $true if ($ExcludePattern) { $include = -not ($_ .FullName -match $ExcludePattern) } $include } | Sort-Object FullName | ForEach-Object { $url = Convert-PathToUrl -FilePath $_.FullName -RootPath (Resolve-Path $RootPath) -BaseUrl $BaseUrl $writer.WriteStartElement("url") $writer.WriteElementString("loc", $url) $lastMod = $_.LastWriteTimeUtc.ToString("yyyy-MM-ddTHH:mm:ssZ") $writer.WriteElementString("lastmod", $lastMod) if ($ChangeFreq) { $writer.WriteElementString("changefreq", $ChangeFreq) } if ($null -ne $Priority) { $writer.WriteElementString("priority", $Priority.ToString("0.0")) } $writer.WriteEndElement() # } $writer.WriteEndElement() # $writer.WriteEndDocument() } finally { $writer.Close() $writer.Dispose() } Write-Host "Sitemap generated at: $OutputFile" -ForegroundColor Green