全局变量没有获得价值

时间:2015-07-02 13:22:43

标签: powershell-v4.0

我想从函数的每次迭代中获取行数,并将其分配给变量,以便我可以在最后通过电子邮件发送结果。我的语法产生了一个错误,告诉我$rowcount实际上从未被分配给它?

  

Send-MailMessage:无法验证参数'Body'的参数。参数为null或空。提供非null或空的参数,然后再次尝试该命令。

#Declaring Global Variable
$myArray = $null
$GoodSyntax = "Select * From tableunknown"
$extractFile = "C:\Test.csv"
$dirName = "C:\Completed\"
$date = Get-Date -f 'MM.dd.yy'

#Call function
Execute-SQLquery 
  if (Execute-SQLquery $GoodSyntax) 

$EmailBody = $myArray | Out-String
send-mailmessage -to "abc123@gmail.com" -from "barkbarksalon123@gmail.com" -Body $EmailBody -BodyAsHtml:$true -subject "Testing Through Powershell"


Function Execute-SQLquery {
    param ($GoodSyntax)

$server = "Server01"
$database = "database01"    
$connectionTemplate = "Data Source={0};Integrated Security=SSPI;Initial Catalog={1};"
$connectionString = [string]::Format($connectionTemplate, $server, $database)
$connection = New-Object System.Data.SqlClient.SqlConnection
$connection.ConnectionString = $connectionString
$command = New-Object System.Data.SqlClient.SqlCommand
$command.CommandText = $QueryString
$command.Connection = $connection
$SqlAdapter = New-Object System.Data.SqlClient.SqlDataAdapter
$SqlAdapter.SelectCommand = $command
$DataSet = New-Object System.Data.DataSet
$rowCount = $SqlAdapter.Fill($DataSet)
if ($rowCount -gt 0)
    {
    [System.IO.Directory]::CreateDirectory($dirName)
    $filename = [IO.Path]::GetFileNameWithoutExtension($extractFile) + "_$date" + [IO.Path]::GetExtension($extractFile)
    $extractFile = Join-Path $dirname $filename 
    $DataSet.Tables[0] | Export-Csv $extractFile -NoTypeInformation
    $myArray +=  $rowCount
}
$connection.Close()
}

1 个答案:

答案 0 :(得分:1)

$rowCount不是全局的......全局变量列在代码的顶部......它应该是这样的......

#Declaring Global Variable
$myArray = $null
$rowCount = 0
$GoodSyntax = "Select * From tableunknown"
...

有意义吗?

修改

我的坏!我看到您正在向$rowCount添加$myArray ...您的问题并不清楚。

试试这个......

#Declaring Global Variable
$rowCountTotal = 0
$GoodSyntax = "Select * From tableunknown"
...
$EmailBody = $rowCountTotal | Out-String
...
$DataSet.Tables[0] | Export-Csv $extractFile -NoTypeInformation
$rowCountTotal += $rowCount
}