繁体   English   中英

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

[英]Powershell functions executed regardless of being called

我无法理解 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;
    }
  }
}

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

与 C/C++/C# 程序不同,“您”需要调用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;
    }
  }

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM