powershell 在不执行脚本的情况下对脚本进行点源化

c9qzyr3d  于 2023-06-23  发布在  Shell
关注(0)|答案(5)|浏览(214)

在PowerShell中是否可以在不执行脚本函数的情况下以某种方式进行点源代码或重用脚本函数?我尝试重用脚本的功能,而不执行脚本本身。我可以把函数分解成一个只包含函数的文件,但我尽量避免这样做。

    • 点源文件示例:**
  1. function doA
  2. {
  3. Write-Host "DoAMethod"
  4. }
  5. Write-Host "reuseme.ps1 main."
    • 消耗文件示例:**
  1. . ".\reuseme.ps1"
  2. Write-Host "consume.ps1 main."
  3. doA
    • 执行结果:**
  1. reuseme.ps1 main.
  2. consume.ps1 main.
  3. DoAMethod
    • 期望结果:**
  1. consume.ps1 main.
  2. DoAMethod
mwg9r5ms

mwg9r5ms1#

您必须执行函数定义以使它们可用。这是没有办法的事。
你可以尝试在文件中抛出PowerShell解析器,只执行函数定义,但我想更简单的方法是将可重用部分构建为模块或简单地构建为除了声明函数之外不做任何事情的脚本。
为了记录在案,一个粗略的测试脚本可以做到这一点:

  1. $file = 'foo.ps1'
  2. $tokens = @()
  3. $errors = @()
  4. $result = [System.Management.Automation.Language.Parser]::ParseFile($file, [ref]$tokens, [ref]$errors)
  5. $tokens | %{$s=''; $braces = 0}{
  6. if ($_.TokenFlags -eq 'Keyword' -and $_.Kind -eq 'Function') {
  7. $inFunction = $true
  8. }
  9. if ($inFunction) { $s += $_.Text + ' ' }
  10. if ($_.TokenFlags -eq 'ParseModeInvariant' -and $_.Kind -eq 'LCurly') {
  11. $braces++
  12. }
  13. if ($_.TokenFlags -eq 'ParseModeInvariant' -and $_.Kind -eq 'RCurly') {
  14. $braces--
  15. if ($braces -eq 0) {
  16. $inFunction = $false;
  17. }
  18. }
  19. if (!$inFunction -and $s -ne '') {
  20. $s
  21. $s = ''
  22. }
  23. } | iex

如果脚本中声明的函数引用脚本参数(因为脚本的参数块不包括在内),您将遇到问题。可能还有一大堆其他的问题会发生,我现在想不起来。我最好的建议仍然是区分可重用的库脚本和打算调用的脚本。

展开查看全部
pwuypxnk

pwuypxnk2#

在你的函数后面,Write-Host "reuseme.ps1 main."行被称为"过程代码"(即,它不在函数内)。您可以通过将此过程代码 Package 在IF语句中来告诉脚本不要运行此过程代码,该IF语句计算$MyInvocation.InvocationName-ne "."
$MyInvocation.InvocationName查看脚本是如何被调用的,如果您使用点(.)来点源化脚本,它将忽略过程代码。如果运行/调用脚本时不带点(.),则它将执行过程代码。示例如下:

  1. function doA
  2. {
  3. Write-Host "DoAMethod"
  4. }
  5. If ($MyInvocation.InvocationName -ne ".")
  6. {
  7. Write-Host "reuseme.ps1 main."
  8. }

因此,当您正常运行脚本时,您将看到输出。当您点源化脚本时,您将看不到输出;但是,函数(而不是过程代码)将被添加到当前范围。

cidc1ykv

cidc1ykv3#

重用代码的最佳方法是将函数放在PowerShell模块中。只需创建一个包含所有函数的文件,并将其扩展名设置为.psm1。然后导入模块以使所有功能可用。例如,reuseme.psm1

  1. function doA
  2. {
  3. Write-Host "DoAMethod"
  4. }
  5. Write-Host "reuseme.ps1 main."

然后,在任何脚本中,你想使用你的函数模块,

  1. # If you're using PowerShell 2, you have to set $PSScriptRoot yourself:
  2. # $PSScriptRoot = Split-Path -Parent -Path $MyInvocation.MyCommand.Definition
  3. Import-Module -Name (Join-Path $PSScriptRoot reuseme.psm1 -Resolve)
  4. doA
z4iuyo4d

z4iuyo4d4#

在进一步寻找这个问题的解决方案时,我发现了一个解决方案,它几乎是Aaron回答中提示的后续。意图有点不同,但可以用来达到同样的结果。
这是我的发现:https://virtualengine.co.uk/2015/testing-private-functions-with-pester/
在使用Pester进行一些测试时需要它,我希望避免在为逻辑编写任何测试之前更改文件的结构。
它工作得很好,让我有信心在重构文件结构之前先为逻辑编写一些测试,这样我就不必再对函数进行点源化。

  1. Describe "SomeFunction" {
  2. # Import the ‘SomeFunction’ function into the current scope
  3. . (Get-FunctionDefinition Path $scriptPath Function SomeFunction)
  4. It "executes the function without executing the script" {
  5. SomeFunction | Should Be "fooBar"
  6. }
  7. }

