forked from ztrhgf/useful_powershell_functions
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Export-ScriptsToModule.ps1
387 lines (322 loc) · 15.2 KB
/
Export-ScriptsToModule.ps1
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
function Export-Scripts2Module {
<#
.SYNOPSIS
Function for generating Powershell module from ps1 scripts (that contains definition of functions) that are stored in given folder.
Generated module will also contain function aliases (no matter if they are defined using Set-Alias or [Alias("Some-Alias")].
Every script file has to have exactly same name as function that is defined inside it (ie Get-LoggedUsers.ps1 contains just function Get-LoggedUsers).
In console where you call this function, font that can show UTF8 chars has to be set!
.PARAMETER configHash
Hash in specific format, where key is path to folder with scripts and value is path to which module should be generated.
e.g.: @{"C:\temp\scripts" = "C:\temp\Modules\Scripts"}
.PARAMETER enc
Which encoding should be used.
Default is UTF8.
.PARAMETER includeUncommitedUntracked
Export also uncommited and untracked files. Only available if scripts are stored in GIT repository.
.PARAMETER dontIncludeRequires
Switch that will lead to ignoring all #requires in scripts, so generated module won't contain them.
Otherwise just module #requires will be added.
.PARAMETER markAutoGenerated
Switch will add comment '# _AUTO_GENERATED_' on first line of each module, that was created by this function.
For internal use, so I can distinguish which modules was created from functions stored in scripts2module and therefore easily generate various reports.
.EXAMPLE
Export-Scripts2Module -configHash @{"C:\PS\Scripts" = "C:\PS\modules\Scripts"}
From ps1 scripts in "C:\PS\Scripts" extract PowerShell functions and export them to module "C:\PS\modules\Scripts".
.EXAMPLE
Export-Scripts2Module -configHash @{"C:\PS\Scripts" = "C:\PS\modules\Scripts"; "C:\PS\HelperScripts" = "C:\PS\modules\HelperScripts"}
From ps1 scripts in "C:\PS\Scripts" extract PowerShell functions and export them to module "C:\PS\modules\Scripts". Same goes for "C:\PS\HelperScripts"
.NOTES
Author: Ondřej Šebela - [email protected]
#>
[CmdletBinding()]
param (
[ValidateNotNullOrEmpty()]
[hashtable] $configHash
,
[ValidateNotNullOrEmpty()]
[string] $enc = 'utf8'
,
[switch] $includeUncommitedUntracked
,
[switch] $dontIncludeRequires
,
[switch] $markAutoGenerated
)
#region functions
function _checkSyntax {
[CmdletBinding()]
param ($file)
$syntaxError = @()
[void][System.Management.Automation.Language.Parser]::ParseFile($file, [ref]$null, [ref]$syntaxError)
return $syntaxError
} # end of _checkSyntax
function _startProcess {
[CmdletBinding()]
param (
[string] $filePath = ''
,
[string] $argumentList = ''
,
[string] $workingDirectory = (Get-Location)
,
[switch] $dontWait
,
# lot of git commands output verbose output to error stream
[switch] $outputErr2Std
)
$p = New-Object System.Diagnostics.Process
$p.StartInfo.UseShellExecute = $false
$p.StartInfo.RedirectStandardOutput = $true
$p.StartInfo.RedirectStandardError = $true
$p.StartInfo.WorkingDirectory = $workingDirectory
$p.StartInfo.FileName = $filePath
$p.StartInfo.Arguments = $argumentList
[void]$p.Start()
if (!$dontWait) {
$p.WaitForExit()
}
$p.StandardOutput.ReadToEnd()
if ($outputErr2Std) {
$p.StandardError.ReadToEnd()
} else {
if ($err = $p.StandardError.ReadToEnd()) {
Write-Error $err
}
}
} # end of _startProcess
function _generatePSModule {
[CmdletBinding()]
param (
[Parameter(Mandatory = $true)]
[ValidateNotNullOrEmpty()]
[string] $scriptFolder
,
[Parameter(Mandatory = $true)]
[ValidateNotNullOrEmpty()]
[string] $moduleFolder
,
[string] $enc
,
[switch] $includeUncommitedUntracked
,
[switch] $dontIncludeRequires
,
[switch] $markAutoGenerated
)
$ErrorActionPreference = "Stop"
if (!(Test-Path $scriptFolder)) {
throw "Path $scriptFolder is not accessible"
}
$modulePath = Join-Path $moduleFolder ((Split-Path $moduleFolder -Leaf) + ".psm1")
$function2Export = @()
$alias2Export = @()
$lastCommitFileContent = @{}
$location = Get-Location
Set-Location $scriptFolder
$unfinishedFile = @()
try {
# uncommited changed files
$unfinishedFile += @(_startProcess git -arg "ls-files -m --full-name")
# untracked files
$unfinishedFile += @(_startProcess git -arg "ls-files --others --exclude-standard --full-name")
} catch {
if ($_ -match "fatal: not a git repository") {
Write-Warning "'$scriptFolder' isn't GIT repository, therefore files will be used exactly as they are, so make sure, that they are in consistent state"
} elseif ($_ -match "The system cannot find the file specified") {
Write-Verbose "GIT isn't installed"
}
}
Set-Location $location
#
# there are untracked and/or uncommited files
# instead just ignoring them try to get and use previous version from GIT
if ($unfinishedFile) {
[System.Collections.ArrayList] $unfinishedFile = @($unfinishedFile)
Set-Location $scriptFolder
$unfinishedFile2 = $unfinishedFile.Clone()
$unfinishedFile2 | % {
$file = $_
$lastCommitContent = _startProcess git "show HEAD:$file" -dontWait # don't wait because if git show HEAD:$file returned anything, process stuck
if (!$lastCommitContent -or $lastCommitContent -match "^fatal: ") {
Write-Warning "Skipping changed but uncommited/untracked file: $file"
} else {
$fName = [System.IO.Path]::GetFileNameWithoutExtension($file)
Write-Warning "$fName has uncommited changed. For module generating I will use its version from previous commit"
$lastCommitFileContent.$fName = $lastCommitContent
$unfinishedFile.Remove($file)
}
}
Set-Location $location
# unix / replace by \
$unfinishedFile = $unfinishedFile -replace "/", "\"
$unfinishedFileName = $unfinishedFile | % { [System.IO.Path]::GetFileName($_) }
if ($includeUncommitedUntracked -and $unfinishedFileName) {
Write-Warning "Exporting changed but uncommited/untracked functions: $($unfinishedFileName -join ', ')"
$unfinishedFile = @()
}
}
#
# in ps1 files to export leave just these in consistent state
$script2Export = (Get-ChildItem (Join-Path $scriptFolder "*.ps1") -File).FullName | where {
$partName = ($_ -split "\\")[-2..-1] -join "\"
if ($unfinishedFile -and $unfinishedFile -match [regex]::Escape($partName)) {
return $false
} else {
return $true
}
}
if (!$script2Export -and $lastCommitFileContent.Keys.Count -eq 0) {
throw "In $scriptFolder there is none usable function to export to $moduleFolder"
}
if (Test-Path $modulePath -ErrorAction SilentlyContinue) {
Write-Verbose "Removing $moduleFolder"
Remove-Item $moduleFolder -Recurse -Confirm:$false -ErrorAction SilentlyContinue
Start-Sleep 1
}
[Void][System.IO.Directory]::CreateDirectory($moduleFolder)
Write-Verbose "To $modulePath`n"
# to hash $lastCommitFileContent add pair, where key is name of the function and value is its text definition
$script2Export | % {
$script = $_
$ast = [System.Management.Automation.Language.Parser]::ParseFile($script, [ref] $null, [ref] $null)
# just END block should exist
if ($ast.BeginBlock -or $ast.ProcessBlock) {
throw "File $script isn't in correct format. It has to contain just function definition (+ alias definition, comment or requires)!"
}
# get function definition
$functionDefinition = $ast.FindAll( {
param([System.Management.Automation.Language.Ast] $ast)
$ast -is [System.Management.Automation.Language.FunctionDefinitionAst] -and
# Class methods have a FunctionDefinitionAst under them as well, but we don't want them.
($PSVersionTable.PSVersion.Major -lt 5 -or
$ast.Parent -isnot [System.Management.Automation.Language.FunctionMemberAst])
}, $false)
if ($functionDefinition.count -ne 1) {
throw "File $script doesn't contain any function or contains more than one."
}
# get function name from its AST definition
$fName = $functionDefinition.name
# add function content only in case it isn't added already (to avoid overwrites)
if (!$lastCommitFileContent.containsKey($fName)) {
# use function definition obtained by AST to generating module
# this way no possible dangerous content will be added
$content = ""
if (!$dontIncludeRequires) {
# adding module requires
$requiredModules = $ast.scriptRequirements.requiredModules.name
if ($requiredModules) {
$content += "#Requires -Modules $($requiredModules -join ',')`n`n"
}
}
# replace invalid chars for valid (en dash etc)
$functionText = $functionDefinition.extent.text -replace [char]0x2013, "-" -replace [char]0x2014, "-"
# add function text definition
$content += $functionText
# add aliases defined by Set-Alias
$ast.EndBlock.Statements | ? { $_ -match "^\s*Set-Alias .+" -and $_ -match [regex]::Escape($functionDefinition.name) } | % { $_.extent.text } | % {
$parts = $_ -split "\s+"
$content += "`n$_"
if ($_ -match "-na") {
# alias set by named parameter
# get parameter value
$i = 0
$parPosition
$parts | % {
if ($_ -match "-na") {
$parPosition = $i
}
++$i
}
# save alias for later export
$alias2Export += $parts[$parPosition + 1]
Write-Verbose "- exporting alias: $($parts[$parPosition + 1])"
} else {
# alias set by positional parameter
# save alias for later export
$alias2Export += $parts[1]
Write-Verbose "- exporting alias: $($parts[1])"
}
}
# add aliases defined by [Alias("Some-Alias")]
$innerAliasDefinition = $ast.FindAll( {
param([System.Management.Automation.Language.Ast] $ast)
$ast -is [System.Management.Automation.Language.AttributeAst]
}, $true) | ? { $_.parent.extent.text -match '^param' } | Select-Object -ExpandProperty PositionalArguments | Select-Object -ExpandProperty Value -ErrorAction SilentlyContinue # filter out aliases for function parameters
if ($innerAliasDefinition) {
$innerAliasDefinition | % {
$alias2Export += $_
Write-Verbose "- exporting 'inner' alias: $_"
}
}
$lastCommitFileContent.$fName = $content
}
}
if ($markAutoGenerated) {
"# _AUTO_GENERATED_" | Out-File $modulePath $enc
"" | Out-File $modulePath -Append $enc
}
#
# save all functions content to module file
# store name of every funtion for later use in Export-ModuleMember
$lastCommitFileContent.GetEnumerator() | % {
$fName = $_.Key
$content = $_.Value
Write-Verbose "- exporting function: $fName"
$function2Export += $fName
$content | Out-File $modulePath -Append $enc
"" | Out-File $modulePath -Append $enc
}
#
# set what functions and aliases should be exported from module
# explicit export is much faster than use *
if (!$function2Export) {
throw "There are none functions to export! Wrong path??"
} else {
if ($function2Export -match "#") {
Remove-Item $modulePath -Recurse -Force -Confirm:$false
throw "Exported function contains unapproved character # in it's name. Module was removed."
}
$function2Export = $function2Export | Select-Object -Unique | Sort-Object
"Export-ModuleMember -function $($function2Export -join ', ')" | Out-File $modulePath -Append $enc
}
if ($alias2Export) {
if ($alias2Export -match "#") {
Remove-Item $modulePath -Recurse -Force -Confirm:$false
throw "Exported alias contains unapproved character # in it's name. Module was removed."
}
$alias2Export = $alias2Export | Select-Object -Unique | Sort-Object
"`nExport-ModuleMember -alias $($alias2Export -join ', ')" | Out-File $modulePath -Append $enc
}
} # end of _generatePSModule
#endregion functions
Write-Output "Generating module"
$configHash.GetEnumerator() | % {
$scriptFolder = $_.key
$moduleFolder = $_.value
$param = @{
scriptFolder = $scriptFolder
moduleFolder = $moduleFolder
enc = $enc
verbose = $VerbosePreference
}
if ($includeUncommitedUntracked) {
$param.includeUncommitedUntracked = $true
}
if ($dontIncludeRequires) {
$param.dontIncludeRequires = $true
}
if ($markAutoGenerated) {
$param.markAutoGenerated = $true
}
Write-Output " - $(Split-Path $moduleFolder -Leaf)"
_generatePSModule @param
# check generated module syntax
Get-ChildItem $moduleFolder -File -Recurse | % {
$file = $_.FullName
$syntaxError = _checkSyntax $file
if ($syntaxError) {
throw "In module file $file were found these syntax problems:`n$syntaxError"
}
}
}
}