Param( [Parameter(Mandatory=$true, HelpMessage="Root folder containing the website files.")] [ValidateScript({Test-Path $_ -PathType Container})] [string]$RootPath, [Parameter(Mandatory=$true, HelpMessage="Base URL of the site (e.g., https://example.com).")] [ValidatePattern('^https?://')] [string]$BaseUrl, [Parameter(HelpMessage="Full path where sitemap.xml will be saved. Defaults to \sitemap.xml")] [string]$OutputFile = (Join-Path -Path $RootPath -ChildPath "sitemap.xml") ) # Ensure BaseUrl does not end with a slash if ($BaseUrl.EndsWith('/')) { $BaseUrl = $BaseUrl.TrimEnd('/') } # Define file extensions to include in the sitemap $extensions = '.html', '.htm', '.php', '.asp', '.aspx', '.jsp', '.txt', '.md' # Gather files recursively, excluding the output sitemap itself $files = Get-ChildItem -Path $RootPath -Recurse -File | Where-Object { $extensions -contains $_.Extension.ToLower() -and $_.FullName -ne (Resolve-Path -Path $OutputFile -ErrorAction SilentlyContinue).Path } # Create XmlWriter settings for pretty output $settings = New-Object System.Xml.XmlWriterSettings $settings.Indent = $true $settings.IndentChars = " " $settings.NewLineOnAttributes = $false $settings.Encoding = [System.Text.Encoding]::UTF8 $writer = [System.Xml.XmlWriter]::Create($OutputFile, $settings) try { $writer.WriteStartDocument() $writer.WriteStartElement("urlset", "http://www.sitemaps.org/schemas/sitemap/0.9") foreach ($file in $files) { # Compute relative URL path $relativePath = $file.FullName.Substring($RootPath.Length).TrimStart('\','/') $urlPath = $relativePath -replace '\\','/' # Encode spaces and other URI characters $escapedPath = [System.Web.HttpUtility]::UrlPathEncode($urlPath) $loc = "$BaseUrl/$escapedPath".Replace(':/','://') # ensure proper scheme separator $writer.WriteStartElement("url") $writer.WriteElementString("loc", $loc) # Last modification date in ISO 8601 (UTC) $lastMod = $file.LastWriteTimeUtc.ToString("yyyy-MM-ddTHH:mm:ssZ") $writer.WriteElementString("lastmod", $lastMod) # Optional tags – you can adjust as needed $writer.WriteElementString("changefreq", "weekly") $writer.WriteElementString("priority", "0.5") $writer.WriteEndElement() # } $writer.WriteEndElement() # $writer.WriteEndDocument() } finally { $writer.Flush() $writer.Close() $writer.Dispose() } Write-Host "Sitemap generated at: $OutputFile" -ForegroundColor Green