2008-11-11 13 views
13

我發現自己編寫了一堆處理不同名詞(集羣,sql服務器,一般服務器,文件等)的相關函數,並將這些函數組中的每一組放入單獨的文件中(比如說cluster_utils.ps1)。如果我需要它們,我希望能夠將我的配置文件中的某些庫以及其他庫中的某些庫導入到我的PowerShell會話中。我寫了2個函數似乎解決了這個問題,但由於我只用了一個月的PowerShell,所以我想問問是否有任何現有的「最佳實踐」類型的腳本可以用來替代。在powershell中導入「庫」

要使用這些功能,我點源他們(我的個人資料或我的會議)...例如,

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

這裏的功能是:

$global:[email protected]{} 
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 
} 

任何反饋會有幫助。

+0

您可能希望將這些添加到PoshCode.org(社區腳本存儲庫)。 – 2008-11-11 20:54:58

+0

沒有去過那個網站。謝謝。 – 2008-11-12 02:41:02

回答

5

大廈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 
    } 
} 
3

邁克,我認爲這些腳本很棒。將你的函數分割成庫是非常有用的,但我認爲你的函數加載腳本非常方便。

我會做的一個變化就是使文件位置也是一個參數。你可以設置一個默認值,甚至可以使用一個全局變量。您不需要添加「.ps1」

$global:scriptdirectory= 'c:\powershellscripts' 
$global:[email protected]{} 
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 
} 

不錯的功能!

1

我想你會發現的PowerShell V2的「模塊」的功能是非常令人滿意的。基本上爲你照顧這個。