代码之家  ›  专栏  ›  技术社区  ›  Mike Shepard

在powershell中导入“库”

  •  13
  • Mike Shepard  · 技术社区  · 17 年前

    我发现自己正在编写一组处理不同名词(集群、sql Server、一般服务器、文件等)的相关函数,并将每组函数放在单独的文件中(例如,cluster_utils.ps1)。如果需要,我希望能够在我的配置文件中“导入”其中一些库,并在powershell会话中“导入”其他库。我已经编写了两个函数,似乎可以解决这个问题,但由于我只使用了powershell一个月,我想我应该询问一下,是否有任何现有的“最佳实践”类型的脚本可以替代。

    # to load c:\powershellscripts\cluster_utils.ps1 if it isn't already loaded
    . require cluster_utils    
    

    以下是功能:

    $global:loaded_scripts=@{}
    function require([string]$filename){
          if (!$loaded_scripts[$filename]){
               . c:\powershellscripts\$filename.ps1
               $loaded_scripts[$filename]=get-date
         }
    }
    
    function reload($filename){
         . c:\powershellscripts\$filename.ps1
         $loaded_scripts[$filename]=get-date
    }
    

    任何反馈都会有帮助。

    3 回复  |  直到 17 年前
        1
  •  5
  •   Community Mohan Dere    9 年前

    建立在 Steven's answer ,另一个改进可能是允许同时加载多个文件:

    $global:scriptdirectory = 'C:\powershellscripts'
    $global:loaded_scripts = @{}
    
    function require {
      param(
        [string[]]$filenames=$(throw 'Please specify scripts to load'),
        [string]$path=$scriptdirectory
      )
    
      $unloadedFilenames = $filenames | where { -not $loaded_scripts[$_] }
      reload $unloadedFilenames $path
    }
    
    function reload {
      param(
        [string[]]$filenames=$(throw 'Please specify scripts to reload'),
        [string]$path=$scriptdirectory
      )
    
      foreach( $filename in $filenames ) {
        . (Join-Path $path $filename)
        $loaded_scripts[$filename] = Get-Date
      }
    }
    
        2
  •  3
  •   Steven Murawski    17 年前

    迈克,我觉得那些剧本太棒了。将函数打包到库中非常有用,但我认为加载脚本的函数非常方便。

    我要做的一个更改是将文件位置也设置为一个参数。您可以为此设置默认值,甚至可以使用全局变量。您不需要添加“.ps1”

    $global:scriptdirectory= 'c:\powershellscripts'
    $global:loaded_scripts=@{}
    function require(){
          param ([string]$filename, [string]$path=$scriptdirectory)
          if (!$loaded_scripts[$filename]){
               . (Join-Path $path $filename)
               $loaded_scripts[$filename]=get-date
         }
    }
    
    function reload(){
         param ([string]$filename, [string]$path=$scriptdirectory)
         . (Join-Path $path $filename)
         $loaded_scripts[$filename]=get-date
    }
    

    功能不错!

        3
  •  1
  •   Don Jones    17 年前

    我认为您会发现PowerShell v2的“模块”功能非常令人满意。基本上会帮你解决这个问题。

    推荐文章