gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-01 08:07:23 24 4
gpt4 key购买 nike

我在我的脚本中一遍又一遍地遇到这个问题。我有这行代码:

$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 函数在 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) |出空
  • $cmd.Parameters.AddWithValue("@uniqueID", $uniqueID) > $null
  • $param = $cmd.Parameters.AddWithValue("@uniqueID", $uniqueID)

关于function - Powershell变量被分配了一个函数的结果和我传递给函数的参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31171001/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com