powershell - 无法将我的类的实例添加到列表<我的类>

标签 powershell powershell-5.0

我有一个 Powershell 脚本,它声明一个类,然后尝试将此类的实例添加到列表中:

Add-Type -TypeDefinition @"
using System.Text.RegularExpressions;
public class BuildWarning
{
    public string Solution { get; private set; }
    public string Project { get; private set; }
    public string WarningMessage { get; private set; }
    public string WarningCode { get; private set; }
    public string Key { get; private set; }
    public bool IsNew { get; set; }
    private static readonly Regex warningMessageKeyRegex = new Regex(@"^(?<before>.*)\([0-9,]+\)(?<after>: warning .*)$");
    public BuildWarning(string solution, string project, string warningMessage, string warningCode)
    {
        Solution = solution;
        Project = project;
        WarningMessage = warningMessage;
        WarningCode = warningCode;
        var match = warningMessageKeyRegex.Match(WarningMessage);
        Key = Solution + "|" + Project + "|" + match.Groups["before"].Value + match.Groups["after"].Value;
    }
}
"@

[System.Collections.Generic.List``1[BuildWarning]] $warnings = New-Object "System.Collections.Generic.List``1[BuildWarning]"

[BuildWarning] $newWarning = New-Object BuildWarning("", "", "", "")

$warnings += $newWarning

在最后一行我收到错误:

Cannot convert the "System.Object[]" value of type "System.Object[]" to type
"BuildWarning".
At C:\development\temp\BuildWarningReportGenerator.ps1:93 char:17
+                 $warnings += $newWarning
+                 ~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : InvalidArgument: (:) [], RuntimeException
    + FullyQualifiedErrorId : ConvertToFinalInvalidCastException

我无法弄清楚问题出在哪里。类型检查显示 $warnings$newWarning 的类型都是正确的。如何修复这个错误?

最佳答案

这样怎么样?

#do not use this way
#$warnings += $newWarning

#but use this instead
$warnings.Add($newWarning)

关于powershell - 无法将我的类的实例添加到列表<我的类>,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52123320/

相关文章:

powershell - 使用robocopy搜索子目录

file - 尽管文件夹已被删除,但移动项目会导致 "File Already Exists"错误

powershell - 列出 VM 及其集群

powershell - 如何动态替换字符串的最后一部分?

powershell - 如何在 Windows 10 中从 PowerShell 启动通用 Windows 应用程序 (UWP)?

powershell - 使用Powershell递归重命名文件

powershell - 如何强制函数返回单个元素数组而不是包含的对象?

powershell - 搜索广告组成员

powershell - 如何导入CSV文件中每行的前两个值电源外壳

powershell - ExpandProperty - 管道中缺少的对象