2012-01-20 18 views
0

我在PS一個下面的腳本:PowerShell腳本中使用XML產生的PowerGUI的和PowerShell控制檯不同的輸出

[System.Xml.XmlDocument] $Config; 

function Get-ScriptDirectory 
{ 
    Split-Path $script:MyInvocation.MyCommand.Path 
} 

function LoadConfig 
{ 
    $configPath = Join-Path (Get-ScriptDirectory) Config.xml  
    $Config = [xml](gc $configPath) 
} 

function WriteData 
{ 
    $sourceFolderPath = $Config.Deploy.SourceFolder 
    Write-Host $sourceFolderPath 
} 

LoadConfig 
WriteData 

我基本的XML文件看起來像:

<Deploy> 
    <SourceFolder>C:\FolderPath</SourceFolder> 
<Deploy> 

當我調試運行它PowerGUI工具工作正常,它寫入正確的輸出。但是當我在Windows 7的PowerShell控制檯中運行相同的腳本時,結果是空行。我不知道爲什麼。

+1

'$ configPath'總是一樣嗎? – stej

+0

是的。同時我解決了它。見下面的答案。 – zosim

回答

3

您的腳本有問題,因爲您在腳本開始時聲明[System.Xml.XmlDocument] $Config,您必須在LoadConfig函數中使用$global:Config。更多解釋請看Get-Help about_Scopes

function LoadConfig 
{ 
    $configPath = Join-Path (Get-ScriptDirectory) Config.xml  
    $global:Config = [xml](gc $configPath) 
} 

它爲什麼在PowerGui中工作?因爲會話中存在$config,所以最好像下圖所示配置PowerGui。

enter image description here

+0

謝謝,這幫助了我。 – zosim

相關問題