Get-FunctionDefinition的代码

  1. #Requires -Version 3
  2. <#
  3. .SYNOPSIS
  4. Retrieves a function's definition from a .ps1 file or ScriptBlock.
  5. .DESCRIPTION
  6. Returns a function's source definition as a Powershell ScriptBlock from an
  7. external .ps1 file or existing ScriptBlock. This module is primarily
  8. intended to be used to test private/nested/internal functions with Pester
  9. by dot-sourcsing the internal function into Pester's scope.
  10. .PARAMETER Function
  11. The source function's name to return as a [ScriptBlock].
  12. .PARAMETER Path
  13. Path to a Powershell script file that contains the source function's
  14. definition.
  15. .PARAMETER LiteralPath
  16. Literal path to a Powershell script file that contains the source
  17. function's definition.
  18. .PARAMETER ScriptBlock
  19. A Powershell [ScriptBlock] that contains the function's definition.
  20. .EXAMPLE
  21. If the following functions are defined in a file named 'PrivateFunction.ps1'
  22. function PublicFunction {
  23. param ()
  24. function PrivateFunction {
  25. param ()
  26. Write-Output 'InnerPrivate'
  27. }
  28. Write-Output (PrivateFunction)
  29. }
  30. The 'PrivateFunction' function can be tested with Pester by dot-sourcing
  31. the required function in the either the 'Describe', 'Context' or 'It'
  32. scopes.
  33. Describe "PrivateFunction" {
  34. It "tests private function" {
  35. ## Import the 'PrivateFunction' definition into the current scope.
  36. . (Get-FunctionDefinition -Path "$here\$sut" -Function PrivateFunction)
  37. PrivateFunction | Should BeExactly 'InnerPrivate'
  38. }
  39. }
  40. .LINK
  41. https://virtualengine.co.uk/2015/testing-private-functions-with-pester/
  42. #>
  43. function Get-FunctionDefinition {
  44. [CmdletBinding(DefaultParameterSetName='Path')]
  45. [OutputType([System.Management.Automation.ScriptBlock])]
  46. param (
  47. [Parameter(Position = 0,
  48. ValueFromPipeline = $true,
  49. ValueFromPipelineByPropertyName = $true,
  50. ParameterSetName='Path')]
  51. [ValidateNotNullOrEmpty()]
  52. [Alias('PSPath','FullName')]
  53. [System.String] $Path = (Get-Location -PSProvider FileSystem),
  54. [Parameter(Position = 0,
  55. ValueFromPipelineByPropertyName = $true,
  56. ParameterSetName = 'LiteralPath')]
  57. [ValidateNotNullOrEmpty()]
  58. [System.String] $LiteralPath,
  59. [Parameter(Position = 0,
  60. ValueFromPipeline = $true,
  61. ParameterSetName = 'ScriptBlock')]
  62. [ValidateNotNullOrEmpty()]
  63. [System.Management.Automation.ScriptBlock] $ScriptBlock,
  64. [Parameter(Mandatory = $true,
  65. Position =1,
  66. ValueFromPipelineByPropertyName = $true)]
  67. [Alias('Name')]
  68. [System.String] $Function
  69. )
  70. begin {
  71. if ($PSCmdlet.ParameterSetName -eq 'Path') {
  72. $Path = $ExecutionContext.SessionState.Path.GetUnresolvedProviderPathFromPSPath($Path);
  73. }
  74. elseif ($PSCmdlet.ParameterSetName -eq 'LiteralPath') {
  75. ## Set $Path reference to the literal path(s)
  76. $Path = $LiteralPath;
  77. }
  78. } # end begin
  79. process {
  80. $errors = @();
  81. $tokens = @();
  82. if ($PSCmdlet.ParameterSetName -eq 'ScriptBlock') {
  83. $ast = [System.Management.Automation.Language.Parser]::ParseInput($ScriptBlock.ToString(), [ref] $tokens, [ref] $errors);
  84. }
  85. else {
  86. $ast = [System.Management.Automation.Language.Parser]::ParseFile($Path, [ref] $tokens, [ref] $errors);
  87. }
  88. [System.Boolean] $isFunctionFound = $false;
  89. $functions = $ast.FindAll({ $args[0] -is [System.Management.Automation.Language.FunctionDefinitionAst] }, $true);
  90. foreach ($f in $functions) {
  91. if ($f.Name -eq $Function) {
  92. Write-Output ([System.Management.Automation.ScriptBlock]::Create($f.Extent.Text));
  93. $isFunctionFound = $true;
  94. }
  95. } # end foreach function
  96. if (-not $isFunctionFound) {
  97. if ($PSCmdlet.ParameterSetName -eq 'ScriptBlock') {
  98. $errorMessage = 'Function "{0}" not defined in script block.' -f $Function;
  99. }
  100. else {
  101. $errorMessage = 'Function "{0}" not defined in "{1}".' -f $Function, $Path;
  102. }
  103. Write-Error -Message $errorMessage;
  104. }
  105. } # end process
  106. } #end function Get-Function
展开查看全部
ct2axkht

ct2axkht5#

下面是一个简单的方法,将函数从另一个文件导入到当前范围,而不执行该文件。在使用Pester进行单元测试时非常有用。

  1. function Get-Functions($filePath)
  2. {
  3. $script = Get-Command $filePath
  4. return $script.ScriptBlock.AST.FindAll({ $args[0] -is [Management.Automation.Language.FunctionDefinitionAst] }, $false)
  5. }
  6. Get-Functions ScriptPath.ps1 | Invoke-Expression

这是通过直接调用PowerShell解析器来实现的,就像前面的答案一样。
Answer的灵感来自于这条线索:Is there a way to show all functions in a PowerShell script?

相关问题