Web check script hangs on second run - powershell

I am trying to connect to Google for a quick check of the Internet availability and host response. If the check returns 200, move on to next script.
The script below works initially. However, when I try multiple times, specifically after 2 runs, PowerShell hangs and doesn't move forward.
If I restart PowerShell and run the script, it runs OK for two times then it hangs again.
I am planning to put this in the Scheduler and run it regularly.
What am I missing here? Can anyone of you advise?
# Once connection gets established, quick status test
$request = [System.Net.WebRequest]::Create("http://www.google.com")
try {
$response = $request.GetResponse()
} catch {
if ($error) {
# write some error on the log
}
}
# if response returns 200, proceed next step, else create critical log
if ($response.StatusCode.value__ -eq 200) {
& ./hostCheck.ps1 ; # Start host Check
}

Related

FindItems() does not work in first run but works in the second run

I am trying to fetch latest mail from my Outlook Exchange server mailbox using PowerShell. I have seen that the most common solution is to do a FindItems() method on the inbox object. However, I find that that running the code first time throws error stating
Exception calling "FindItems" with "1" argument(s): "The request failed.
When I run it once again, the script completes successfully returning the last mail from my mailbox. In order to make it more clear, I wrote a script to execute the FindItems() method to execute twice in a while loop as shown below:
# bind to the Inbox folder of the target mailbox
$inbox = [Microsoft.Exchange.WebServices.Data.Folder]::Bind($ews,[Microsoft.Exchange.WebServices.Data.WellKnownFolderName]::Inbox)
echo outsideWhile
$i = 0
while ($i -ne 2) {
echo insideWhileBefore
$inbox.FindItems(1)
echo insideWhileAfter
$i += 1
}
The first execution of $inbox.FindItems(1) fails but the second execution goes through fine returning the desired results.
The result output is as shown below
outsideWhile
insideWhileBefore
Exception calling "FindItems" with "1" argument(s): "The request failed. The remote server returned an error: (501)" ........
insideWhileAfter
insideWhileBefore
<MAIL CONTENTS>
insideWhileAfter
Please help me out in understanding why this happening so and how I can overcome it.

How to automate VPN connection on Windows 10

I'm going to be traveling for the next month, and I'd like to automate the VPN connection process so that on X event, the script fires and automatically connects me. I've already configured the [L2TP/IPSec] VPN connection in ms-settings:network-vpn & verified it works, but it's automation step that's proving problematic.
Windows GUI: The credentials have been saved.
PowerShell: The RememberCredential property is set to True
VBScript: Curiously, the VPN connection is hidden:
Dim oShell : Set oShell = CreateObject("Shell.Application")
Dim NetConn : Set NetConn = oShell.Namespace(49)
Dim Connections : Set Connections = NetConn.Items
wscript.echo "Connection Count [" & Connections.Count & "]"
For i = 0 to Connections.Count - 1
wscript.echo "Connections.Item(" & i & ").Name: [" & Connections.Item(i).Name & "]"
next
rasdial <entry>: Expectedly returns error 691.
rasphone -d <entry>: Displays the Connection dialog whereas I'd prefer it to just connect automatically and hidden.
Is this even possible in Windows 10? Or am I just overlooking some small yet key detail?
I ended up leveraging Add-VpnConnectionTriggerApplication to trigger an automatic connection of the VPN on the launch of specific executables/UWP applications. The downside is that when doing this, PoSh warns that SplitTunneling must be enabled which is less than ideal.
However after playing around with it for a while (just 2 or so hours now) to ensure the VPN keys off specific executables/UWP's, I ended up disabling SplitTunneling and, paradoxically, it appears to continue working as I would hope/expect. I rebooted a few times, logged on and sure enough by the time the desktop loaded the VPN had been established.
I need to do more testing to confirm, but this is sufficient to help save me from myself.
I do this by checking the Remember my sign-in info checkbox when I created the VPN connection.
You can check this in your PowerShell script by ensuring that Get-VpnConnection returns RememberCredential : True.
If this is the case, then rasdial should automatically connect it.
I do it with this:
<#
.SYNOPSIS
Ensures vpn connection (assumed to have saved credentials) is connected.
#>
function Connect-Vpn
{
[CmdletBinding()]
param (
[object]
$Settings
)
$rr1 = Get-VpnConnection -Verbose:$false | where {$_.ServerAddress -imatch $Settings.VpnConnectionPattern -and $_.RememberCredential} | Select -First 1
if ($rr1.ConnectionStatus -ne 'Connected')
{
rasdial.exe $rr1.Name
If (-not $LASTEXITCODE)
{
throw "Cannot connect to '$($rr1.Name)'."
}
}
else
{
Write-Verbose "Already connected to '$($rr1.Name)'."
}
}
You will have to massage this code to your needs as this uses some fields from my settings file...

