Disable $OKButton until textbox is populated? - powershell

I have a question on an event trigger. I'd like to have my OKButton be disabled until a textbox(s) are populated, pretty much requiring the user to input data into that field or cancel out of the form. I have $OKButton.enabled = $false already and think I need something along the lines of
if ($Textbox3.Text.Length <1) {
$OKButton.enabled = $true
} else {
$OKButton.enabled = $false
}
I have this piece of code in my script currently and the OK button is disabled but I think I am having a syntax error because when Textbox3 is filled the button remains disabled.

In PowerShell, the "less-than" comparison operator is not < but rather -lt (short for, you guessed it, less than):
if ($Textbox3.Text.Length -lt 1) {
$OKButton.enabled = $true
} else {
$OKButton.enabled = $false
}
Read more about comparison operators in PowerShell with Get-Help about_Comparison_Operators

Related

How can I allow only Y/N to be input in Read-Host without having to press Enter in Powershell?

I'm trying to find a way to have something like a Read-Host to ask the user if they want to output to the file listed or not. With this I want them to either press y or n and then the code continues rather than then pressing y/n then pressing enter as well. At the moment this all works well but again it's not quite what I'm wanting.
I've tried looking into Readkey and SendKeys (to push Enter for the user) but neither work as they seem to only execute after the user has pushed Enter on the Read-Host. I'm still very new to Powershell so I'm not entirely sure whether it's actually possible or not and I've spent too much time googling/testing to find an answer that works. If I was to use Write-Host or something to do this, it needs to not show up in the log.
I've included the necessary part of my script below. It basically asks the user if the file location is correct. If it is they press y and it uses it for the output, otherwise if they push n then it loads the FolderBrowserDialog for them to select the folder they want.
I should also note this is all within a Tee-object as this code is what determines where the Tee-object output goes to.
$OutputYN = Read-Host "Do you want the output file generated to $startDirectory\FolderList.txt? (Y/N)"
If (“y”,”n” -notcontains $OutputYN) {
Do {
$OutputYN = Read-Host "Please input either a 'Y' for yes or a 'N' for no"
} While (“y”,”n” -notcontains $OutputYN)
}
if ($OutputYN -eq "Y") {
$OutputLoc = $startDirectory
}
elseif ($OutputYN -eq "N") {
$OutputLocDir = New-Object System.Windows.Forms.FolderBrowserDialog
$OutputLocDir.Description = "Select a folder for the output"
$OutputLocDir.SelectedPath = "$StartDirectory"
if ($OutputLocDir.ShowDialog() -eq "OK") {
$OutputLoc = $OutputLocDir.SelectedPath
$OutputLoc = $OutputLoc.TrimEnd('\')
}
}
EDIT:
I should have been a little more clear. I had already tried message box type stuff as well but I'd really prefer if there is a way that the user types in a y or a n. I'm not really interested in a popup box that the user has to click. If it's not possible then so be it.
Readkey is the right way.
Use the following as template.
:prompt while ($true) {
switch ([console]::ReadKey($true).Key) {
{ $_ -eq [System.ConsoleKey]::Y } { break prompt }
{ $_ -eq [System.ConsoleKey]::N } { return }
default { Write-Error "Only 'Y' or 'N' allowed!" }
}
}
write-host 'do it' -ForegroundColor Green
:prompt gives the outer loop (while) a name which can be used in the switch statement to directly break out entirely via break prompt (and not within the switch statement).
Alternative (for Windows):
Use a MessageBox.
Add-Type -AssemblyName PresentationFramework
$messageBoxResult = [System.Windows.MessageBox]::Show("Do you want the output file generated to $startDirectory\FolderList.txt?" , 'Question' , [System.Windows.MessageBoxButton]::YesNo , [System.Windows.MessageBoxImage]::Question)
switch ($messageBoxResult) {
{ $_ -eq [System.Windows.MessageBoxResult]::Yes } {
'do this'
break
}
{ $_ -eq [System.Windows.MessageBoxResult]::No } {
'do that'
break
}
default {
# stop
return # or EXIT
}
}
Not sure if this is possible in the console. But when I need the user to write one answer of a specified set, I use a do-until-loop like:
Do {
$a = Read-Host "Y / N"
} until ( 'y', 'n' - contains $a )
try this:
$title = 'Question'
$question = 'Do you want the output file generated to $startDirectory\FolderList.txt?'
$choices = New-Object Collections.ObjectModel.Collection[Management.Automation.Host.ChoiceDescription]
$choices.Add((New-Object Management.Automation.Host.ChoiceDescription -ArgumentList '&Yes'))
$choices.Add((New-Object Management.Automation.Host.ChoiceDescription -ArgumentList '&No'))
$decision = $Host.UI.PromptForChoice($title, $question, $choices, 1)
if ($decision -eq 0) {
Write-Host 'Yes'
} else {
Write-Host 'No'
}
If you are on Windows, you can do it :
[System.Reflection.Assembly]::LoadWithPartialName("System.Windows.Forms") | Out-Null
$result = [System.Windows.Forms.MessageBox]::Show('Do you want the output file generated to $startDirectory\FolderList.txt?' , "Question" , [System.Windows.Forms.MessageBoxButtons]::YesNo, [System.Windows.Forms.MessageBoxIcon]::Question)
if ($result -eq 'Yes') {
"Yes"
}
else
{
"No"
}

Powershell excel replace always returns true

I've doing a find and replace in a whole bunch of excel files (to update some links that have moved)
I want to track which files had changes made to them however the result of a replace is always true regardless of if the required text was is there. A find like this:
$worksheet.UsedRange.Find($Text)
will either return null if the text being looked for does not exist or an object if it does, but thats significant extra processing I'd prefer to remove given that I have about 1.2million files to check.
Here is my replace code:
$found=$false
$xlCalculationManual = -4135
$excel = New-Object -comobject Excel.Application
$excel.visible = $false
$excel.AskToUpdateLinks = $false
$excel.DisplayAlerts = $false
$excel.EnableEvents = $false
$workbook=$excel.Workbooks.Open($openfile,0,$false,5,"nopassword","nopassowrd")
$excel.Calculation = $xlCalculationManual
foreach ($worksheet in $workbook.Sheets)
{
foreach ($Text in $FindText)
{
If ($worksheet.UsedRange.replace($Text,$ReplaceText))
{
$found=$true
}
}
}
Looks like Theo is correct on this. I've not found anyway to increase the efficiency by removing the find.
Also it seems that on some files a replace only replaces the first instance and therefore a loop is also required.
Maybe try
$worksheet.UsedRange.replace($Text,$ReplaceText)
If ($?)
Instead of
If ($worksheet.UsedRange.replace($Text,$ReplaceText))
OR you could try searching for the text, and confirm that it found something?
Before your if replace option, try (I apologize, but this code is speculation, and may not full fix it. There is an article on this at https://msdn.microsoft.com/en-us/vba/excel-vba/articles/range-find-method-excel
$confirm = $worksheet.Used.Range.find($text)
if ($confirm -ne $null) {
Echo $true
$worksheet.UsedRange.replace($Text,$ReplaceText)
$confirm = $null
}
else{
echo $false
}

Where Command not Working? [duplicate]

Very new to coding in general, so I fear I am missing something completely obvious. I want my program to check for a file. If it is there, just continue the code. If it has not arrived, continue cheking for a given amount of time, or untill the file shows up. My loop works on its own, so when i only select the do-part in Powershell ISE, it works. But when i try running it inside the if statement, nothing happens. The loops doesnt begin.
$exists= Test-Path $resultFile
$a = 1
if ($exists -eq "False")
{
do
{
$a++
log "Now `$a is $a "
start-sleep -s ($a)
$exists= Test-Path $resultFile
write-host "exists = $exists"
}
while (($a -le 5) -and ($exists -ne "True"))
}
Another way of doing this is using a while loop:
$VerbosePreference = 'Continue'
$file = 'S:\myFile.txt'
$maxRetries = 5; $retryCount = 0; $completed = $false
while (-not $completed) {
if (Test-Path -LiteralPath $file) {
Write-Verbose "File '$file' found"
$completed = $true
# Do actions with your file here
}
else {
if ($retryCount -ge $maxRetries) {
throw "Failed finding the file within '$maxRetries' retries"
} else {
Write-Verbose "File not found, retrying in 5 seconds."
Start-Sleep '5'
$retryCount++
}
}
}
Some tips:
Try to avoid Write-Host as it kills puppies and the pipeline (Don Jones). Better would be, if it's meant for viewing the script's progress, to use Write-Verbose.
Try to be consistent in spacing. The longer and more complex your scripts become, the more difficult it will be to read and understand them. Especially when others need to help you. For this reason, proper spacing helps all of us.
Try to use Tab completion in the PowerShell ISE. When you type start and press the TAB-key, it will automatically propose the options available. When you select what you want with the arrow down/up and press enter, it will nicely format the CmdLet to Start-Sleep.
The most important tip of all: keep exploring! The more you try and play with PowerShell, the better you'll get at it.
As pointed out in comments, your problem is that you're comparing a boolean value with the string "False":
$exists -eq "False"
In PowerShell, comparison operators evaluate arguments from left-to-right, and the type of the left-hand argument determines the type of comparison being made.
Since the left-hand argument ($exists) has the type [bool] (a boolean value, it can be $true or $false), PowerShell tries to convert the right-hand argument to a [bool] as well.
PowerShell interprets any non-empty string as $true, so the statement:
$exists -eq "False"
is equivalent to
$exists -eq $true
Which is probably not what you intended.

Powershell loop only if condition is true

Very new to coding in general, so I fear I am missing something completely obvious. I want my program to check for a file. If it is there, just continue the code. If it has not arrived, continue cheking for a given amount of time, or untill the file shows up. My loop works on its own, so when i only select the do-part in Powershell ISE, it works. But when i try running it inside the if statement, nothing happens. The loops doesnt begin.
$exists= Test-Path $resultFile
$a = 1
if ($exists -eq "False")
{
do
{
$a++
log "Now `$a is $a "
start-sleep -s ($a)
$exists= Test-Path $resultFile
write-host "exists = $exists"
}
while (($a -le 5) -and ($exists -ne "True"))
}
Another way of doing this is using a while loop:
$VerbosePreference = 'Continue'
$file = 'S:\myFile.txt'
$maxRetries = 5; $retryCount = 0; $completed = $false
while (-not $completed) {
if (Test-Path -LiteralPath $file) {
Write-Verbose "File '$file' found"
$completed = $true
# Do actions with your file here
}
else {
if ($retryCount -ge $maxRetries) {
throw "Failed finding the file within '$maxRetries' retries"
} else {
Write-Verbose "File not found, retrying in 5 seconds."
Start-Sleep '5'
$retryCount++
}
}
}
Some tips:
Try to avoid Write-Host as it kills puppies and the pipeline (Don Jones). Better would be, if it's meant for viewing the script's progress, to use Write-Verbose.
Try to be consistent in spacing. The longer and more complex your scripts become, the more difficult it will be to read and understand them. Especially when others need to help you. For this reason, proper spacing helps all of us.
Try to use Tab completion in the PowerShell ISE. When you type start and press the TAB-key, it will automatically propose the options available. When you select what you want with the arrow down/up and press enter, it will nicely format the CmdLet to Start-Sleep.
The most important tip of all: keep exploring! The more you try and play with PowerShell, the better you'll get at it.
As pointed out in comments, your problem is that you're comparing a boolean value with the string "False":
$exists -eq "False"
In PowerShell, comparison operators evaluate arguments from left-to-right, and the type of the left-hand argument determines the type of comparison being made.
Since the left-hand argument ($exists) has the type [bool] (a boolean value, it can be $true or $false), PowerShell tries to convert the right-hand argument to a [bool] as well.
PowerShell interprets any non-empty string as $true, so the statement:
$exists -eq "False"
is equivalent to
$exists -eq $true
Which is probably not what you intended.

Powershell foreach loop with multiple if statements

I have a script snippet that basically gets some unformated xml type output from a command.
Then in a defined filter section I'm transforming that into xml and run a search loop on each node, as from the part below.
What I'm trying to figure out is how I can make a multiple if -and loop, like
if (($CimProperty.VALUE -eq $somevariable) -and ($CimProperty.VALUE -eq $something-else))
The only problem is that since it's a foreach loop it won't take it, as it takes each property at a time and then the 'if statement -and portion' for it, which doesn't work since it's the same xml type property section.
In other words the loop doesn't go through the entire array to identify both conditions from the if statement.
PS code snippet:
filter Import-CimXml
{
$CimXml = [Xml]$_
$CimObj = New-Object -TypeName System.Object
foreach ($CimProperty in $CimXml.SelectNodes(“/INSTANCE/PROPERTY”))
{
if ($CimProperty.VALUE -eq $somevariable)
{
write-host "found it"
}
}
}
I hope the scenario is clear, thanks everyone in advance!
For just two conditions, you can make it fairly straight forward like (the untested);
filter Import-CimXml
{
$foundfirst = $false
$foundsecond = $false
$CimXml = [Xml]$_
$CimObj = New-Object -TypeName System.Object
foreach ($CimProperty in $CimXml.SelectNodes(“/INSTANCE/PROPERTY”))
{
if ($CimProperty.VALUE -eq $somevariable)
{
$foundfirst = $true
}
if ($CimProperty.VALUE -eq $someothervariable)
{
$foundsecond = $true
}
}
if ($foundfirst -and $foundsecond)
{
write-host "found it"
}
}
For more conditions, you may want to use arrays of corresponding matchwords/booleans instead.
Just extend your xpath query to do it all. It's less code and should be more efficient.
filter Import-CimXml
{
$CimXml = [Xml]$_
$CimObj = New-Object -TypeName System.Object
if($CimXml.SelectNodes(“/INSTANCE[PROPERTY='$somevariable' and PROPERTY='$someothervariable']”).Count -gt 0) {
write-host "found it"
}
}