param( [Parameter(Mandatory=$true, Position=0)] [string]$RootPath, [Parameter(Mandatory=$true, Position=1)] [ValidatePattern('^https?://')] [string]$BaseUrl, [Parameter(Position=2)] [string]$OutputPath = (Join-Path -Path $RootPath -ChildPath 'sitemap.xml') ) # Ensure trailing slash on BaseUrl if (-not $BaseUrl.EndsWith('/')) { $BaseUrl = "$BaseUrl/" } # Resolve the root path $resolvedRoot = Resolve-Path -Path $RootPath -ErrorAction Stop | Select-Object -ExpandProperty Path if (-not (Test-Path -LiteralPath $resolvedRoot -PathType Container)) { Write-Error "RootPath '$RootPath' does not exist or is not a directory." exit 1 } # Gather files to include in sitemap (common web page extensions) $extensions = @('.html','.htm','.php','.aspx','.asp') $files = Get-ChildItem -Path $resolvedRoot -Recurse -File | Where-Object { $extensions -contains $_.Extension.ToLower() } # Prepare XML document $ns = 'http://www.sitemaps.org/schemas/sitemap/0.9' $xml = New-Object System.Xml.XmlDocument $decl = $xml.CreateXmlDeclaration('1.0','UTF-8',$null) $xml.AppendChild($decl) | Out-Null $urlset = $xml.CreateElement('urlset', $ns) $xml.AppendChild($urlset) | Out-Null foreach ($file in $files) { # Compute relative path $relativePath = $file.FullName.Substring($resolvedRoot.Length).TrimStart('\','/') $relativeUrl = $relativePath -replace '\\','/' # URL-encode each segment to avoid illegal characters $segments = $relativeUrl -split '/' $encodedSegments = $segments | ForEach-Object { [uri]::EscapeDataString($_) } $encodedPath = ($encodedSegments -join '/') $loc = "$BaseUrl$encodedPath" $urlElem = $xml.CreateElement('url', $ns) $locElem = $xml.CreateElement('loc', $ns) $locElem.InnerText = $loc $urlElem.AppendChild($locElem) | Out-Null # Optional lastmod (UTC ISO 8601) $lastModElem = $xml.CreateElement('lastmod', $ns) $lastModElem.InnerText = $file.LastWriteTimeUtc.ToString('yyyy-MM-ddTHH:mm:ss+00:00') $urlElem.AppendChild($lastModElem) | Out-Null $urlset.AppendChild($urlElem) | Out-Null } # Ensure output directory exists $outDir = Split-Path -Parent $OutputPath if (-not (Test-Path -LiteralPath $outDir)) { New-Item -ItemType Directory -Path $outDir -Force | Out-Null } # Save the sitemap $xml.Save($OutputPath) Write-Host "Sitemap generated at: $OutputPath" -ForegroundColor Green