New-Module.psm1
function New-Module { [CmdletBinding()] param( [Parameter(Mandatory)] [string]$Name, [switch]$UseDefaultsFile ) $version = "0.0.1" # — Resolve user Modules folder $delim = if ($env:PSModulePath -like "*;*") { ';' } else { ':' } $moduleRoot = ($env:PSModulePath -split $delim | Where-Object { [IO.Directory]::Exists($_) -and ($_ -match "Documents") }) | Select-Object -First 1 if (-not $moduleRoot) { Write-Error "❌ Cannot find a writable user Modules folder under Documents." return } $root = Join-Path $moduleRoot $Name $modulePath = Join-Path $root $version Write-Host "🔍 Checking if '$Name' exists locally at $root..." if (Test-Path $root) { Write-Warning "❌ A folder for '$Name' already exists." return } Write-Host "🔍 Checking PowerShell Gallery for module '$Name'..." if (Find-Module -Name $Name -ErrorAction SilentlyContinue) { Write-Warning "⚠️ A module named '$Name' already exists on PSGallery." return } Write-Host "📁 Creating folder structure: $modulePath" New-Item -Path $modulePath -ItemType Directory -Force | Out-Null $psm1 = Join-Path $modulePath "$Name.psm1" Write-Host "📝 Stubbing out $Name.psm1" Set-Content -Path $psm1 -Value "# $Name module code goes here`n" # — Load metadata if requested $meta = $null if ($UseDefaultsFile) { $defaultsPath = Join-Path $PSScriptRoot "defaults.json" Write-Host "🔎 Looking for defaults.json at $defaultsPath" if (Test-Path $defaultsPath) { Write-Host "📖 Parsing defaults.json" $meta = Get-Content $defaultsPath -Raw | ConvertFrom-Json } else { Write-Warning "⚠️ defaults.json not found. Skipping metadata." } } # — Generate the PSD1 $psd1 = Join-Path $modulePath "$Name.psd1" Write-Host "📄 Generating manifest: $psd1" if ($meta) { New-ModuleManifest -Path $psd1 ` -RootModule "$Name.psm1" ` -ModuleVersion $version ` -Author $meta.Author ` -CompanyName $meta.CompanyName ` -Description $meta.Description ` -PowerShellVersion $meta.PowerShellVersion ` -Copyright $meta.Copyright } else { New-ModuleManifest -Path $psd1 ` -RootModule "$Name.psm1" ` -ModuleVersion $version } Write-Host "`n✅ Module '$Name' created at $modulePath`n" } |