Could we use this kind or am I missing something or would an other way be better ? We also want to use this kind of thing if resourcegroups are missing in Azure.
Hi thank you but my question is not whether it works it does, my question is : Is this a valid way. It’s more of a question like. Is this an ugly or not ugly solution.
@JonaUK - $Error is an in-built variable in PowerShell and we should not set value to it.
Using Try Catch is a good option, but we should be checking the exception as well before setting the Flag, There can be many reasons why Get-ADUser fails.
Also, I’d just mention that wrapping this is a function is just unnecessary code. There are multiple one line checks for a boolean, so just make a descriptive variable:
Errors do print the exception by default until PS 5.1 and with Get-Error in PowerShell core we will get all the necessary information from errors.
So when catching the exception you can specify the exception type to catch block.
try{
some unknown keyword
}
catch [DivideByZeroException]{
'division by zero not possible'
}
catch [exception] {
'Error for unknown keyword'
}
try{
1/0
}
catch [DivideByZeroException]{
'division by zero not possible'
}
catch [exception] {
'Error for unknown keyword'
}
It’s not really a question of validity. If the code executes it’s valid. Using -Identity with Get-ADUser will produce an error. Using -Filter either finds a result or nothing\null. There is strict and minimal. Look at these examples:
# 1 line. Simple and has the same functionality of the function wrapper
[bool](Get-Aduser -Filter "samaccountname -like '*$username*'")
#3 lines. Not really gaining anything
function Test-AdUserExistence($UserName) {
[bool](Get-Aduser -Filter "samaccountname -like '*$username*'")
}
# 10 lines. More strict. Mandatory parameter
function Test-AdUserExistenceV2 {
param (
[Parameter(Mandatory=$true)]
[string]$UserName
)
begin {}
process {
[bool](Get-Aduser -Filter "samaccountname -like '*$username*'")
}
end {}
}
# More traditional approach. Once you find the user you are going to do
# something with the user, so the search returns the user vs just telling
# you the user exits
$user = Get-ADUser -Filter {SamAccountName -eq $UserName}
if ($user) {
try {
Set-ADUser -Identity $user -ErrorAction Stop
}
catch {
Throw ('Error occured setting AD stuf for {0}. {1}' -f $UserName,$_)
}
}
else {
'No user found with username {0}' -f $UserName
}