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

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.

Related

Web check script hangs on second run

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
}

How to get AWStats Error Notification via email?

I'm trying to find a way for an email notification in awstats.
The idea is that whenever there's an error (missing log files, statistics couldn't be generated) an email with an error message should be send to a specific email address.
I already found the config-Attribute "ErrorMessages" but as far as i get it its just for displaying an error.
Is there an attribute like "ErrorMessages" for activating mail notifications or do i have to implement it myself?
You can use cron job to run awstats update proccess.
And it'll sent update process result via email to you.
Example:
* * * * * /usr/local/awstats/update.sh | mail abc#xzy.com
I found a way to trap Errors while my code is executed. It's not an awstats feature, more a generic way:
Inside my script:
#Error Handling
set -e
function sendErrorNotification(){
echo "Awstats: An error occured during processing server logs." | mail -s "AWSTATS ERROR" "...#..."
}
trap sendErrorNotification EXIT
....code goes here...
set +e
trap - EXIT

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.
}

Is there a way to add errors from build step in TeamCity to the email notification?

I have a Powershell build step, and I'd like to add some messages fromt the script to the resulting email that is sent to people on the notification list. I see this happen for tests where the number of failures and the error is added to the email. But, how can I add my custom messages from the PowerShell build step to the resulting email?
Have you tried using service messages?
See here:http://confluence.jetbrains.com/display/TCD7/Build+Script+Interaction+with+TeamCity
You could use
write-host "##teamcity[message text='Its broken again' errorDetails='Your exception message' status='FAILURE']"
In order for the errors to be included in emails, I found I needed to add "compilationStarted" and "compilationFinished" tags, e.g:
##teamcity[compilationStarted compiler='Solution.sln']
##teamcity[message text='1>File.cpp(1): error C2065: "stackoverflow" : undeclared identifier' status='ERROR']
##teamcity[compilationFinished compiler='Solution.sln']
I use a Python script to parse the output from devenv, looking for specific strings to add as errors and warnings. The email adds these under a "compilation errors" section.
If you mean to pipe the output of an error that occurred in the Powershell script you are running then try piping the error object to a TeamCity service message after it has been caught
This is untested code but it might work for you:
trap [SystemException]
{
write-host "##teamcity[message text='An error occurred' errorDetails='$_' status='ERROR']";exit 1
}
OR
try
{
# Something...
}
catch
{
write-host "##teamcity[message text='An error occurred' errorDetails='$_' status='ERROR']";exit 1
}