while ($EmployeeNumber -ne [int])
{
try
{
[int]$EmployeeNumber = Read-Host -Prompt "Enter Employee Number"
}
catch [System.Management.Automation.PSInvalidCastException]
{
Write-Host -ForegroundColor Red "You can only use numbers!!!"
}
}
$password = Read-Host -Prompt "Enter password"
If I run this script and will enter laters the script will ask me again to enter numbers
but even if enter numbers it’s just showing me a number and not moving to ask password
is anyone know why?
while($EmployeeNumber.GetType().Name -ne 'Int32'){
try {
[int]$EmployeeNumber = Read-Host -Prompt "Enter Employee Number" -ErrorAction Stop
}
catch [System.Management.Automation.PSInvalidCastException] {
Write-Host -ForegroundColor Red "You can only use numbers!!!"
}
}
Regardless of that - wouldn’t it be a much better option to generate an Employee Number automatically from specific rules? If the user of this script enters a number already used it might cause conflicts.
The -ne operator checks for equality. Your statement doesn’t make sense (and will always return false) because what you’re trying to do is compare a value with a type.
What you mean to do is check if $EmployeeNumber is an instance of type [int]. To check if an object is an instance of a particular type, you need to use the -is-isnot operators:
while ($EmployeeNumber -isnot [int]) {
try {
[int]$EmployeeNumber = Read-Host -Prompt "Enter Employee Number"
}
catch [System.Management.Automation.PSInvalidCastException] {
Write-Host -ForegroundColor Red "You can only use numbers!!!"
}
}
$password = Read-Host -Prompt "Enter password"
That said, the above is a pretty horrible way of doing things. I recommend learning about functions and parameters:
function getEmployeeNumber {
param (
[Parameter(Mandatory = $true, HelpMessage="Enter the employee number")]
[int]$employeeNumber
)
$employeeNumber
}
getEmployeeNumber
It runs for me just as expected if the variable is either not existing or of another type than [int].
Try to run this before:
Remove-Variable -Name 'EmployeeNumber'
BTW:
If you want to make sure that our loop runs at least once you should use a tail controlled loop instead of a head controlled one.
do {
try {
[int]$EmployeeNumber = Read-Host -Prompt "Enter Employee Number"
}
catch [System.Management.Automation.PSInvalidCastException] {
Write-Host -ForegroundColor Red "You can only use numbers!!!"
}
} while ($EmployeeNumber -isnot [int])
its not working
i just want if i will type number the script will move to next step and will ask for password
and if i will type laters its will give the warnning message and will ask again numbers
Please don’t get me wrong - this will be my last reply on this topic.
It will prompt for the employee number from inside the loop when the variable does not exist yet or is of another type than [int]. I just tested it several times. It works.