I'm trying to create a cleaner code for my script. I'm first defining the array, which will be used to check if the user account has been already queried. Currently the code has two nested if statements, which I want to combine into one if possible. Here is my code:
function addUser {
[cmdletbinding()]
Param(
[Parameter(Mandatory=$true)]
[String]$userName
,
[Parameter(Mandatory=$true)]
[String]$userDomain
,
[Parameter(Mandatory=$true)]
[String]$userAccount
)
Begin {}
Process {
$adAttribute = (Get-ADUser -Identity $userName -Server ($userDomain + "<FQDN HERE>") -Properties "<AD ATTRIBUTE NAME HERE>")."<AD ATTRIBUTE NAME HERE>"
Write-Output (
[pscustomobject]@{
userName = $userName
userDomain = $userDomain
userAccount = $userAccount
<AD ATTRIBUTE NAME HERE> = $adAttribute
}
)
}
End {}
}
$userList = @()
Get-Content $sourceFile | % {
<SOME CODE HERE>
if ($userList.Length -eq 0) {
$userList += addUser -userName $userName -userDomain $userDomain -userAccount $userAccount
}
else {
if (-not $userList.userAccount.Contains($userAccount)){
$userList += addUser -userName $userName -userDomain $userDomain -userAccount $userAccount
}
}
$userAdAttribute = $userList.Where({$_.userAccount -eq $userAccount})."<AD ATTRIBUTE NAME HERE>"
}
<SOME CODE HERE>
As you can see the following code is repetative:
$userList += <SOME FUNCTION CODE HERE>
but I cannot figure out how to make it cleaner, as in the beginning the array is empty and I cannot validate it before adding, so I'm wondering if anyone can share a tip?