Powershell变量被分配了一个函数的结果和我传递给函数的参数

Powershell variable is assigned the result of a function AND the parameter I passed to the function

我 运行 在我的脚本中一遍又一遍地参与其中。我有这行代码:

$Errors = Get-DeploymentErrors $uniqueID

运行时,$Errors 会被分配 Get-DeploymentErrors 的结果和 $uniqueID 的值。我只想为 $Errors 分配 Get-DeploymentErrors 的结果。

这是 Get-DeploymentErrors 函数:

Function Get-DeploymentErrors($uniqueID)
{
$Errors = @()

$conn = New-Object -TypeName System.Data.SqlClient.SqlConnection
$conn.ConnectionString = 'removed connection string'

$cmd = New-Object -TypeName System.Data.SqlClient.SqlCommand
$cmd.Connection = $conn
$cmd.CommandText = "removed sql statement"
$cmd.Parameters.AddWithValue("@uniqueID", $uniqueID)

$conn.Open()
$reader = $cmd.ExecuteReader()

if($reader.HasRows)
{
    While ($reader.Read())
    {
        $error = New-Object -TypeName PSObject

        $error | Add-Member -MemberType NoteProperty -Name StepID -Value $reader["StepID"]
        $error | Add-Member -MemberType NoteProperty -Name DeploymentID -Value $reader["DeploymentID"]
        $error | Add-Member -MemberType NoteProperty -Name MessageID -Value $reader["MessageID"]
        $error | Add-Member -MemberType NoteProperty -Name Severity -Value $reader["Severity"]
        $error | Add-Member -MemberType NoteProperty -Name Message -Value $reader["Message"]
        $error | Add-Member -MemberType NoteProperty -Name StepName -Value $reader["StepName"]
        $error | Add-Member -MemberType NoteProperty -Name CurrentStep -Value $reader["CurrentStep"]
        $error | Add-Member -MemberType NoteProperty -Name TotalSteps -Value $reader["TotalSteps"]
        $error | Add-Member -MemberType NoteProperty -Name CurrentTime -Value $reader["CurrentTime"]

        $Errors += $error
    }
}

return $Errors
}

$cmd.Parameters.AddWithValue() 回显添加的参数,PowerShell 函数 return success output stream 上的整个非捕获输出,而不仅仅是 return 关键字的参数。

引用自about_Return(强调我的):

SHORT DESCRIPTION
Exits the current scope, which can be a function, script, or script block.

LONG DESCRIPTION
The Return keyword exits a function, script, or script block. It can be used to exit a scope at a specific point, to return a value, or to indicate that the end of the scope has been reached.

Users who are familiar with languages like C or C# might want to use the Return keyword to make the logic of leaving a scope explicit.

In Windows PowerShell, the results of each statement are returned as output, even without a statement that contains the Return keyword. Languages like C or C# return only the value or values that are specified by the Return keyword.

使用以下任何一种方法来抑制不需要的输出:

  • [void]$cmd.Parameters.AddWithValue("@uniqueID", $uniqueID)
  • $cmd.Parameters.AddWithValue("@uniqueID", $uniqueID) | Out-Null
  • $cmd.Parameters.AddWithValue("@uniqueID", $uniqueID) > $null
  • $param = $cmd.Parameters.AddWithValue("@uniqueID", $uniqueID)