首页 > 解决方案 > PowerShell 类构造函数 - Get-Content 返回字符串而不是数组

问题描述

我有一个文本文件,其中包含如下测试设备列表。

D1
D2
D3

我有一个类构造函数,除其他外,它从文本文件中获取内容并将其分配给一个属性。

如果在我运行的构造函数中,$this.TestList = Get-Content ".\testlist.txt"我得到一串 D1 D2 D3

如果在构造函数中运行,$TestList = Get-Content ".\testlist.txt"我会得到一个数组。

如果我$TestList = Get-Content ".\testlist.txt"接着跑,$this.TestList = $TestList我会得到一个字符串。

我是 PowerShell 中的类的新手,所以它可能是一个简单的代码错误,但我无法弄清楚为什么会发生这种情况。任何人都可以对此有所了解吗?

编辑:

这是一个非常精简的代码版本。

class CMBuildInfo {
    [string]$TestMachine

    CMBuildInfo () {
        $this.Testmachine = Get-Content "C:\test\ProTestmachines.txt"
    }
}

[CMBuildInfo]$NewApplication = New-Object -TypeName CMBuildInfo -ArgumentList($LatestUpdateInfo)

$NewApplication.TestMachine

我已经确定了这个问题,它是 TestMachine 在课堂上的铸造。最初它是一个简单的字符串。当我决定切换到数组时,我将额外的方括号放在 TestMachine 下面的属性声明中。

有趣的是意想不到的结果。将 Get-Content 转换为字符串,它似乎将每一行与空格分隔符连接在一起。

正确的代码是:

class CMBuildInfo {
    [string[]]$TestMachine

    CMBuildInfo () {
        $this.Testmachine = Get-Content "C:\test\ProTestmachines.txt"
    }
}

[CMBuildInfo]$NewApplication = New-Object -TypeName CMBuildInfo -ArgumentList($LatestUpdateInfo)

$NewApplication.TestMachine

标签: powershellclassconstructor

解决方案


继续我的评论,从文档和帮助文件中推断出来。

  1. 了解$this仅在类的当前实例中使用。
  2. $this仅在方法体的上下文中有效。
  3. 在类主体之外,$this没有任何意义,它会按设计返回 null。没有点引用,你不能给它分配任何东西。
  4. this是要在类的实例中使用的值的类中的引用,该值将由传递的变量内容保存。
  5. 这些、$this.TestList = Get-Content ".\testlist.txt"$TestList = Get-Content ".\testlist.txt" followed by $this.TestList = $TestList对构造函数无效;因为如第 3 点所述。

如我的评论中所述,除非您另有说明,否则 PowerShell 将即时施放。然而,这实际上是针对 1:1 的事情,而不是文件的内容。

一个简单的类、构造函数和用例如下所示:

class New_Car {
    # descriptors/properties/state
    [string]$Color
    [string]$Name
    [string]$Manufacturer
    [string]$Model
    [int]$Length
    [int]$Width
    [int]$Height
    [int]$Mileage

    # Methods, to perform on the object
    [void]Drive($Milage)
    {
        <# 
        Reference for a current instance of the object
        and is only valid in this method body
        #>
        $this.Mileage += $Mileage
    }
}


([New_Car]).GetType() | 
Format-Table -AutoSize
# Results
<#
IsPublic IsSerial Name        BaseType                  
-------- -------- ----        --------                  
False    True     RuntimeType System.Reflection.TypeInfo
#>


# Instantiate the constructor
($MyNewCar = [New_Car]::new())
# Results
<#
Color        : 
Name         : 
Manufacturer : 
Model        : 
Length       : 0
Width        : 0
Height       : 0
Mileage      : 0
#>

($MyNewCar).GetType() | 
Format-Table -AutoSize
# Results
<#
IsPublic IsSerial Name    BaseType     
-------- -------- ----    --------     
True     False    New_Car System.Object
#>

$MyNewCar | Get-Member
# Results
<#
   TypeName: New_Car

Name         MemberType   Definition                      
----         ----------   ----------                      
Drive        Method       void Drive(System.Object Milage)
Equals       Method       bool Equals(System.Object obj)  
GetHashCode  Method       int GetHashCode()               
GetType      Method       type GetType()                  
ToString     Method       string ToString()               
Color        Property     string Color {get;set;}         
Height       Property     int Height {get;set;}           
Length       Property     int Length {get;set;}           
Manufacturer Property     string Manufacturer {get;set;}  
Mileage      Property     int Mileage {get;set;}          
Model        Property     string Model {get;set;}         
Name         Property     string Name {get;set;}          
Width        Property     int Width {get;set;}
#>

$MyNewCar.Drive(9)
$MyNewCar
# Results
<#
Color        : 
Name         : 
Manufacturer : 
Model        : 
Length       : 0
Width        : 0
Height       : 0
Mileage      : 9
#>

$MyNewCar.Manufacturer = Get-Content -Path 'D:\Temp\CarMakers.txt'
$MyNewCar
# Results
<#
Color        : 
Name         : 
Manufacturer : BMW GM Ford
Model        : 
Length       : 0
Width        : 0
Height       : 0
Mileage      : 9
#>

$CarFolks = Get-Content -Path 'D:\Temp\CarMakers.txt'
$MyNewCar.Manufacturer = $CarFolks
$MyNewCar
# Results
<#
Color        : 
Name         : 
Manufacturer : BMW GM Ford
Model        : 
Length       : 0
Width        : 0
Height       : 0
Mileage      : 9
#>

这样做,在构造函数中......

$this. 

...不会产生 IntelliSense,没有任何结果,并且作为保留字/功能,不能/不应用于其他目的。

最后,如果您尝试在一个类中加载多个内容,那么您正在查看构造函数重载。所以这...

Class Car
{
    [String]$vin
    static [int]$numberOfWheels = 4
    [int]$numberOfDoors
    [datetime]$year
    [String]$model

    Car ([string]$vin)
    {$this.vin = $vin        }
    Car ([string]$vin, [string]$model)
    {
        $this.vin   = $vin
        $this.model = $model
    }
    Car ([string]$vin, [string]$model, [datetime]$year)
    {
        $this.vin   = $vin
        $this.model = $model
        $this.year  = $year
    }
    Car ([string]$vin, [string]$model, [datetime]$year, [int]$numberOfDoors)
    {
        $this.vin  = $vin
        $this.model = $model
        $this.year  = $year
        $this.numberOfDoors = $numberOfDoors
    }
}
[car]::new
# Results
<#
OverloadDefinitions
-------------------
Car new(string vin)
Car new(string vin, string model)
Car new(string vin, string model, datetime year)
Car new(string vin, string model, datetime year, int numberOfDoors)
#>

[car]::new(1234, 'chevy', '1/2/2015', 3)
# Results
<#
vin  numberOfDoors year               model
---  ------------- ----               -----
1234             3 02-Jan-15 00:00:00 chevy
#>

在此处查看详细信息:https ://devblogs.microsoft.com/scripting/powershell-5-classes-constructor-overloading


推荐阅读