函数将值返回到控制台,但不返回文件

时间:2015-09-17 14:59:54

标签: function powershell

尝试编写一个函数来创建一个新行,以便添加到表中以便导出。以下内容将正确的值输出到控制台,但CSV为空。

如果我将代码放置在脚本中的不同位置创建$newline,它可以正常工作,但不是在我将其称为函数时。

    $report = @()

Function CreateNewLine
{
$lineproperties = @{
Cluster = $cluster
Node = $node
Database = $d.Name
LogCount = $logcount
LogPath = $p
}

$newline = New-Object PSObject -property $lineproperties
}

# Loop to create values for $cluster etc...

CreateNewLine
$report += $newline

# End loop

$report |  Export-CSV 'pathto file' -notype

3 个答案:

答案 0 :(得分:0)

函数CreateNewLine永远不会返回值。您需要执行以下操作:

Function CreateNewLine
{
    $lineproperties = [PSCustomObject]@{
        Cluster = $cluster
        Node = $node
        Database = $d.Name
        LogCount = $logcount
        LogPath = $p
    }
    $lineProperties
}

答案 1 :(得分:0)

这里有一个范围问题。 $newline在函数外没有上下文。因此,您只需将$ null添加到$report数组。使函数返回可以捕获的值。

Function CreateNewLine
{
    $lineproperties = @{
        Cluster = $cluster
        Node = $node
        Database = $d.Name
        LogCount = $logcount
        LogPath = $p
    }

    New-Object PSObject -property $lineproperties
}

# Loop to create values for $cluster etc...

$report += CreateNewLine

该函数应该可以访问那些其他变量,只要它们位于函数的父作用域中即可。

答案 2 :(得分:0)

您可以更轻松地创建对象(正如Matt所说,这适用于Powershell 3.0及更高版本):

Function CreateNewLine
{
  [pscustomobject]@{
  Cluster = $cluster
  Node = $node
  Database = "name"
  LogCount = $logcount
  LogPath = $p
  }
}

然后,在您想要的任何地方,您都可以使用此功能:

$cluster = "cluster 1"
$report += createnewline

$cluster = "cluster 2"
$report += createnewline

$report |  Export-CSV 'pathto file' -notype