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') ) function Convert-PathToUrl { param( [string]$FilePath, [string]$RootPath, [string]$BaseUrl ) $relative = Resolve-Path -Path $FilePath -Relative -RelativeBasePath $RootPath $relative = $relative -replace '\\','/' $url = $BaseUrl.TrimEnd('/') + '/' + $relative.TrimStart('/') return $url } # Ensure root path exists if (-not (Test-Path -LiteralPath $RootPath -PathType Container)) { Write-Error "RootPath '$RootPath' does not exist or is not a directory." exit 1 } # Gather files to include in the sitemap $extensions = '.html', '.htm', '.php', '.asp', '.aspx', '.jsp' $files = Get-ChildItem -Path $RootPath -Recurse -File | Where-Object { $extensions -contains $_.Extension.ToLower() } # Create XML document [xml]$xmlDoc = New-Object System.Xml.XmlDocument $xmlDeclaration = $xmlDoc.CreateXmlDeclaration('1.0','UTF-8',$null) $xmlDoc.AppendChild($xmlDeclaration) | Out-Null $urlset = $xmlDoc.CreateElement('urlset') $xmlnsAttr = $xmlDoc.CreateAttribute('xmlns') $xmlnsAttr.Value = 'http://www.sitemaps.org/schemas/sitemap/0.9' $urlset.Attributes.Append($xmlnsAttr) | Out-Null $xmlDoc.AppendChild($urlset) | Out-Null foreach ($file in $files) { $urlElem = $xmlDoc.CreateElement('url') $locElem = $xmlDoc.CreateElement('loc') $locElem.InnerText = Convert-PathToUrl -FilePath $file.FullName -RootPath $RootPath -BaseUrl $BaseUrl $urlElem.AppendChild($locElem) | Out-Null $lastModElem = $xmlDoc.CreateElement('lastmod') $lastModElem.InnerText = $file.LastWriteTimeUtc.ToString('yyyy-MM-ddTHH:mm:ssZ') $urlElem.AppendChild($lastModElem) | Out-Null # Optional: changefreq and priority (static defaults, can be adjusted later) $changeFreqElem = $xmlDoc.CreateElement('changefreq') $changeFreqElem.InnerText = 'monthly' $urlElem.AppendChild($changeFreqElem) | Out-Null $priorityElem = $xmlDoc.CreateElement('priority') $priorityElem.InnerText = '0.5' $urlElem.AppendChild($priorityElem) | Out-Null $urlset.AppendChild($urlElem) | Out-Null } # Save XML with indentation $settings = New-Object System.Xml.XmlWriterSettings $settings.Indent = $true $settings.Encoding = [System.Text.Encoding]::UTF8 $writer = [System.Xml.XmlWriter]::Create($OutputPath, $settings) $xmlDoc.WriteContentTo($writer) $writer.Flush() $writer.Close() Write-Host "Sitemap generated at: $OutputPath" -ForegroundColor Green