1+ Function Add-MissingCBH {
2+ <#
3+ . SYNOPSIS
4+ Create comment based help for a function.
5+ . DESCRIPTION
6+ Create comment based help for a function.
7+ . PARAMETER Code
8+ Multi-line or piped lines of code to process.
9+ . EXAMPLE
10+ PS > $test = Get-Content 'C:\temp\test.ps1' -raw
11+ PS > $test | Add-MissingCBH | clip
12+
13+ Takes C:\temp\test.ps1 as input, creates basic comment based help and puts the result in the clipboard
14+ to be pasted elsewhere for review.
15+ . NOTES
16+ Author: Zachary Loeber
17+ Site: http://www.the-little-things.net/
18+ Requires: Powershell 3.0
19+
20+ Version History
21+ 1.0.0 - Initial release
22+ 1.0.1 - Updated for ModuleBuild
23+ #>
24+ [CmdletBinding ()]
25+ param (
26+ [parameter (Position = 0 , ValueFromPipeline = $true , HelpMessage = ' Lines of code to process.' )]
27+ [string []]$Code
28+ )
29+
30+ begin {
31+ # CBH pattern that tells us CBH likely already exists
32+ $CBHPattern = " (?ms)(^\s*\<#.*[\.SYNOPSIS|\.DESCRIPTION|\.PARAMETER|\.EXAMPLE|\.NOTES|\.LINK].*?#>)"
33+ $Codeblock = @ ()
34+ }
35+ process {
36+ $Codeblock += $Code
37+ }
38+ end {
39+ $ScriptText = ($Codeblock | Out-String ).trim(" `r`n " )
40+ # If no sign of CBH exists then try to generate and insert it
41+ if ($ScriptText -notmatch $CBHPattern ) {
42+ $CBH = @ ($ScriptText | New-CommentBasedHelp )
43+
44+ if ($CBH.Count -gt 1 ) {
45+ throw ' Too many functions are defined in the input string!'
46+ }
47+
48+ if ($CBH.Count -ne 0 ) {
49+ try {
50+ $currscriptblock = [scriptblock ]::Create($ScriptText )
51+ . $currscriptblock
52+ $currfunct = get-command $CBH.FunctionName
53+ }
54+ catch {
55+ throw $_
56+ }
57+
58+ $UpdatedFunct = ' Function ' + $currfunct.Name + ' {' + " `r`n " + $CBH.CBH + " `r`n " + $currfunct.definition + " `r`n " + ' }'
59+
60+ $UpdatedFunct
61+ }
62+ else {
63+ Write-Warning ' Unable to generate CBH for the script text!'
64+ $ScriptText
65+ }
66+ }
67+ else {
68+ Write-Verbose " Comment based help already exists - skipping CBH insertion and returning original script."
69+ $ScriptText
70+ }
71+ }
72+ }
0 commit comments