无论被调用,都会执行Powershell函数

时间:2012-11-28 09:24:32

标签: function powershell

我无法理解Powershell如何处理函数。在下面的脚本中,即使我从未实际调用main函数,也会调用所有函数。 powershell没有调用链的概念吗?

param([string]$directory)

[string]$global:sqlscript;
$global:types = @{
"double" = "DOUBLE PRECISION"; 
"int" = "INTEGER"; 
"QString" = "INTEGER";
"Ignored" = "1";
"Normal" = "2";
"Critical" = "3" }

function resultToSql($element)
{
  $global:sqlscript += ('"')
  $global:sqlscript += ($element.name + '" ')
  $global:sqlscript += ($global:types.Get_Item($element.type))
  $global:sqlscript += (',' + [Environment]::Newline)
  $global:sqlscript += ('"' + $element.name + "_metric_group" + " " + $global:types.Get_Item($element.metric_group.type))   
  $global:sqlscript += (',' + [Environment]::Newline)
}

function xmlToSql($source)
{
  Write-Host "Parsing...";
  $global:sqlscript += "CREATE TABLE IF NOT EXISTS " + '"' + $source.spec.task.ToLower() + '"'+ [Environment]::NewLine
  $global:sqlscript += '"' + "id" + '"' + " SERIAL NOT NULL" + [Environment]::NewLine

  foreach ($node in $source.spec.measure) {
      resultToSql $node
  }

  foreach ($m in $source.spec.error) {
    resultToSql $m
  }

  $global:sqlscript += '"' + "weighted_sum" + '" ' + $global:types.Get_Item("double") + [Environment]::Newline;
}

function main
{
  if ($directory -eq $null) { exit }
  else
  {
    $xmlfiles = Get-ChildItem -Path $directory -include *Spec.xml
    foreach ($xmlfile in $xmlfiles)
    {
        Write-Host "Filename:" $xmlfile;
        [xml]$spec = Get-Content $file;
        xmlToSql $spec; 
        Write-Host $script;
    }
  }
}

3 个答案:

答案 0 :(得分:2)

PowerShell无法神奇地检测到脚本的更改,关闭ISE并重新打开它然后再次运行脚本。如果失败,请将脚本的内容粘贴到ISE中,然后单击执行按钮,我就这样做了,主要没有运行。

答案 1 :(得分:0)

与C / C ++ / C#程序不同,“你”需要调用此脚本底部的Main函数。当你运行上面的脚本时,它所做的就是创建你定义的函数。它不运行任何一个。你必须通过在脚本中调用它们来做到这一点,其中一个调用必须在脚本级别(在任何函数之外)。

答案 2 :(得分:0)

删除主函数容器,使其类似于下面的代码:

  if ($directory -eq $null) { exit }
  else
  {
    $xmlfiles = Get-ChildItem -Path $directory -include *Spec.xml
    foreach ($xmlfile in $xmlfiles)
    {
        Write-Host "Filename:" $xmlfile;
        [xml]$spec = Get-Content $file;
        xmlToSql $spec; 
        Write-Host $script;
    }
  }

Powershell不像C#/ C ++那样从Main执行。它执行首先在函数外部接收的语句。在上面的这种情况下,它将首先执行if语句,因为它出现在函数框之外。

相关问题