param( [Parameter(Mandatory = $true, HelpMessage = "Root folder of the website (physical path).")] [string]$RootPath, [Parameter(Mandatory = $true, HelpMessage = "Base URL of the site (e.g. https://example.com).")] [string]$BaseUrl, [Parameter(HelpMessage = "Full path to the sitemap file to create.")] [string]$OutputFile = "$RootPath\sitemap.xml", [ValidateSet('always','hourly','daily','weekly','monthly','yearly','never')] [string]$ChangeFreq = 'weekly', [ValidateRange(0.0,1.0)] [double]$Priority = 0.5, [string[]]$IncludeExtensions = @('.html', '.htm', '.php') ) # Ensure paths are resolved $RootPath = (Resolve-Path -Path $RootPath).ProviderPath if (-not (Test-Path -Path $RootPath -PathType Container)) { Write-Error "RootPath '$RootPath' does not exist or is not a directory." exit 1 } # Normalise BaseUrl (remove trailing slash) if ($BaseUrl.EndsWith('/')) { $BaseUrl = $BaseUrl.TrimEnd('/') } # Gather files $files = Get-ChildItem -Path $RootPath -Recurse -File | Where-Object { $IncludeExtensions -contains $_.Extension.ToLower() } if ($files.Count -eq 0) { Write-Warning "No files with extensions $($IncludeExtensions -join ', ') were found under '$RootPath'." } # Create XML writer settings $settings = New-Object System.Xml.XmlWriterSettings $settings.Indent = $true $settings.OmitXmlDeclaration = $false $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 web path $relativePath = $file.FullName.Substring($RootPath.Length).TrimStart('\','/') $relativeUrl = $relativePath -replace '\\','/' # Construct full URL $url = "$BaseUrl/$relativeUrl" $url = $url -replace '//','/' # Ensure scheme remains (e.g., https://) if ($url -notmatch '^[a-z][a-z0-9+.-]*://') { $url = $url -replace ':/','://' } $writer.WriteStartElement('url') $writer.WriteElementString('loc', $url) $lastMod = $file.LastWriteTimeUtc.ToString('yyyy-MM-dd') $writer.WriteElementString('lastmod', $lastMod) $writer.WriteElementString('changefreq', $ChangeFreq) $writer.WriteElementString('priority', $Priority.ToString('0.0', [cultureinfo]::InvariantCulture)) $writer.WriteEndElement() # url } $writer.WriteEndElement() # urlset $writer.WriteEndDocument() } finally { $writer.Flush() $writer.Close() $writer.Dispose() } Write-Host "Sitemap generated at: $OutputFile" -ForegroundColor Green