Prism.psm1
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 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 |
# Copyright WebMD Health Services # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License #Requires -Version 5.1 Set-StrictMode -Version 'Latest' # Functions should use $moduleRoot as the relative root from which to find # things. A published module has its function appended to this file, while a # module in development has its functions in the Functions directory. $moduleRoot = $PSScriptRoot # Store each of your module's functions in its own file in the Functions # directory. On the build server, your module's functions will be appended to # this file, so only dot-source files that exist on the file system. This allows # developers to work on a module without having to build it first. Grab all the # functions that are in their own files. $functionsPath = Join-Path -Path $moduleRoot -ChildPath 'Functions\*.ps1' if( (Test-Path -Path $functionsPath) ) { foreach( $functionPath in (Get-Item $functionsPath) ) { . $functionPath.FullName } } function Get-PackageManagementPreference { [CmdletBinding()] param( ) Set-StrictMode -Version 'Latest' Use-CallerPreference -Cmdlet $PSCmdlet -SessionState $ExecutionContext.SessionState $deepPrefs = @{} if( (Test-Path -Path 'env:PRISM_DISABLE_DEEP_DEBUG') -and ` 'Continue' -in @($Global:DebugPreference, $DebugPreference) ) { $deepPrefs['Debug'] = $false } if( (Test-Path -Path 'env:PRISM_DISABLE_DEEP_VERBOSE') -and ` 'Continue' -in @($Global:VerbosePreference, $VerbosePreference)) { $deepPrefs['Verbose'] = $false } return $deepPrefs } # Ugh. I hate this name, but it interferes with Install-Module in one of the package management modules. function Install-PrivateModule { [CmdletBinding()] param( [Parameter(Mandatory, ValueFromPipeline)] [Object] $Configuration ) begin { Set-StrictMode -Version 'Latest' Use-CallerPreference -Cmdlet $PSCmdlet -SessionState $ExecutionContext.SessionState $pkgMgmtPrefs = Get-PackageManagementPreference } process { if( -not (Test-Path -Path $Configuration.LockPath) ) { $Configuration | Update-ModuleLock | Format-Table } $repoByLocation = @{} Get-PSRepository | ForEach-Object { $repoUrl = $_.SourceLocation $repoByLocation[$repoUrl] = $_.Name # Ignore slashes at the end of URLs. $trimmedRepoUrl = $repoUrl.TrimEnd('/') $repoByLocation[$trimmedRepoUrl] = $_.Name } $privateModulePathWildcard = Join-Path -Path $config.PSModulesPath -ChildPath '*' $locks = Get-Content -Path $Configuration.LockPath | ConvertFrom-Json $locks | Add-Member -Name 'PSModules' -MemberType NoteProperty -Value @() -ErrorAction Ignore foreach( $module in $locks.PSModules ) { $installedModules = Get-Module -Name $module.name -ListAvailable -ErrorAction Ignore | Where-Object 'Path' -Like $privateModulePathWildcard | Add-Member -Name 'SemVer' -MemberType ScriptProperty -PassThru -Value { $prerelease = $this.PrivateData['PSData']['PreRelease'] if( $prerelease ) { $prerelease = "-$($prerelease)" } return "$($this.Version)$($prerelease)" } $savePath = Join-Path -Path $Configuration.File.DirectoryName -ChildPath $Configuration.PSModulesDirectoryName $installedModule = $installedModules | Where-Object SemVer -EQ $module.version if( -not $installedModule ) { $sourceUrl = $module.repositorySourceLocation $repoName = $repoByLocation[$sourceUrl] if( -not $repoName ) { # Ignore slashes at the end of URLs. $sourceUrl = $sourceUrl.TrimEnd('/') } $repoName = $repoByLocation[$sourceUrl] if( -not $repoName ) { $msg = "PowerShell repository at ""$($module.repositorySourceLocation)"" does not exist. Use " + '"Get-PSRepository" to see the current list of repositories, "Register-PSRepository" ' + 'to add a new repository, or "Set-PSRepository" to update an existing repository.' Write-Error $msg continue } if( -not (Test-Path -Path $savePath) ) { New-Item -Path $savePath -ItemType 'Directory' -Force | Out-Null } Save-Module -Name $module.name ` -Path $savePath ` -RequiredVersion $module.version ` -AllowPrerelease ` -Repository $repoName ` @pkgMgmtPrefs } $modulePath = Join-Path -Path $savePath -ChildPath $module.name | Resolve-Path -Relative $installedModule = [pscustomobject]@{ Name = $module.name; Version = $module.version; Path = $modulePath; RepositorySourceLocation = $module.repositorySourceLocation; } $installedModule.pstypenames.Add('Prism.InstalledModule') $installedModule | Write-Output } } } function Invoke-Prism { <# .SYNOPSIS Invokes Prism. .DESCRIPTION A tool similar to nuget but for PowerShell modules. A config file in the root of a repository that specifies what modules should be installed into the PSModules directory of the repository. If a path is provided for the module it will be installed at the specified path instead of the PSModules directory. .EXAMPLE Invoke-Prism 'install' Demonstrates how to call this function to install required PSModules. #> [CmdletBinding()] param( [Parameter(Mandatory)] [ValidateSet('install', 'update')] [String] $Command, # The path to a prism.json file or a directory where Prism can find a prism.json file. If path is to a file, # the "FileName" parameter is ignored, if given. # # If the path is a directory, Prism will look for a "prism.json' file in that directory. If the -Recurse switch # is given and the path is to a directory, Prism will recursively search in and under that directory and run for # each prism.json file it finds. If Path is to a directory and FileName is given, Prism will look for a file # with that name instead. [Parameter(ValueFromPipeline, ValueFromPipelineByPropertyName)] [Alias('FullName')] [String] $Path, # The name of the Prism configuration file to use. Defaults to `prism.json`. Ignored if "Path" is given and is # the path to a file. [String] $FileName = 'prism.json', # If given, searches the current directory and all sub-directories for prism.json files and runs the command # for each file. If the Path parameter is given and is to a directory, Prism will start searching in that # directory instead of the current directory. [switch] $Recurse ) begin { Set-StrictMode -Version 'Latest' Use-CallerPreference -Cmdlet $PSCmdlet -SessionState $ExecutionContext.SessionState $origModulePath = $env:PSModulePath $pkgMgmtPrefs = Get-PackageManagementPreference Import-Module -Name 'PackageManagement' ` -MinimumVersion '1.3.2' ` -MaximumVersion '1.4.8.1' ` -Global ` -ErrorAction Stop ` @pkgMgmtPrefs Import-Module -Name 'PowerShellGet' ` -MinimumVersion '2.0.0' ` -MaximumVersion '2.2.5' ` -Global ` -ErrorAction Stop ` @pkgMgmtPrefs } process { try { $startIn = '.' if( $Path ) { if( (Test-Path -Path $Path -PathType Leaf) ) { $FileName = $Path | Split-Path -Leaf $startIn = $Path | Split-Path -Parent } elseif( (Test-Path -Path $Path -PathType Container) ) { $startIn = $Path } else { Write-Error -Message "Path ""$($Path)"" does not exist." return } } $Force = $FileName.StartsWith('.') $prismJsonFiles = Get-ChildItem -Path $startIn -Filter $FileName -Recurse:$Recurse -Force:$Force -ErrorAction Ignore if( -not $prismJsonFiles ) { $msg = '' $suffix = '' if( $Recurse ) { $suffix = 's' $msg = ' or any of its sub-directories' } $locationMsg = 'the current directory' if( $startIn -ne '.' -and $startIn -ne (Get-Location).Path ) { $locationMsg = """$($startIn | Resolve-Path -Relative)""" } $msg = "No $($FileName) file$($suffix) found in $($locationMsg)$($msg)." Write-Error -Message $msg -ErrorAction Stop return } foreach( $prismJsonFile in $prismJsonFiles ) { $prismJsonPath = $prismJsonFile.FullName $config = Get-Content -Path $prismJsonPath | ConvertFrom-Json if( -not $config ) { Write-Warning "File ""$($prismJsonPath | Resolve-Path -Relative) is empty." continue } $lockBaseName = [IO.Path]::GetFileNameWithoutExtension($prismJsonPath) $lockExtension = [IO.Path]::GetExtension($prismJsonPath) # Hidden file with no extension, e.g. `.prism` if( -not $lockBaseName -and $lockExtension ) { $lockBaseName = $lockExtension $lockExtension = '' } $ignore = @{ 'ErrorAction' = 'Ignore' } # public configuration that users can customize. # Add-Member doesn't return an object if the member already exists, so these can't be part of one pipeline. $config | Add-Member -Name 'PSModules' -MemberType NoteProperty -Value @() @ignore $config | Add-Member -Name 'PSModulesDirectoryName' -MemberType NoteProperty -Value 'PSModules' @ignore $privateModulePath = Join-Path -Path $prismJsonFile.DirectoryName -ChildPath $config.PSModulesDirectoryName $lockPath = Join-Path -Path ($prismJsonPath | Split-Path -Parent) -ChildPath "$($lockBaseName).lock$($lockExtension)" $addMemberArgs = @{ MemberType = 'NoteProperty'; PassThru = $true; # Force so users can't customize these properties. Force = $true; } # Members that users aren't allowed to customize/override. $config | Add-Member -Name 'Path' -Value $prismJsonPath @addMemberArgs | Add-Member -Name 'File' -Value $prismJsonFile @addMemberArgs | Add-Member -Name 'LockPath' -Value $lockPath @addMemberArgs | Add-Member -Name 'PSModulesPath' -Value $privateModulePath @addMemberArgs | Out-Null # This makes it so we can use PowerShell's module cmdlets as much as possible. $privateModulePath = & { # Prism's private module path, PSModules. $config.PSModulesPath | Write-Output # PackageManagement needs to be able to find and load PowerShellGet so it can get repositoriees, # package sources, etc, so it and PowerShellGet have to be in PSModulePath, unfortunately. Get-Module -Name 'PackageManagement','PowerShellGet' | Select-Object -ExpandProperty 'Path' | # **\PSModules\MODULE\VERSION\MODULE.psd1 Split-Path -Parent | # **\PSModules\MODULE\VERSION Split-Path -Parent | # **\PSModules\MODULE Split-Path -Parent | # **\PSModules Select-Object -Unique | Write-Output } $env:PSModulePath = $privateModulePath -join [IO.Path]::PathSeparator Write-Debug -Message "env:PSModulePath $($env:PSModulePath)" switch( $Command ) { 'install' { $config | Install-PrivateModule } 'update' { $config | Update-ModuleLock } } } } finally { $env:PSModulePath = $origModulePath } } } Set-Alias -Name 'prism' -Value 'Invoke-Prism' function Select-Module { [CmdletBinding()] param( [Parameter(Mandatory, ValueFromPipeline)] [Object] $Module, [Parameter(Mandatory)] [String] $Name, [String] $Version, [switch] $AllowPrerelease ) process { if( $Module.Name -ne $Name ) { return } if( $Version -and $Module.Version -notlike $Version ) { return } if( $AllowPrerelease ) { return $Module } [Version]$moduleVersion = $null if( [Version]::TryParse($Module.Version, [ref]$moduleVersion) ) { return $Module } } } function Update-ModuleLock { [CmdletBinding()] param( [Parameter(Mandatory, ValueFromPipeline)] [Object] $Configuration ) begin { Set-StrictMode -Version 'Latest' Use-CallerPreference -Cmdlet $PSCmdlet -SessionState $ExecutionContext.SessionState $pkgMgmtPrefs = Get-PackageManagementPreference } process { $modulesNotFound = [Collections.ArrayList]::New() $moduleNames = $Configuration.PSModules | Select-Object -ExpandProperty 'Name' if( -not $moduleNames ) { Write-Warning "There are no modules listed in ""$($Path | Resolve-Path -Relative)""." return } $numFinds = $moduleNames | Measure-Object | Select-Object -ExpandProperty 'Count' $numFinds = $numFinds + 2 Write-Debug " numSteps $($numFinds)" $curStep = 0 $uniqueModuleNames = $moduleNames | Select-Object -Unique $status = "Find-Module -Name '$($uniqueModuleNames -join "', '")'" $percentComplete = ($curStep++/$numFinds * 100) $activity = @{ Activity = 'Resolving Module Versions' } Write-Progress @activity -Status $status -PercentComplete $percentComplete try { $modules = Find-Module -Name $uniqueModuleNames -ErrorAction Ignore @pkgMgmtPrefs if( -not $modules ) { $msg = "$($Path | Resolve-Path -Relative): Modules ""$($uniqueModuleNames -join '", "')"" not " + 'found.' Write-Error $msg return } # Find-Module is expensive. Limit calls as much as possible. $findModuleCache = @{} $locks = [Collections.ArrayList]::New() $env:PSModulePath = Join-Path -Path $Configuration.File.DirectoryName -ChildPath $Configuration.PSModulesDirectoryName foreach( $pxModule in $Configuration.PSModules ) { $optionalParams = @{} # Make sure these members are present and have default values. $pxModule | Add-Member -Name 'Version' -MemberType NoteProperty -Value '' -ErrorAction Ignore $pxModule | Add-Member -Name 'AllowPrerelease' -MemberType NoteProperty -Value $false -ErrorAction Ignore $versionDesc = 'latest' if( $pxModule.Version ) { $versionDesc = $optionalParams['Version'] = $pxModule.Version } $allowPrerelease = $false if( $pxModule.AllowPrerelease -or $pxModule.Version -match '-' ) { $allowPrerelease = $optionalParams['AllowPrerelease'] = $true } $curStep += 1 Write-Debug " curStep $($curStep)" $moduleToInstall = $modules | Select-Module -Name $pxModule.Name @optionalParams | Select-Object -First 1 if( -not $moduleToInstall ) { $status = "Find-Module -Name '$($pxModule.Name)' -AllVersions" if( $allowPrerelease ) { $status = "$($status) -AllowPrerelease" } if( -not $findModuleCache.ContainsKey($status) ) { Write-Progress @activity -Status $status -PercentComplete ($curStep/$numFinds * 100) $findModuleCache[$status] = Find-Module -Name $pxModule.Name ` -AllVersions ` -AllowPrerelease:$allowPrerelease ` -ErrorAction Ignore ` @pkgMgmtPrefs } $moduleToInstall = $findModuleCache[$status] | Select-Module -Name $pxModule.Name @optionalParams | Select-Object -First 1 } if( -not $moduleToInstall ) { [void]$modulesNotFound.Add($pxModule.Name) continue } $pin = [pscustomobject]@{ name = $moduleToInstall.Name; version = $moduleToInstall.Version; repositorySourceLocation = $moduleToInstall.RepositorySourceLocation; } [void]$locks.Add( $pin ) if( -not (Test-Path -Path $Configuration.LockPath) ) { New-Item -Path $Configuration.LockPath ` -ItemType 'File' ` -Value (([pscustomobject]@{}) | ConvertTo-Json) | Out-Null } $moduleLock = [pscustomobject]@{ ModuleName = $pxModule.Name; Version = $versionDesc; LockedVersion = $pin.version; RepositorySourceLocation = $pin.repositorySourceLocation; Path = ($Configuration.LockPath | Resolve-Path -Relative); } $moduleLock.pstypenames.Add('Prism.ModuleLock') $moduleLock | Write-Output } Write-Progress @activity -Status "Saving lock file ""$($Configuration.LockPath)""." -PercentComplete 100 $prismLock = [pscustomobject]@{ PSModules = $locks; } $prismLock | ConvertTo-Json -Depth 2 | Set-Content -Path $Configuration.LockPath -NoNewline if( $modulesNotFound.Count ) { $suffix = '' if( $modulesNotFound.Count -gt 1 ) { $suffix = 's' } $msg = "$($Path | Resolve-Path -Relative): Module$($suffix) ""$($modulesNotFound -join '", "')"" not " + 'found.' Write-Error $msg } } finally { Write-Progress @activity -Completed } } } function Use-CallerPreference { <# .SYNOPSIS Sets the PowerShell preference variables in a module's function based on the callers preferences. .DESCRIPTION Script module functions do not automatically inherit their caller's variables, including preferences set by common parameters. This means if you call a script with switches like `-Verbose` or `-WhatIf`, those that parameter don't get passed into any function that belongs to a module. When used in a module function, `Use-CallerPreference` will grab the value of these common parameters used by the function's caller: * ErrorAction * Debug * Confirm * InformationAction * Verbose * WarningAction * WhatIf This function should be used in a module's function to grab the caller's preference variables so the caller doesn't have to explicitly pass common parameters to the module function. This function is adapted from the [`Get-CallerPreference` function written by David Wyatt](https://gallery.technet.microsoft.com/scriptcenter/Inherit-Preference-82343b9d). There is currently a [bug in PowerShell](https://connect.microsoft.com/PowerShell/Feedback/Details/763621) that causes an error when `ErrorAction` is implicitly set to `Ignore`. If you use this function, you'll need to add explicit `-ErrorAction $ErrorActionPreference` to every `Write-Error` call. Please vote up this issue so it can get fixed. .LINK about_Preference_Variables .LINK about_CommonParameters .LINK https://gallery.technet.microsoft.com/scriptcenter/Inherit-Preference-82343b9d .LINK http://powershell.org/wp/2014/01/13/getting-your-script-module-functions-to-inherit-preference-variables-from-the-caller/ .EXAMPLE Use-CallerPreference -Cmdlet $PSCmdlet -SessionState $ExecutionContext.SessionState Demonstrates how to set the caller's common parameter preference variables in a module function. #> [CmdletBinding()] param ( [Parameter(Mandatory)] #[Management.Automation.PSScriptCmdlet] # The module function's `$PSCmdlet` object. Requires the function be decorated with the `[CmdletBinding()]` # attribute. $Cmdlet, [Parameter(Mandatory)] # The module function's `$ExecutionContext.SessionState` object. Requires the function be decorated with the # `[CmdletBinding()]` attribute. # # Used to set variables in its callers' scope, even if that caller is in a different script module. [Management.Automation.SessionState]$SessionState ) Set-StrictMode -Version 'Latest' # List of preference variables taken from the about_Preference_Variables and their common parameter name (taken # from about_CommonParameters). $commonPreferences = @{ 'ErrorActionPreference' = 'ErrorAction'; 'DebugPreference' = 'Debug'; 'ConfirmPreference' = 'Confirm'; 'InformationPreference' = 'InformationAction'; 'VerbosePreference' = 'Verbose'; 'WarningPreference' = 'WarningAction'; 'WhatIfPreference' = 'WhatIf'; } foreach( $prefName in $commonPreferences.Keys ) { $parameterName = $commonPreferences[$prefName] # Don't do anything if the parameter was passed in. if( $Cmdlet.MyInvocation.BoundParameters.ContainsKey($parameterName) ) { continue } $variable = $Cmdlet.SessionState.PSVariable.Get($prefName) # Don't do anything if caller didn't use a common parameter. if( -not $variable ) { continue } if( $SessionState -eq $ExecutionContext.SessionState ) { Set-Variable -Scope 1 -Name $variable.Name -Value $variable.Value -Force -Confirm:$false -WhatIf:$false } else { $SessionState.PSVariable.Set($variable.Name, $variable.Value) } } } |