Param( [Parameter(Mandatory = $true, HelpMessage = "Base URL of the site (e.g., https://www.example.com)")] [ValidatePattern('^https?://')] [string]$BaseUrl, [Parameter(Mandatory = $true, HelpMessage = "Root folder containing the website files")] [string]$RootPath, [Parameter(HelpMessage = "Output file path for sitemap.xml (default: \sitemap.xml)")] [string]$OutputPath = "$RootPath\sitemap.xml" ) # Ensure the root path exists if (-not (Test-Path -Path $RootPath -PathType Container)) { Write-Error "RootPath '$RootPath' does not exist or is not a directory." exit 1 } # Resolve full paths $RootPath = (Resolve-Path -Path $RootPath).ProviderPath if ($OutputPath -eq "$RootPath\sitemap.xml") { $OutputPath = Join-Path -Path $RootPath -ChildPath "sitemap.xml" } $OutputPath = (Resolve-Path -Path (Split-Path -Parent $OutputPath) -ErrorAction SilentlyContinue).ProviderPath + "\" + (Split-Path -Leaf $OutputPath) # Gather files to include in the sitemap $extensions = @('*.html','*.htm','*.aspx','*.php','*.asp','*.jsp') $files = Get-ChildItem -Path $RootPath -Recurse -File -Include $extensions -ErrorAction SilentlyContinue if ($files.Count -eq 0) { Write-Warning "No files matching extensions $($extensions -join ', ') were found under $RootPath." exit 0 } # Create XML document [xml]$xml = New-Object System.Xml.XmlDocument $decl = $xml.CreateXmlDeclaration('1.0','UTF-8',$null) $xml.AppendChild($decl) | Out-Null $urlset = $xml.CreateElement('urlset') $urlset.SetAttribute('xmlns','http://www.sitemaps.org/schemas/sitemap/0.9') $xml.AppendChild($urlset) | Out-Null foreach ($file in $files) { # Build relative URL path $relativePath = $file.FullName.Substring($RootPath.Length).TrimStart('\','/') $url = ($BaseUrl.TrimEnd('/') + '/' + $relativePath) -replace '\\','/' $urlElement = $xml.CreateElement('url') $loc = $xml.CreateElement('loc') $loc.InnerText = $url $urlElement.AppendChild($loc) | Out-Null $lastmod = $xml.CreateElement('lastmod') $lastmod.InnerText = $file.LastWriteTimeUtc.ToString('yyyy-MM-ddTHH:mm:ssZ') $urlElement.AppendChild($lastmod) | Out-Null $urlset.AppendChild($urlElement) | Out-Null } # Save the sitemap try { $xml.Save($OutputPath) Write-Host "Sitemap successfully generated:" -ForegroundColor Green Write-Host " Path : $OutputPath" Write-Host " URLs : $($files.Count)" } catch { Write-Error "Failed to save sitemap to '$OutputPath'. $_" exit 1 }