Function 函数将值返回到控制台,但不返回到文件
尝试编写一个函数来创建要添加到表中以进行导出的新行。以下命令将正确的值输出到控制台,但CSV为空 如果我将创建Function 函数将值返回到控制台,但不返回到文件,function,powershell,Function,Powershell,尝试编写一个函数来创建要添加到表中以进行导出的新行。以下命令将正确的值输出到控制台,但CSV为空 如果我将创建$newline的代码放在脚本中的不同位置,它可以正常工作,但当我将其作为函数调用时就不行了 $report = @() Function CreateNewLine { $lineproperties = @{ Cluster = $cluster Node = $node Database = $d.Name LogCount = $logcount LogPath = $
$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
函数
CreateNewLine
从不返回值。您需要执行以下操作:
Function CreateNewLine
{
$lineproperties = [PSCustomObject]@{
Cluster = $cluster
Node = $node
Database = $d.Name
LogCount = $logcount
LogPath = $p
}
$lineProperties
}
这里有一个范围问题<代码>$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
函数应该可以访问这些其他变量,只要它们在函数的父范围内 您可以更轻松地创建对象(正如Matt所说,这在Powershell 3.0及更高版本中有效): 然后,在您想要的任何地方,您都可以使用此功能:
$cluster = "cluster 1"
$report += createnewline
$cluster = "cluster 2"
$report += createnewline
$report | Export-CSV 'pathto file' -notype
如果你要这样做,那么你甚至不需要麻烦变量赋值。在这个简单的例子中,是的,但我想强调的是没有返回值的部分,由于该问题可能省略了其他逻辑。仅供参考,您需要确保您使用的是PowerShell 3.0或更高版本,以使其正常工作。仅供参考,您需要确保您使用的是PowerShell 3.0或更高版本,以使其正常工作。
$cluster = "cluster 1"
$report += createnewline
$cluster = "cluster 2"
$report += createnewline
$report | Export-CSV 'pathto file' -notype