2012-12-04 1 views
11

내가 Foo.ps1Powershell 스크립트에 설정 파일을 어떻게 소개 할 수 있습니까?

라는 PowerShell 스크립트가 있다고 가정

나는처럼 내 환경 설정 뭔가 지정할 수 있습니다

Foo.ps1.config

라는 XML 구성 파일 소개하고 싶습니다 :

<FunctionsDirectory> 
    $ScriptDirectory\Functions 
</FunctionsDirectory> 
<ModulesDirectory> 
    $ScriptDirectory\Modules 
</ModulesDirectory> 

그리고 나서이 구성을 Foo.ps1의 시작 부분에로드하여 모듈과 도트를 함수 디렉터리로 가져올 수 있습니다.

어떻게 PowerShell에서 이것을 수행 할 수 있습니까?

+1

내가 나에게 합리적인 보이는 웹에 이걸 발견 : 여기 출력은 http://www.bjd145.org/2008/01/powershell-and-xml-configuration-files.html – pencilCake

+0

또는이 하나 : http://rkeithhill.wordpress.com/2006/06/01/creating-and-using-a-configuration-file-for-your-powershell-scripts/ – pencilCake

+0

저는 Keith의 솔루션을 사용하기 전에 치료를합니다. – nimizen

답변

7

Keith's solution 바탕으로 ... 코드로드 XML :

$configFile = "c:\Path2Config" 
    if(Test-Path $configFile) { 
     Try { 
      #Load config appsettings 
      $global:appSettings = @{} 
      $config = [xml](get-content $configFile) 
      foreach ($addNode in $config.configuration.appsettings.add) { 
       if ($addNode.Value.Contains(‘,’)) { 
        # Array case 
        $value = $addNode.Value.Split(‘,’) 
         for ($i = 0; $i -lt $value.length; $i++) { 
          $value[$i] = $value[$i].Trim() 
         } 
       } 
       else { 
        # Scalar case 
        $value = $addNode.Value 
       } 
      $global:appSettings[$addNode.Key] = $value 
      } 
     } 
     Catch [system.exception]{ 
     } 
    } 

는 XML 값에서 변수를 채우려면 :

  $variable1 = $appSettings["var1"] 
      $variable2 = $appSettings["var2"] 

및 관련 XML : 아마

<?xml version="1.0"?> 
<configuration> 
    <startup> 
    </startup> 
    <appSettings> 
<!--Vars --> 
    <add key="var1" value="variableValue1"/> 
    <add key="var2" value="variableValue2"/> 
    </appSettings> 
</configuration> 
9

쉬운 해결책 .... 구성 파일이 "Con

PS Testing> $configFile.configuration.appsettings 
#comment        add 
--------        --- 
Vars         {add, add} 

PS Testing> $configFile.configuration.appsettings.add 
key         value 
---         ----- 
var1         variableValue1 
var2         variableValue2 

PS Testing> $configFile.configuration.appsettings.add[0].value 
variableValue2 

길고도 짧은 이야기 : 새로운 변수에서

PS Testing> [xml]$configFile= get-content .\Config=.xml 
PS Testing> $configFile 
xml         configuration 
---         ------------- 
version="1.0"      configuration 

읽기 데이터를 "fix.xml이 시도 XML로 변수를 주조하고, GET-내용을. 이 경우

은의 Config.xml은 다음과 같습니다

<?xml version="1.0"?> 
<configuration> 
    <startup> 
    </startup> 
    <appSettings> 
    <!--Vars --> 
    <add key="var1" value="variableValue1"/> 
    <add key="var2" value="variableValue2"/> 
    </appSettings> 
</configuration> 
6

을 XML 구성의 대안 들어, 구성의 다른 유형을 사용하여 유연합니다. 글로벌 PS 구성 파일을 사용하는 것이 좋습니다. 여기에 그 방법이 있습니다 :

Powershell 구성 파일 (예 : Config.ps1)을 만든 다음 모든 구성을 전역 변수로 저장하고 첫 번째 단계로 초기화하여 구성 값을 사용할 수 있도록합니다 스크립트 컨텍스트

이 접근법의 이점은 스칼라 변수, 컬렉션 및 해시와 같은 다양한 유형의 데이터 구조를 Config.ps1 PS 파일에서 사용할 수 있으며 PS 코드에서 쉽게 참조 할 수 있다는 것입니다. 여기서 C는

enter image description here

:

$global:config = @{ 
    Var1 = "Value1" 

    varCollection = @{  
     item0  = "colValue0" 
     item1 = "colValue1" 
     item2 = "colValue2" 
    }  
} 


그 다음 기능 구성에서/변수를로드 구성 \ Config.ps1 파일 \


다음 행동의 예이다. 이 모듈의 ps1 파일은 C : \ Module \ PSModule.psm1이므로 다음과 같습니다.

$scriptFiles = Get-ChildItem "$PSScriptRoot\Config\*.ps1" -Recurse 

foreach ($script in $scriptFiles) 
{ 
    try 
    {  
     . $script.FullName 
    } 
    catch [System.Exception] 
    { 
     throw 
    } 
} 

La stly, 초기화 스크립트는 아래 한 줄을 포함합니다 : (C : \ Init.ps1).

Import-Module $PSScriptRoot\Module\PSModule.psm1 -Force

Init.ps1을 실행 한 후. global : config 변수는 스크립트 컨텍스트에서 사용할 수 있습니다.
enter image description here

관련 문제