After adding the code
$ip = (nslookup $pcName | Select-String Address | Where-Object LineNumber -eq 5).ToString().Split(' ')[-1]
It will not give any result when the user has NO pc name assigned to his User ID. The script doesn't run and it's giving a blank result. It works when the user has a PC name assigned to his user id.
The same when the user ID cannot be found due to typo or something else. There I want to prompt the user to give in the correct user ID and restart the script. I'm trying to figure it out how it can be done but I don't find the correct way to do it.
Thanks in advance for your help!
$csv = Import-CSV 'C:\Users\ADMIN\Desktop\Powershells\Computers in a specific workgroup or domain.csv'
$ADprops = @(
'DisplayName'
'Mail'
'LastBadPasswordAttempt'
'AccountExpirationDate'
'PasswordLastSet'
)
$filter = @(
$ADprops
@{
Name = 'Password Changeable'
Expression = { $changeable }
}, @{
Name = 'Password Expires'
Expression = { $expires }
}, @{
Name = 'Last logon'
Expression = { $lastlogon }
}, @{
Name = 'PC Name'
Expression = { $pcName }
}, @{
Name = 'Address'
Expression = { $ip }
}
)
Clear-Host
do
{
Write-Host " Enter the user ID: " -ForegroundColor Cyan -NoNewline
$UserName = Read-Host
Write-Host ""
$pcName = $csv.Where({ $_."User ID" -match $Username })."PC Name"
$ip = (nslookup $pcName | Select-String Address | Where-Object LineNumber -eq 5).ToString().Split(' ')[-1]
$expires, $changeable = net user $Username /domain |
Select-String -Pattern 'Password Changeable|Password Expires|Last logon'|
ForEach-Object { ($_ -split '\s{2,}')[1] }
Get-ADUser -Identity $Username -Properties $ADprops |
Select-Object $filter
} while ($Username -notcontains $Processes)
When testing your code I notice that when you provide the function nsloockup with empty string value the function is stucked. What I suggest is to add a check on the $pcName variable as follow:
$pcName = $csv.Where({ $_."User ID" -match $Username })."PC Name"
if([string]::IsNullOrEmpty($pcName)){
continue;
}