I have a small program which accepts an integer and converts it to DateTime. However, I try to use KeyCode to only allow numbers from both keyboard and numpad, and eliminate the special characters and letters. My code is allowing Shift+Num to enter those special characters. How do eliminate them from being entered?
$FromDateText.Add_KeyDown({KeyDown})
$ToDateText.Add_KeyDown({KeyDown}) #TextBox
Function KeyDown()
{
if ($FromDateText.Focused -eq $true -or $ToDateText.Focused -eq $true)
{
if ($_.KeyCode -gt 47 -And $_.KeyCode -lt 58 -or $_.KeyCode -gt 95 -and
$_.KeyCode -lt 106 -or $_.KeyCode -eq 8)
{
$_.SuppressKeyPress = $false
}
else
{
$_.SuppressKeyPress = $true
}
}
}
Instead of intercepting the KeyDown event, I'd simply just remove any non-digit character from the TextBox every time the TextChanged event is raised:
$ToDateText.add_TextChanged({
# Check if Text contains any non-Digits
if($tbox.Text -match '\D'){
# If so, remove them
$tbox.Text = $tbox.Text -replace '\D'
# If Text still has a value, move the cursor to the end of the number
if($tbox.Text.Length -gt 0){
$tbox.Focus()
$tbox.SelectionStart = $tbox.Text.Length
}
}
})
Way easier than trying to infer the input value from Key event args
Related
I'm wondering if there's a way to simplify the code below by having an if statement that checks if a value matches one of the entries of an array...
The code I ended up with:
foreach ($sourceLine in $source) {
$sourceAVTrim = $sourceLine.ID.Remove(0, 1)
$sourceAV = "av" + $sourceAVTrim
if ($SourceLine.MAC -like "VCO*" -or $SourceLine.MAC -like "FOO*" -or $SourceLine.MAC -like "HOM*" -or $SourceLine.MAC -like "EOP*" -or $SourceLine.MAC -like "PCP*" -or $SourceLine.MAC -like "BUI*" -or $SourceLine.MAC -like "DML*") {
if ($SourceLine.MAC -like "*ADM" -or $SourceLine.MAC -like "*SAL" -or $SourceLine.MAC -like "*PLA" -or $SourceLine.MAC -like "*PLN" -or $SourceLine.MAC -like "*PLC" -or $SourceLine.MAC -like "*PLS") {
Write-Host "$($SourceAV) will NOT receive SMS - $($SourceLine.MAC)" -ForegroundColor Red
} else {
Write-Host "$($SourceAV) will receive SMS - $($SourceLine.MAC)" -ForegroundColor Green
}
} else {
Write-Host "$($SourceAV) will NOT receive SMS - $($SourceLine.MAC)" -ForegroundColor Red
}
}
But how can I set 2 arrays instead and have IF check my value against each entry?
$startMACs = #("VCO","FOO","HOM","EOP","PCP","BUI","DML")
$endMACs = #("ADM","SAL","PLA","PLN","PLC","PLS")
For exact matches you could use the -contains or -in operator. However, in your case you want a partial match against multiple strings, so I'd go with a regular expression.
$startMACs = 'VCO', 'FOO', 'HOM', 'EOP', 'PCP', 'BUI', 'DML'
$pattern = ($startMACs | ForEach-Object { [Regex]::Escape($_) }) -join '|'
if ($SourceLine.MAC -match "^($pattern)") {
...
} else {
...
}
^ anchors the expression at the beginning of a line, so you'll get the matches beginning with those substrings.
To anchor the expression at the end of a line (so you'll get the matches ending with the substrings) replace "^($pattern)" with "($pattern)$".
$pattern is constructed as an alternation (VCO|FOO|HOM|...), meaning "match any of these substrings" ("VCO" or "FOO" or "HOM" or ...).
Escaping the individual terms before building the pattern is so that characters with a special meaning in regular expressions (like for instance . or *) are treated as literal characters. It's not required in this case (since there are no special characters in the sample strings), but it's good practice so that nothing unexpected happens should someone update the list of strings with values that do contain special characters.
Since your patterns all start with a 3 letter code, one possibility is to grab the start of the target string and match using the -in operator with the pattern collection:
$startMACs = #("VCO","FOO","HOM","EOP","PCP","BUI","DML","HDOM")
if($SourceLine.MAC.Substring(0,3) -in $startMACs) {
# Do something
}
So, if $SourceLine.MAC is, say, EOP123, the substring() call grabs the EOP part, then compares it to each entry in the $startMACs array, returning true if it finds a match, and false otherwise - should be true in this example.
You can do something similar for the end patterns:
$endMACs = #("ADM","SAL","PLA","PLN","PLC","PLS")
if($SourceLine.MAC.Substring($SourceLine.MAC.Length - 3,3) -in $endMACs) {
# Do something
}
Context:
We are making an API to get a list of all VMs and the filter it, using if loops, to return only VMs with name starting only with the values in $MachineList.
The list of servers is split in 2:
set 1: srv-a-1, srv-a-2, srv-b-1, srv-b-2, srv-c-1, srv-c-2, etc.
set 2: tst-a-1, tst-a-2, tst-b-1, tst-b-2, tst-c-1, tst-c-2, etc.
This is the script:
$EnvironmentList = "Environments-4" -or "Environments-5" -or "Environments-41" -or "Environments-61"
$MachineList = "srv-a*" -or "srv-b*" -or "srv-c*" -or "srv-d*" -or "srv-e*" -or "srv-f*" -or "srv-g*" -or "srv-h*" -or" srv-i*" -or "srv-j*" -or "srv-k*" -or "srv-l*"
function CheckService {
$MachinesRequest = (Invoke-WebRequest -Method Get -Headers #{"X-system-ApiKey"="Hashed-API-Key-Value"} -URI https://url-to-site.local/api/machines/all).Content | ConvertFrom-Json
foreach ($Machine in $MachinesRequest) {
if ($EnvironmentList -contains $Machine.EnvironmentIds) {
if ($MachineList -contains $Machine.Name) {
$Machine.Name
}
}
}
}
CheckService
We're trying to return just the items which match the values in the machine list however this is returning the full list of machines (both srv* and tst*).
First and foremost, $MachineList = "srv-a*" -or "srv-b*" -or ... won't do what you apparently think it does. It's a boolean expression that evaluates to $true, because PowerShell interprets non-empty strings as $true in a boolean context. If you need to define a list of values, define a list of values:
$MachineList = "srv-a*", "srv-b*", ...
Also, the -contains operator does exact matches (meaning it checks if any of the values in the array is equal to the reference value). For wildcard matches you need a nested Where-Object filter
$MachineList = "srv-a*", "srv-b*", "srv-c*", ...
...
if ($MachineList | Where-Object {$Machine.Name -like $_}) {
...
}
A better approach in this scenario would be a regular expression match, though, e.g.:
$pattern = '^srv-[a-l]'
...
if ($Machine.Name -match $pattern) {
...
}
use -eq for an exact match. use -match or -contains for a partial string match
$my_list='manager','coordinator','engineer', 'project engineer',
$retval=$False
if ($dd_and_pm -eq "engineer")
{
$retval=$True
}
I have a small program which accepts an integer and converts it to DateTime. However, I try to use KeyCode to only allow numbers from both keyboard and numpad, and eliminate the special characters and letters. My code is allowing Shift+Num to enter those special characters. How do eliminate them from being entered?
$FromDateText.Add_KeyDown({KeyDown})
$ToDateText.Add_KeyDown({KeyDown}) #TextBox
Function KeyDown()
{
if ($FromDateText.Focused -eq $true -or $ToDateText.Focused -eq $true)
{
if ($_.KeyCode -gt 47 -And $_.KeyCode -lt 58 -or $_.KeyCode -gt 95 -and
$_.KeyCode -lt 106 -or $_.KeyCode -eq 8)
{
$_.SuppressKeyPress = $false
}
else
{
$_.SuppressKeyPress = $true
}
}
}
Instead of intercepting the KeyDown event, I'd simply just remove any non-digit character from the TextBox every time the TextChanged event is raised:
$ToDateText.add_TextChanged({
# Check if Text contains any non-Digits
if($tbox.Text -match '\D'){
# If so, remove them
$tbox.Text = $tbox.Text -replace '\D'
# If Text still has a value, move the cursor to the end of the number
if($tbox.Text.Length -gt 0){
$tbox.Focus()
$tbox.SelectionStart = $tbox.Text.Length
}
}
})
Way easier than trying to infer the input value from Key event args
Hi I am new to Powershell and need some help:
My Script gets a number by userinput. I want to check this number if it´s between these ranges. So far so easy, but the input from 1-9 is with a leading zero.
With google, I got this working without the special case "leading zero".
do {
try {
$numOk = $true
$input = Read-host "Write a number between 1-12"
} # end try
catch {$numOK = $false }
} # end do
# check numbers
until (
($input -ge 1 -and $input -lt 13) -or
($input -ge 21 -and $input -lt 25) -or
($input -ge 41 -and $input -lt 49) -or
($input -ge 61 -and $input -lt 67) -and $numOK)
Write-Host $input
For example:
Input "5" Output "5"
Input "05" stucks in loop, should be "05"
AddOn: Is it possible to block inputs like 1-9 and just accept inputs like 01-09?
you can use the -f operator to format the string here is to get a 2 digits number
PS>"{0:00}" -f 5
05
some readings : http://ss64.com/ps/syntax-f-operator.html
I am trying to create a function in which a user has to give a filename that can not containt an empty string. Besides that, the string can not contain a dot. When I run this function, I keep looping when I enter "test" for example. Any idea as to why?
function Export-Output {
do {
$exportInvoke = Read-Host "Do you want to export this output to a new .txt file? [Y/N]"
} until ($exportInvoke -eq "Y" -or "N")
if ($exportInvoke -eq "Y") {
do {
$script:newLog = Read-Host "Please enter a filename! (Exclude the extension)"
if ($script:newLog.Length -lt 1 -or $script:newLog -match ".*") {
Write-Host "Wrong input!" -for red
}
} while ($script:newLog.Length -lt 1 -or $script:newLog -match ".*")
ni "$script:workingDirectory\$script:newLog.txt" -Type file -Value $exportValue | Out-Null
}
}
EDIT:
On a related note:
do {
$exportInvoke = Read-Host "Do you want to export this output to a new .txt file? [Y/N]"
} until ($exportInvoke -eq "Y" -or "N")
When I use these lines of code I can simply hit enter to circumvent the Read-Host. When I replace "Y" -or "N" with simply "Y" it does not. Any idea as to why this is happening?
The -match operator checks against a regular expression, so this:
$script:newLog -match ".*"
is testing if the filename contains any charachter except newline (.) 0 or more times (*). This condition will always be true, thus creating an infinite loop.
If you want to test for a literal dot, you must escape it:
$script:newLog -match '\.'
As for your other question, you're misunderstanding how logical and comparison operators work. $exportInvoke -eq "Y" -or "N" does not mean $exportInvoke -eq ("Y" -or "N"), i.e. variable equals either "Y" or "N". It means ($exportInvoke -eq "Y") -or ("N"). Since the expression "N" does not evaluate to zero, PowerShell interprets it as $true, so your condition becomes ($exportInvoke -eq "Y") -or $true, which is always true. You need to change the condition to this:
$exportInvoke -eq "Y" -or $exportInvoke -eq "N"
Use this to test your input:
!($script:newLog.contains('.')) -and !([String]::IsNullOrEmpty($script:newLog)) -and !([String]::IsNullOrWhiteSpace($script:newLog))
Your regular expression (-match ".*" is essentially matching on everything.