Return code of scheduled task prefixed with 0x8007000 in list view, registered as 0 in the event log

I am currently trying to setup monitoring of windows scheduled tasks in Zabbix. It seemed easy enough to just monitor the Microsoft-Windows-TaskScheduler/Operational event log filtered by 201 events and regexing on the return code, but when I started simulating errors to test the monitoring, nothing happened.
It turns out that all our windows 2012 servers always log "return code 0" in the event log, even though it actually, sort of, displays it correctly in the Task Scheduler list view. When I say "sort of", it's because the "Last Run Result" actually displays 0x80070001 if the exit code of the program run by the scheduled task is 1.
I have spend a lot of time tweaking the settings, like user account, Run only when user is logged on, Run whether user is logged on or not, setting path on the action, Run with highest privileges, Configure for Vista/7/2012, etc. Nothing helped.
Finally I did some testing on my local machine, Windows 7, and a 2008R2 server, both of which just worked as expected.
The specific task I was testing ran a PowerShell script, using -Command so that it properly propagates the exit, but to rule out any PS issues I also tested with a batch file containing "exit 1" and finally with a small C# console program, that just returns whatever you supply on the command line.
PS, batch and console program all work fine on 7 and 2008, but they all fail in the same manner on 2012.
I've google this to death, but keep coming up short. Apparently 0x80070005 and other similar error codes are have some meaning, but that's not what happens in my case. In my case it seems that my exit code is bitwise or'ed with 0x80070000.
I should note that in all the cases, even 2012, the program started by the task, actually executes and run to the end, it's just the exit code which is handled weirdly.
Following is the output from the test runs:
From Powershell (my shell writes :( if $LASTEXITCODE > 0 ):
54 :( .\ExitCodeTest.exe 1
55 :( $LASTEXITCODE
1
56 :) .\ExitCodeTest.exe 10
57 :( $LASTEXITCODE
10
Windows Server 2008 R2 Standard:
Last Run Result (from list view): 0xA
Event 201 from event log Microsoft-Windows-TaskScheduler/Operational:
Task Scheduler successfully completed task "\ErrorTest" ,
instance "{b67a26cf-7fd8-461a-93d9-a5e48e72e558}" ,
action "D:\Tasks\ExitCodeTest.exe" with return code 10.
Windows Server 2012 Datacenter (notice that the return code in the event log is 0):
Last Run Result (from list view): 0x8007000A
Event 201 from event log Microsoft-Windows-TaskScheduler/Operational:
Task Scheduler successfully completed task "\error test" ,
instance "{2bde46b8-2858-4772-a7ec-d66b29d893a6}" ,
action "D:\Tasks\ExitCodeTest.exe" with return code 0.
Source for ExitCodeTest.exe:
static void Main( string[] args )
{
int exitCode = 0;
if ( args.Length > 0 )
{
exitCode = Convert.ToInt32( args[0] );
}
Environment.Exit( exitCode );
}
Please help, I am at my wits end.
Thanks,
John
(this is NOT an answer, but StackOverflow is refusing to let me add comments - when I click 'add comment', browser scrolls to top of page :-/)
You may be misinterpreting the Last Run Result column. According to Wikipedia (http://en.wikipedia.org/wiki/Windows_Task_Scheduler), LRR values of 0, 1 and 10 are common. Ignore the 0x8007 prefix - this just indicates a WIN32 error code transformed into an HRESULT (http://msdn.microsoft.com/en-us/library/gg567305.aspx).
Try running the test and forcing an exit code of something other than 1 or 10 to see if this influences LRR.
This does not explain of course why action return code is 0 in 2012. Error code 10 is defined as 'environment is incorrect'. Could it be that 2012 server does not want to run 32bit executable?
One other suggestion (and I'm a little out of my depth); according to (http://msdn.microsoft.com/en-us/library/system.environment.exit(v=vs.110).aspx): "Exit requires the caller to have permission to call unmanaged code. The return statement does not.". Might be worth re-compiling ExitCodeTest as follows:
static int Main(string[] args)
{
int exitCode = 0;
if ( args.Length > 0 )
{
exitCode = Convert.ToInt32( args[0] );
}
return exitCode;
}
I'm seeing a similar issue on Server 2012 with a batch file that looks like it succeeds, shows a return value of 0 in event log, but a Last Run Result of 0x80070001.
I see MSFT has a hotfix available for Server 2012 which might address this issue:
http://support.microsoft.com/kb/3003689
I had this problem and fixed it this way.
Instead of calling a batch file move the commands into the actions section of the scheduled task.
I realize this may not work for you as some batch files are long.
I suspect it has to do with circumventing security on a scheduled task -- if you can change the batch file then you could get a scheduled task to run as the identity without windows being the wiser.

How do I get topshelf to return error code when command fails?

I am trying to start my service with powershell but currently it fails. I don't know why it fails but that is not the point here. When trying to start the host all I don't get the correct exit code so my automatic deploy fails silently.
What I'm trying to do is:
$cmd = "$folder" + "\MyService.exe"
try
{
& $cmd stop
& $cmd uninstall
& $cmd install
& $cmd start
}
catch
{
Write-Host "Error: Update of service failed"
exit 1
}
The start command fails with the following messge:
Topshelf.Hosts.StartHost Error: 0 : The service failed to start., System.InvalidOperationException: Cannot start service MyService on computer '.'. ---> System.ComponentModel.Win32Exception: The service cannot be started, either because it is disabled or because it has no enabled devices associated with it
--- End of inner exception stack trace ---
at System.ServiceProcess.ServiceController.Start(String[] args)
at System.ServiceProcess.ServiceController.Start()
at Topshelf.Runtime.Windows.WindowsHostEnvironment.StartService(String serviceName)
at Topshelf.Hosts.StartHost.Run()
and I never get into the catch statement of my powershell script.
UPDATE:
Note that I am asking for how to get the method to the catch statement and not the solution to the actual exception. I have solved the actual exception but I want better feedback in the future if it fails, and that is want the catch statement to be executed which it isn't in case of error.
try/catch in PowerShell doesn't work with exe.
After myservice.exe calls you need to check the automatic variable $LastExitCode.
Try something like this:
$out = & $cmd start
if ($LastExitCode -ne 0) # if exe returns 0 on success, if not change the condition accordingly
{
"ERROR: $out"
return # to exit script or do something else.
}

Error handling in Net::Openssh (host ,async =>1) option

I am using Openssh module to connect to hosts using the (async => 1) option.
How is it possible to trap connection errors for those hosts that are not able to connect.I do not want the error to appear in the terminal but instead be stored in a data structure, since I want to finally format all the data as a cgi script.When I run the script the hosts that has a connection problem throw error in the terminal.The code executes further and try to run commands on disconnected hosts.I want to isolate the disconnected hosts.
my (%ssh, %ls); #Code copied from CPAN Net::OpenSSH
my #hosts = qw(host1 host2 host3 host4 );
# multiple connections are stablished in parallel:
for my $host (#hosts) {
$ssh{$host} = Net::OpenSSH->new($host, async => 1);
$ssh{$host}->error and die "no remote connection "; <--- doesn't work here! :-(
}
# then to run some command in all the hosts (sequentially):
for my $host (#hosts) {
$ssh{$host}->system('ls /');
}
$ssh{$host}->error and die "no remote connection doesn't work".
Any help will be appreciated.
Thanks
You run async connections. So program continue work and dont wait when connection is establised.
After new with async option you try to check error but it is not defined because connection in progress and no information about error.
As i understand you need wait after first loop until connection process got results.
Try to use ->wait_for_master(0);
If a false value is given, it will finalize the connection process and wait until the multiplexing socket is available.
It returns a true value after the connection has been succesfully established. False is returned if the connection process fails or if it has not yet completed (then, the "error" method can be used to distinguish between both cases).
for my $host (#hosts) {
$ssh{$host} = Net::OpenSSH->new($host, async => 1);
}
for my $host (#hosts) {
unless ($ssh{$host}->wait_for_master(0)) {
# check $ssh{$host}->error here. For example delete $ssh{$host}
}
}
# Do work here
I don't check this code.
PS: Sorry for my English. Hope it helps you.