我想在PowerShell中定义类。在该类中,我想使用其他地方定义的函数,因此当需要该值时,它会在需要时自动运行。以下是一个例子。
class ActiveDirectoryUser {
$DisplayName
$LastName
$FirstName
$FirstNameNonLatin = Remove-StringLatinCharacters -String $FirstName
}
然而,这并没有真正起作用。它在C#中工作,那么在PowerShell中它的等价物是什么?
我正在以某种方式使用此代码:
$user = New-Object ActiveDirectoryUser
$user.DisplayName = $u.DisplayName
$user.LastName = $u.LastName
$user.FirstName = $u.FirstName
$user | ft * # should show all fields including FirstNameNonLatin
答案 0 :(得分:1)
给它一个旋转
function Get-FormattedFullName {
Param (
[string]
$FirstName
,
[string]
$LastName
)
Process {
return "{0} {1}" -f $FirstName, $LastName
}
}
$ActiveDirectoryUser = New-Object -TypeName PSObject
$ActiveDirectoryUser | Add-Member -MemberType NoteProperty -Name "FirstName" -Value "John"
$ActiveDirectoryUser | Add-Member -MemberType NoteProperty -Name "LastName" -Value "Smith"
$ActiveDirectoryUser | Add-Member -MemberType ScriptProperty -Name "FullName" -Value `
{ #Get
return Get-FormattedFullName -FirstName $this.FirstName -LastName $this.LastName
}
`
$ActiveDirectoryUser
结果:
FirstName LastName FullName
--------- -------- --------
John Smith John Smith
如果我们然后更新对象的LastName
属性,FullName
也会反映此更改:
$ActiveDirectoryUser.LastName = "CHANGED"
$ActiveDirectoryUser
结果:
FirstName LastName FullName
--------- -------- --------
John CHANGED John CHANGED
答案 1 :(得分:1)
您需要一个构造函数来使用另一个属性设置默认值。例如:
function Remove-StringLatinCharacters ([string]$String) { $string.Substring(0,1) }
class ActiveDirectoryUser {
[string]$DisplayName
[string]$LastName
[string]$FirstName
[string]$FirstNameNonLatin
ActiveDirectoryUser ([string]$DisplayName, [string]$LastName, [string]$FirstName) {
$this.DisplayName = $DisplayName
$this.LastName = $LastName
$this.FirstName = $FirstName
$this.FirstNameNonLatin = (Remove-StringLatinCharacters -String $FirstName)
}
}
[ActiveDirectoryUser]::new("Disp","Last","First")
DisplayName LastName FirstName FirstNameNonLatin
----------- -------- --------- -----------------
Disp Last First F