2015-11-21 48 views
-1

我有以下配置INI文件:讀INI文件參數

[Applications] 
app1= aplication1 
app2= aplication2 

[BBDD] 
server_bbdd = name_bbdd 

[DATA] 
data_dir = c:\data\ 

[LOGS] 
data_log = c:\data\log\ 

我需要閱讀,並與我的PowerShell腳本加載應用程序數據。例如,對於app1,我需要將此應用的所有數據加載到數據庫(是SQL-SERVER BBDD),然後對app2執行相同的操作。

我可以通過PowerShell讀取和加載應用程序數據嗎?

+0

* for app1我需要將此應用程序的所有數據加載到數據庫中*什麼是「所有數據」?來自哪裏?進入什麼數據庫?哪張桌子?解析一個INI文件很簡單,但是你沒有提供足夠的信息給任何人甚至猜測如何從那裏繼續。 –

回答

0

您可以像使用散列一樣處理ini文件,並創建一個散列表並將它們放入變量中。 例如 $ Applications = @ {「app1」=「aplication1」;「app2」=「aplication2」}

這個只讀函數將讀取ini文件並將這些部分分開, 我們將它讀到內存中的散列,您將需要它稍後輸出。 「switch -regex」用於處理多個if語句。 -regex將匹配子句(如果字符串)作爲正則表達式(正則表達式,即RegEx字符:^。[] - g G?+ * p P w W s s d D $)處理。

function Get-IniContent ($filePath) 
    { 
     $ini = @{} 
     switch -regex -file $FilePath 
     { 
      "^\[(.+)\]" # Find Sections 
      { 
       $section = $matches[1] 
       $ini[$section] = @{} 
       $CommentCount = 0 
      } 
      "^(;.*)$" # Find Comments 
      { 
       $value = $matches[1] 
       $CommentCount = $CommentCount + 1 
       $name = "Comment" + $CommentCount 
       $ini[$section][$name] = $value 
      } 
      "(.+?)\s*=(.*)" # Find Keys 
      { 
       $name,$value = $matches[1..2] 
       $ini[$section][$name] = $value 
      } 
     } 
     return $ini 
    } 

之後,你可以讀取它的變量,因此,輸出這些變量到一個文件或東西。

$iniContent = Get-IniContent 「c:\temp\file.ini」 
$iniContent[「Applications」] 
$value = $iniContent[「Applications」][「app1」] 
$iniContent[「Applications」].Keys | %{$iniContent["Applications"][$_]} 
+1

https://gallery.technet.microsoft.com/scriptcenter/ea40c1ef-c856-434b-b8fb-ebd7a76e8d91 –

+0

是的。你應該在信貸到期時給予信貸。 – Matt