Full Code - Pastebin.com
I am attempting to refine my PowerShell script by adding in error messages if they appear.
I am planning for
If a Username already exists in our AD environment
If the "NewUsername" text box is left blank
these are just the first 2 examples I can see causing a problem going forward.
I have been researching around, and I believe i should be using try/catch blocks. However I am unsure of how to incorporate them, and how to pull specific error messages.
Do I do start that by adding the try/catch blocks at this location in the code?
$CreateAccount = New-Object system.windows.Forms.Button
$CreateAccount.Text = "Create Account"
$CreateAccount.Width = 127
$CreateAccount.Height = 27
$CreateAccount.Add_MouseClick({
#add here code triggered by the event
try
{
#code to actually run here
}
catch
{
#code to display error messages if any come up
}
If so, can someone point me in the right direction to grab the 2 error types so I can display them to the user running the script?
I feel I must also point out that I convert the .ps1 script to an .exe file with no console showing when it is ran. Will this cause issues for that?
Related
(Resolved: The delay/issues I was having, was not due to the delay of adding in try-catch, or redirecting errors to null. It was a result of using usernames that were not real, for testing the script, as opposed to actual/production names. The AD lookup times are obviously different -- didn't think of that before.)
I've been editing https://github.com/dafthack/DomainPasswordSpray for a work project, with the intent of adding in logging. The script outputs to a logfile about 6 times a second, which throws ioexception errors about accessibility of the file. It's a nonterminating error.
I'm ok with the error and potentially non-logged info. However, it clutters the console.
Since it's a non-terminating error, I tried set-content -erroraction 'silentlycontinue', but the error is still displayed. However, there is no measurable performance impact -- just a cluttered console.
So researching further, I tried a try/catch block, which does eliminate the error from the console, BUT the script now takes a tad over 2x as log to run.
Is there a 3rd alternative?
I can mitigate it by splitting the data lists into two, and running the script twice, concurrently. But it's less than idea, as I'm actually already splitting the data list up to speed up the process. (single list takes 2 hours, and 30m is the goal, so I'd need 8 windows to maintain current timing...)
Anyway. Hope that makes sense. Any thoughts/input appreciated. (attempting to copy the code to a machine where I can upload a portion here for those who want to review, but gmail blocks it. working on it.)
The code causing issues:
$FileLocation2 = "LOG-LastTested_$($Userlist)"
# Write out the last user tried
$tm = get-date
# This file is written to so rapidly, errors can occur, b/c it's still open, "In use by another process. SilentlyContinue not working, using try-catch which surpresses error (but is 2x slower).
Try {Write-output "Num: $cu, Name: $name, Pass: $Password, Time: $tm" | set-content -erroraction 'stop' $FileLocation2}
Catch [System.IO.IOException] {continue}```
Resolved: The delay/issues I was having, was not due to the delay of adding in try-catch, or redirecting errors to null. It was a result of using usernames that were not real, for testing the script, as opposed to actual/production names. The AD lookup times are obviously different -- didn't think of that before.
I was testing the error suppression (try-catch/redirect to null) with a list of dummy users. When I checked the rate of testing, it had dropped from 10 users/second with production accounts, to 3/s with dummy accounts. After reverting all the error suppression it was still at the slower 3/s rate. So I put my try-catch lines back in, and tried with production accounts, and it worked great -- 8-10 users/sec.
So, the issue was due to the only change: using dummy accts instead of production. Once I went back to all production accounts, WITH my error surpression -- worked like a champ. Hope that helps someone else.
Thanks to #RetiredGeek and #Mr.Sven who kept me testing and looking for a solution.
I am writing a autologin script in Powershell. With main purpose of doing autologon with keystrokes on remote clients in our environment after installation, with the desired AD and password entered.
Works fine on my i9. But most people using Tablets and Elitebooks so using
Thread Sleep
Works bad since i would need to have custom timing on Every hardware, or very high default numbers for lower end clients using my script
Is there any way adding an "wait for row above to completed" Before continuation to next.
I don't have enough on your current code to produce a more accurate answer but the idea, in all cases, remains the same.
You should periodically wake up the thread to check whether or not the machine is in the state you want it in and from there, you either go back to sleep or exit the loop and continue.
The delay is up to you but you want to find a sweet spot to have great performance and reactivity.
Example (based on your description)
$IsLoggedIn = $false
while (! $IsLoggedIn) {
$IsLoggedIn = 'Custom Logic returning $true if the user is logged in'
if ($IsLoggedIn) { break }
Start-Sleep -Milliseconds 100
}
You just need to figure out the thing you want to use as the check to validate the computer is in the correct state you need it in before proceeding further.
I'm trying to create a Selenium script in Powershell that automatically buys something that I tell it to. I've gotten it past finding the item, and clicking the Buy Now button, but then this window pops up and I've tried what seems like 3000 different ways of failing to click the Place your order button. Web code to the right. Appears to be the "turbo-checkout-pyo-button", but finding it by ID, XPath, CSSselector, etc have all failed for me. It's not a wait issue. I've even thrown in an explicit (and overly long) 5 second delay to be sure this field is present and "should" be clickable. Any ideas?
I've tried all of these. They're all followed by $placeYourOrderBtn.click() (and have all failed):
$placeYourOrderBtn = $ChromeDriver.FindElementByXpath("//*[#id='turbo-checkout-pyo-button']")
$placeYourOrderBtn = $ChromeDriver.FindElementByXPath("//*[#id='turbo-checkout-place-order-button']")
$placeYourOrderBtn = $ChromeDriver.FindElementByXPath("//span[text() = Place your order]")
$placeYourOrderBtn = $ChromeDriver.FindElementById("turbo-checkout-place-order-button-announce")
$placeYourOrderBtn = $ChromeDriver.FindElementById("turbo-checkout-pyo-button")
$placeYourOrderBtn = $ChromeDriver.FindElementByCssSelector("#turbo-checkout-pyo-button")
I did this for a windows that sends email. You have to click the button to open the new window, then use "SwitchTo()" to change to the new window.
[void]$Webdriver.SwitchTo().Window($WebDriver.WindowHandles[1])
You may have to read the window handles attribute and query each one to determine which one you need to open.
I have a Perl script which listens to a port and filters messages, and, based on them, proposes to take action or ignore event.
I'd like to make it show a notification window (not a dialogue window) with buttons 'take action' and 'ignore', which would go after a certain timeout.
So far I have something like this:
my #react = ("somecommand", "someoptions); # based on what regex a message matched
my $cmd = "xmessage";
my $cmd_args = "-print -timeout 7 -buttons React,Dismiss $message"; # raw message from port
open XMSG, "$cmd $cmd_args |";
while (<XMSG>) {
if ($_ eq "React\n") {
do something...
}
}
But it would handle only one notification at once, and the next message would not appear until the previous one is dismissed, reacted to or timed out, so it's quite a bad decision. I cannot do anything until I get return code from xmessage, and I can't get xmessage run a command. Well I probably can if I introduce event IDs and listen to a socket where xmessage prints, but it would make things too complicated, I guess.
So I wonder is there a library or an utility for Linux to draw notify-like windows with buttons which would each trigger a command?
I'm sorry I didn't see this one when it first was posted. There are several gui toolkits which could do something along these lines. Prima is a toolkit built especially for Perl and has no external library dependencies.
For when you just need a popup dialog, there is the Ask module which delegates the task of popping up windows to any available library.
In case anyone's interested, I've ended up writing a small Tcl/Tk program for that, the full code (all 48 lines) can be found here: http://cloudcabin.org/read/twobutton_notify, and you can ignore the text in Russian around it.
I am trying to call an existing VFP 6 application using Jacob which is a COM bridge for Java.
val vfp = new Application(new ActiveXComponent("VisualFoxPro.Application").getProperty("Application").toDispatch())
vfp.setVisible(false)
try {
vfp.doCmd("do my.exe with myconfig.txt")
} catch {
case t: Throwable => t.printStackTrace
} finally {
vfp.doCmd("close data")
vfp.doCmd("clear all")
vfp.doCmd("clear")
vfp.quit
vfp.safeRelease
}
When there are no error conditions this code executes well and generates the expected .dbfs. The problem is that when an error occurs (.dbf not found, file in use by another user, etc) a GUI window pops up and stops execution of the program until I use the mouse to cancel it. I want this program to run on a server with no user interaction so this won't work.
How can I gracefully handle the errors preferably without making a change to the VFP 6 program?
Since you have the source code for VFP6, I would suggest looking into
SYS(2335,0)
Sys 2335 is used to identify if the program is running in an "unattended" mode, any such popup dialog boxes will throw an error and prevent an actual "hit" ok/cancel/whatever button to continue. This includes popup window prompting user to pick a table.
I'm not positive of when it was made available as I had limited use of it. Like you, when dealing with a COM server under IIS and obviously nobody there to respond.
Start JVM in headless mode, catch HeadlessException or something. Or, write a Java program that will execute your GUI program using Runtime, and restart in a case of parsed errors in console.