PowerShell - Remote Sessions, Try{}Catch{}, ErrorActionPreference

Hello everyone,
I am encountering issues with Remote Exchange sessions and was wondering what I am overlooking/over-complicating.
I am running Windows 8.1/PowerShell 4.0. Reason I mention this is because of this blog post:
http://blogs.msdn.com/b/powershell/archive/2013/10/25/windows-management-framework-4-0-is-now-available.aspx
The IMPORTANT section noted that Exchange 2007, 2010, 2013 are not compatible with WMF 4.0 and didn't know if that is good/bad since the OS is using PowerShell 4.0.
1 - I am connecting to Office 365 utilizing the following:
http://help.outlook.com/en-us/140/cc952755.aspx
2 - I have the following function:
function Get-SomeMailboxStatistics {
[CmdletBinding()]
param(
[Parameter(Mandatory=$True,
ValueFromPipeline=$True,
HelpMessage="Identities or aliases to gather Exchange Statistics from.")]
[Alias('Username')]
[string[]]$Identity,
[string]$ErrorLog = 'C:\MbxStatsErrorLog.txt',
[switch]$LogErrors
BEGIN{}
PROCESS{
Write-Verbose "Beginning..."
foreach ($alias in $Identity)
Write-Verbose "Gathering info for $alias."
#trap [ManagementObjectNotFoundException] {$everythingOK = $false}
Try{
# $ErrorActionPreference = "Stop" # Testing purposes.
$everythingOK = $true
$gms = Get-MailboxStatistics -Identity $alias -ErrorAction Stop # http://technet.microsoft.com/library/hh847884.aspx
# Trap {
# throw $_
Catch{
$everythingOK = $false
Write-Warning "Lookup on $alias failed."
if ($LogErrors -eq $true){
$alias | Out-File $ErrorLog -Append
Write-Warning "Logged $alias to $ErrorLog."
if ($everythingOK){
$props = @{};
$props = @{'Alias' = $alias;
'DisplayName' = $gms.DisplayName;
'TotalItemSizeInBytes' = ($gms.TotalItemSize.Value.ToString() -replace "(.*\()|,| [a-z]*\)", "");
'TotalDeletedItemSizeInBytes' = ($gms.TotalDeletedItemSize.Value.ToString() -replace "(.*\()|,| [a-z]*\)", "");
'MailboxType' = $gms.MailboxType; };
$obj = New-Object -TypeName PSObject -Property $props
Write-Output $obj
END{}
Example: Get-SomeMailboxStatistics -Identity GoodAlias1,GoodAlias2,FailAlias,GoodAlias3 -LogErrors -ErrorLog 'C:\Logs\MbxStatsErrors.txt' -Verbose
The pipeline terminates on FailAlias, and then throws an error when it tries to pass the FailAlias to the $props.
$gms | Get-Member on a good alias is:
TypeName: Deserialized.Microsoft.Exchange.Management.MapiTasks.Presentation.MailboxStatistics
I have tried setting $ErrorActionPreference = 'Stop' in various sections and think I am scope-creeping/not catching the Error where I should be or PowerShell is flat-out ignoring something.
I have tried additional nested if{}else{} in the Try{}Catch{} and cannot get it to behave as expected.
I have also tried to Trap{[ManagementObjectNotFoundException]} and Throw exception in various portions without success.
However, setting $ErrorActionPreference = 'Stop' in the session window (from default of 'Continue') the script behaves as I expected it to, when encountering a non-existant mailbox, it logs the error. It doesn't seem to have issues executing on Windows 8.0/PowerShell
3.0.
I have encountered numerous blog/forum posts with no definitive answer/resolution.
Based some of my tests around some suggestions from this thread:
http://stackoverflow.com/questions/1142211/try-catch-does-not-seem-to-have-an-effect
Extras:
http://blogs.technet.com/b/heyscriptingguy/archive/2010/03/09/hey-scripting-guy-march-9-2010.aspxhttp://stackoverflow.com/questions/19553278/powershell-catch-non-terminating-errors-with-silentlycontinue
http://stackoverflow.com/questions/15545429/erroractionpreference-and-erroraction-silentlycontinue-for-get-pssessionconfigur
http://social.technet.microsoft.com/Forums/scriptcenter/en-US/228a3329-f564-4daa-ad70-6d869b912246/non-terminating-error-turned-into-a-terminating-error?forum=winserverpowershell

This is not the only problem with WMF 4.0
When you use -ErrorAction 'SilentlyContinue', $Error object is not set.
[PS]
$Error.Clear()
[PS]
$objContact =
Get-Contact -Identity
'CN=unknown contact,OU=Users,DC=mydomain,DC=mytopdomain'
-ErrorAction 'Stop'
The operation couldn't be performed because object 'mytopdomain.mydomain/Users/unknown contact' couldn't be found on 'mydc.mydomain.mytopdomain'.
    + CategoryInfo          : NotSpecified: (:) [Get-Contact], ManagementObjectNotFoundException   
+ FullyQualifiedErrorId : 482E7079,Microsoft.Exchange.Management.RecipientTasks.GetContact
    + PSComputerName        : myexchange.mydomain.mytopdomain
[PS]
$Error.Count
1
[PS]
$Error.Clear()
[PS]
$objContact =
Get-Contact -Identity
'CN=unknown contact,OU=Users,DC=mydomain,DC=mytopdomain'
-ErrorAction 'SilentlyContinue'
[PS]
$Error.Count
0
That's why since Exchange 2010 SP3 Rollup 5 (i suppose when reading Exchange Supportability Matrix), The Exchange Management Shell link has been updated to use Powershell 2.0
Before 2010 SP3 Rollup 5
C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe -noexit -command ". 'C:\Program Files\Microsoft\Exchange Server\V14\bin\RemoteExchange.ps1'; Connect-ExchangeServer -auto"
After 2010 SP3 Rollup 5
C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe -version 2.0 -noexit -command ". 'C:\Program Files\Microsoft\Exchange Server\V14\bin\RemoteExchange.ps1'; Connect-ExchangeServer -auto"

Similar Messages

  • How to set IPaddress to a VM which has Linux OS using powershell remoting.

    I have downloaded the SetLinuxVM scripts for setting the ipaddress of virtual machine which has Linux as OS. I have 2 different Hyperv host machines for Eg: HostServer1 and HostServer2  and I have installed SetLinuxVM scripts on server HostServer1 but
    my LinuxVM is created in HostServer2 and is highly available.
    Now I have development server from where I connect to any of these HyperV servers remotely .
    I have created powershell remote session from my development server to HostServer1 where SetLinuxVM scripts are installed and excuting the script as given below.
    Set-LinuxVM -VMName "TestLinuxVM" -Manager "Hyper-V" -VMHost "HostServer2"
    -Username "root" -Password "Gen#123" -Hostname "TestLinuxSrv " -IPAddress "192.168.2.2" -SubnetMask "255.255.0.0" -GatewayAddress "192.168.2.1" -PrimaryDNSAddress "8.8.8.8" 
    Even though I am providing the -VMHost and even if the VM is in cluster its not executing the scripts and I am getting the error  WMI not available.
    Its working fine if the scripts are installed on HostServer2 where the LinuxVM is created but my question is that do we need to install the scripts on all HyperV hosts then whats the use of the above parameter -VMHost "HostServer2"  because if
    the hyperv host is remotely connected using powershell we need to provide the VMHost name in the above scripts.
    From the examples provided in the SetLinuxVM module my understanding is that if the SetLinuxVM module is installed in any of the Hyperv servers which  are in a cluster and even though the VM is created in any of the servers and is highly available by just
    providing the VMHost for that particular VM we can set the IPadress ,hostname etc by connecting remotely using powershell to the HostServer which has SetLinuxVM module by providing the VMHost name in the above script .
     Hoping that my problem will be resolved at your earliest convenience.
    Thanks in advance,
    Fayaz Syed.
    FayazSyed

    I am not familiar with these scripts, but in general any modules must exist on the target Hyper-V server.
    The commands do not appear to be suing SCVMM, in which case you would execute the PowerShell script at the VMM console machine.
    Brian Ehlert
    http://ITProctology.blogspot.com
    Learn. Apply. Repeat.

  • Issues using SharePoint PowerShell cmdlets using PowerShell Remoting

    We are having an issue with the SharePoint 2010 management cmdlets inside of a PowerShell Remoting session.
    Here is a example code output (stripped of company-specific data):
    Windows PowerShell
    Copyright (C) 2009 Microsoft Corporation. All rights reserved.
    PS C:\> $Server = "server.domain.msd"
    PS C:\> $Credential = Get-Credential "domain\admin"
    PS C:\> $Session = New-PSSession -ComputerName $Server -Credential $Credential -Authentication "CredSSP" -UseSSL -SessionOption $(New-PSSessionOption -SkipCNCheck -OperationTimeOut 0 -OpenTimeOut 10000)
    PS C:\> Enter-PSSession $Session
    [server.domain.msd]: PS C:\> Add-PSSnapin "Microsoft.SharePoint.PowerShell"
    [server.domain.msd]: PS C:\> New-SPUser -UserAlias "domain\spadmin" -sitecollectionadmin -web "http://sharepoint"
    New-SPUser : You need to be a site collection administrator to set this property.
    + CategoryInfo : InvalidData: (Microsoft.Share...SPCmdletNewUser:SPCmdletNewUser) [New-SPUser], SPExcepti
    on
    + FullyQualifiedErrorId : Microsoft.SharePoint.PowerShell.SPCmdletNewUser
    [server.domain.msd]: PS C:\> whoami
    domain\admin
    [server.domain.msd]: PS C:\>
    However if I run the command on the remote system inside of an RDP session it works fine:
    Windows PowerShell
    Copyright (C) 2009 Microsoft Corporation. All rights reserved.
    PS C:\> Add-PSSnapin "Microsoft.SharePoint.PowerShell"
    PS C:\> New-SPUser -UserAlias "domain\spadmin" -sitecollectionadmin -web "http://sharepoint"
    UserLogin DisplayName
    i:0#.w|domain\... DOMAIN\spadmin
    PS C:\> whoami
    domain\admin
    PS C:\>
    This looks like it has something to do with WinRM not being an elevated shell, because when I use the SharePoint API inside of WinRM I need to use RunWithElevatedPrivileges.  Does anyone know of a way around this limitation?

    Hye i found a way to run sharepoint cmdlets from remote computer on this blog. Actually we need to use credssp authentication mechanism.
    hope it helps others.
    http://www.liberalcode.com/2013/04/running-sharepoint-cmdlets-from-remote.html

  • Powershell generic session and import this session in Exchange remote management session c#

    The situation :
    I am trying to make an application (c#-asp.net) to manipulate user's on an exchange server. The application will be on a different server than the exchange's one. So, to manipulate the data, I am using an "Exchange remote management session" created
    with c#. Exchange remote management session give access to simple powershell command like "New-Mailbox" and "Set-User" - This is good for simple task, but in my case, I have to do more complexe operations that will need some specific command
    that is not included in the default command. To access this command, I have to use some specific module like "ActiveDirectory". It is simple ? Only use "Import-Module" ! Not really, like I said, the "Exchange remote management session"
    is very limited with the command, and "Import-Module" is not allowed...
    So what we can do ?
    I read a lot about my problem, and the most "simple" (That I understand the theory) solution is something like :
    Start with a generic PS session, import the AD module, then connect to an Exchange management session and do an Import-PSSession and use implicit remoting for the
    Exchange management stuff.
    Given that I am pretty new to manipulate the Powershell with c#, I have no idea how to use this awesome solution in my code. So I am asking your help.
    Here's my current code :
    // Prepare the credentials.
    string runasUsername = @"MarioKart 8";
    string runasPassword = "MarioKart";
    SecureString ssRunasPassword = new SecureString();
    foreach (char x in runasPassword)
    ssRunasPassword.AppendChar(x);
    PSCredential credentials =
    new PSCredential(runasUsername, ssRunasPassword);
    // Prepare the connection
    var connInfo = new WSManConnectionInfo(
    new Uri("MarioKart8Server"),
    "http://schemas.microsoft.com/powershell/Microsoft.Exchange",
    credentials);
    connInfo.AuthenticationMechanism =
    AuthenticationMechanism.Basic;
    connInfo.SkipCACheck = true;
    connInfo.SkipCNCheck = true;
    // Create the runspace where the command will be executed
    var runspace = RunspaceFactory.CreateRunspace(connInfo);
    // create the PowerShell command
    var command = new Command("New-Mailbox");
    // Add the command to the runspace's pipeline
    runspace.Open();
    var pipeline = runspace.CreatePipeline();
    pipeline.Commands.Add(command);
    // Execute the command
    var results = pipeline.Invoke();
    if (results.Count > 0)
    System.Diagnostics.Debug.WriteLine("SUCCESS");
    else
    System.Diagnostics.Debug.WriteLine("FAIL");
    This code work great for simple task (like "New-Mailbox") ! But how can I create a "generic PS session" and then use this session in the "Exchange remote management session" ?

    Hi Vincent,
    Generally we can use the cmdlet "import-module" to import the AD module on DC (Domain Controller), and we can also create a exchange remote powershell session with the cmdlet new-pssession, for more detailed information to create exchange remote session,
    please refer to this article:
    Managing Exchange 2010 with Remote PowerShell
    In addition, to invoke powershell cmdlet in C#, please also try to save all the cmdlets to a powershell script (.ps1 file), then we can add the powershell script to C# like:
    Pipeline pipeline = runspace.CreatePipeline();
    pipeline.Commands.AddScript(scriptText);
    If I have any misunderstanding, please let me know.
    Best Regards,
    Anna Wang

  • Hyper-V 2012 R2. RemoteFx. "The remote session was disconnected because there were network problems during the licensing protocol. Please try connecting to the remote computer again."

    After a Installation from Windows 8.1/windows 7 everything works fine. For example  Install updates and Software. If I connect the first time a remotefx card i can use RDP as well. But if i restart the host I get the mentioned error. What can I do. These
    Hosts are not in a domain configuration. I tried it too but there was  no difference. I didn't discovered any errors in the eventlog, too. Only an actviex error. But same errors occurs with a succsefull rdp session.
    Also strange is if i start the vm without a remotefx card it works fine again. Only session with a Remotefx card aren't possible anymore.
    Is there a bug or something. I tried it many times with the same error.
    Maybe someone can help me. 
    kind regards  
    Tobi

    Hi Tobi,
    Thank you for posting in Windows Server Forum.
    For a workaround, please try to perform the two steps.
    1. Do NOT enable RDP 8 on the Windows 7 SP1 VM.  You should install RDP 8 and update the ICs though.
    2. Change the connection setting on the client from "Automatically detect" to "LAN"
    Please check again below thread for information.
    a. "The remote session was disconnected
    because there were network problems during the licensing protocol" after enabling RemoteFX Windows 8 VM
    (Please recheck answer by “dgeddes”)
    b. "The remote session
    was disconnected because there were network problems during the licensing protocol" After Installing RemoteFX
    Hope it helps!
    Thanks,
    Dharmesh

  • Exchange 2013 remote session running as PowerShell version 2.0. How can I get it to run version 3.0?

    I'm trying to use the newer Powershell 3.0 features, particularly the ability to disconnect/reconnect a remote session, for our Exchange 2013 administration tools.  I have 3.0 on my workstation, and am connecting to a remote session on an Exchange 2013
    server (on Server 2012).   Even LOCALLY on the Exchange 2013 server Exchange Management Shell I get the same behavior:
    Exchange Command Shell on an Exchange 2013 server (running Windows Server 2012)
    [PS] >$PSVersionTable
    Name                           Value
    PSVersion                      3.0
    WSManStackVersion              3.0
    SerializationVersion           1.1.0.1
    CLRVersion                     4.0.30319.19117
    BuildVersion                   6.2.9200.16628
    PSCompatibleVersions           {1.0, 2.0, 3.0}
    PSRemotingProtocolVersion      2.2
    [PS] C:\Windows\system32>Get-PSSession
     Id Name            ComputerName    State         ConfigurationName
      1 Session1        mercmbx35r.n... Opened        Microsoft.Exchange
    [PS] C:\Windows\system32>$session = Get-PSSession
    [PS] C:\Windows\system32>$session.ApplicationPrivateData.PSVersionTable
    Name                           Value
    PSVersion                      2.0
    PSCompatibleVersions           {1.0, 2.0, 3.0}
    PSRemotingProtocolVersion      2.2
    BuildVersion                   6.2.9200.16628
    CLRVersion                     4.0.30319.19117
    WSManStackVersion              3.0
    SerializationVersion           1.1.0.1
    How/where can I force the Exchange session to run version 3.0?
    Thanks in advance,
    Rick Tatem

    I still can't get it to work that way. I changed my cfexecute to:
    <cfexecute name="C:\windows\system32\cmd.exe" arguments="/c C:\Inetpub\wwwroot\captcha\#cmd_filename#" outputFile="C:\testoutput.txt" timeout = "90"></cfexecute>
    And I changed my bat file to have:
    <cfsavecontent variable="cmd_content">
    cd\
    TSC.exe /s "#newString#" C:\Inetpub\wwwroot\captcha\#FileName# Mary (for Telephone)
    </cfsavecontent>
    The output file is showing:
    C:\ColdFusion9\runtime\bin>cd\
    C:\>TSC.exe /s "3.....P.....4.....Z.....8.....U.....7.....X....." C:\Inetpub\wwwroot\captcha\3P4Z8U7X-105724.wav Mary (for Telephone)
    I still can't get it to run the exe. I have watched the process list while running this and the exe doesn't show up. I tried cfexecute on the exe directly before trying the bat method, with hard coded arguments, and it still didn't work. I am so lost right now this makes no sense to me.

  • Can i catch a virus through Teamviewer App (doing a remote session with other computer) in my iPad?

    Can i catch a virus through Teamviewer App (doing a remote session with other computer) in my iPad?

    There are no viruses that can affect the iPad.  And a teamviewer session is a remote connection to a computer. Anything you do in the teamviewer session is happening on the remote computer not on your iPad, so unless you manually transfer a file to the iPad there's no way for a virus to move through the session.
    And as I said, even if you transferred an infected file from the remote machine, the virus can't run on an iPad so it would not affect it.

  • Force PowerShell version on remote session

    Hi, as the title suggest, I want to explicitly use PowerShell 2.0 to execute scripts and commands, why? Because SharePoint 2010 only supports PowerShell 2.0. So my problem:
    I have SharePoint 2010 installed on a Windows Server 2012 (with PowerShell 4.0 as default). When I execute a SharePoint PowerShell command on the server, it only works when I go to a PowerShell 2.0 console (powershell.exe
    -v 2). But when I am on another server and start a PowerShell 2.0 console, the remote session I create with e.g. Enter-PSSession is always PowerShell 4.0, the version of the host. This will prevent me from executing SharePoint commands remotely
    So my question is, is it possible in some way to force a specific version of PowerShell with a remote session?

    Hi TechPeepz,
    To start powershell 2.0 on remote session, please refer to the steps below:
    Server02 remote access Server01
    1. Run the cmdlet below on server01
    Register-PSSessionConfiguration -Name PS2 -PSVersion 2.0
    2. Run the cmdlets below on server02
    $s = New-PSSession -ComputerName Server01 -ConfigurationName PS2
    Enter-PSSession -Session $s
    For more detailed information, please refer to this article:
    Starting the Windows PowerShell 2.0 Engine
    If there is anything else regarding this issue, please feel free to post back.
    Best Regards,
    Anna Wang

  • Using PowerShell Remoting with Workflows and Functions

    Hello,
    I have an existing set of scripts with a mixture of Modules containing the functions, Workflows that call the functions and Main script that invokes the workflows.
    Step 1: The Main script picks up the list of servers from a custom db and invokes the relevant workflow for further operation
    Step 2: The workflow runs as foreach parallel and calls a function by passing the server name as a parameter
    Step 3. The function in the module does the real job
    All of this runs, from a central location. 90% of the server are geo dispersed. This seems to be a bit of a concern in terms of turnaround time is too high. 
    Hence, I would like to use WinRM (PowerShell Remoting). I have configured WinRM on all the Server with Firewall Exception.
    My Queries:
    1. Apart from using Enter-PSSession or Invoke-Command, are there any other CMDLet's?
    2. Say for example; I plan to use Enter-PSSession, should I embed the code with Workflow?
    3. How will it retrieve the output?
    Please advice, Thanks
    Rajiv

    You cannot use Enter-PSSession in a script.  
    It's only intended to be used interactively from the console. If you try to use it in a script, the script will run the subsequent commands on the local system, not in the remote session.
    You'll need to use Invoke-Command, and you'll have to include the function definitions in the invoked script block, since those functions will not exist in the remote sessions.
    [string](0..33|%{[char][int](46+("686552495351636652556262185355647068516270555358646562655775 0645570").substring(($_*2),2))})-replace " "

  • Unable to Change Screen Resolution in Remote Session - Windows Server 2012 R2

    Does anybody know of a way to allow Remote Desktop users to adjust their own screen resolution in a remote session under Windows Server 2012 R2? We are struggling with this and can't seem to find a solution.
    When users login to their RDP session and try to adjust their screen resolution this message is displayed in Control Panel:
    "The display settings can't be changed from a remote session."
    We don't want to use the "make text and other items larger or smaller" scaling feature, as this produces undesirable results with some of our applications.  We also don't want to have to support multiple types of RDP clients or RDP shortcut
    files.
    We have looked at other posts but can't find an answer that applies to Windows Server 2012 R2.  The closest thing we could find is KB2726399, but it only applies to Server 2008.
    Does anybody have a solution for Server 2012?
    Thanks

    Hi,
    Currently you cannot change the resolution from within the session.  This is normal and expected behavior.  
    Unfortunately this means you need to set the desired resolution before connecting by using custom .rdp files, manually within the Remote Desktop Client, custom web launch page, custom windows launch program, etc.
    -TP

  • [Forum FAQ] "Unable to connect to the server by using Windows PowerShell Remoting" error while installing RDS roles on Server 2012 R2

    When you try to install RDS role on server 2012 R2 using standard deployment, this issue may occur (Figure 1).
    “Unable to connect to the server by using Windows PowerShell remoting”.
    Figure 1: Unable to connect to the server by using Windows PowerShell remoting
    First of all, we need to verify the configurations as it suggested:
    1. The server must be available by using Windows PowerShell remotely.
    2. The server must be joined to a domain.
    3. The server must be running at least Windows Server 2012 R2.
    4. The currently logged on user must be a member of the local Administrators group on the server.
    5. Remote Desktop Services connections must be enabled by using Group Policy.
    In addition, we need to check if the “Windows Remote Management “service is running and related firewall exceptions have been created for WinRM listener.
    To enabling PowerShell remoting, we can run this PowerShell command as administrator (Figure 2).
    Enable-PSRemoting -Force
    Figure 2: Enable PowerShell Remoting
    However, if issue persists, we need to check whether it has enough memory to work.
    By default, remote shell allots only 150 MB of memory. If we have IIS or SharePoint App pool, 150 MB of memory is not sufficient to perform the remoting task. Therefore, we need to increase
    the memory via the PowerShell command below:
    Set-Item WSMan:\localhost\Shell\MaxMemoryPerShellMB 1000
    Then, you need to restart the server and the issue should be resolved.
    You can get more information regarding Remote Troubleshooting by below link:
    about_Remote_Troubleshooting
    If you need further assistance, welcome to post your questions in the
    RDS forum.
    Please click to vote if the post helps you. This can be beneficial to other community members reading the thread.

    i found another possible reason, this solution worked for me:
    http://oyvindnilsen.com/solution-for-powershell-remoting-error-it-cannot-determine-the-content-type-of-the-http-response-from-the-destination-computer/
    I tried to set up powershell remoting on a server and kept getting this error:
    Enter-PSSession : Connecting to remote server failed with the following error message : The WinRM client cann
    ot process the request. It cannot determine the content type of the HTTP response from the destination comput
    er. The content type is absent or invalid. For more information, see the about_Remote_Troubleshooting Help to
    pic.
    After a bit of troubleshooting I discovered that the problem was that the authentication packets was to big (over 16k), this will cause WinRM to reject the request. The reason for authentication packets getting too big can be because the user is member of very
    many security groups or in my case because of the SidHistory attribute.
    The solution was to increase the MaxFieldLength and MaxRequestBytes keys in the registry under HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\services\HTTP\Parameters
    If the keys does not exists you can create them, be sure to use the DWORD type.
    I sat MaxFieldLength to DEC value 40000 and MaxRequestBytes to DEC value 32768 and rebooted the server. Problem solved.

  • How to get the returned error messages in the Try/Catch block in DS 3.0?

    A customer sent me the following questions when he tried to implement custom error handling in DS 3.0. I could only find the function "smtp_to" can return the last few lines of trace or error log file but this is not what he wants. Does anyone know the answers? Thanks!
    I am trying to implement the Try/Catch for error handling, but I have
    hard time to get the return the msg from DI, so I can write it to out
    custom log table.
    Can you tell me or point me to sample code that can do this, also, can
    you tell me which tables capture these info if I want to query it from
    DI system tables

    Hi Larry,
    In Data Services XI 3.1 (GAd yesterday) we made several enhancements for our Try/Catch blocks. One of them is the additional of functions to get details on the error that was catched :
    - error_message() Returns the error message of the caught exception
    - error_number() Returns the error number of the caught exception
    - error_timestamp() Returns the timestamp of the caught exception.
    - error_context() Returns the context of the caught exception. For example, "|Session Datapreview_job|Dataflow debug_DataFlow|Transform Debug"
    In previous versions, the only thing you could do was in the mail_to function specify the number of lines you want to include from the error_log, which would send the error_log details in the body of the mail.
    Thanks,
    Ben.

  • Return statement and Try Catch problem

    Hi!!
    I've got the next code:
    public ResultSet DBSelectTeam(String query) {
    try {
    Statement s = con.createStatement();
    ResultSet rs = s.executeQuery(query);
    return rs;
    } catch (Exception err) {
    JOptionPane.showMessageDialog(null, "ERROR: " + err);
    But I need a return statement in the catch-block, but I don't know what's the best option.
    Help...
    Many thanks.

    The error message is: "missing return statement", Yes, I know.
    You have to either return from the catch statement, or throw from the catch statement, or return or throw after the catch statement.
    The only ways your method is allowed to complete is by returning a value or throwing an exception. As it stands, if an exception is thrown, you catch it, but then you don't throw anything and you don't return a value.
    So, like I said: What would you return from within or after catch? There's no good value to return. The only remotely reasonable choice would be null, but that sucks because now the caller has to explicitly check for it.
    So we conclude that catch shouldn't return anything. So catch must throw something. But what? You could wrap the SQLE in your own exception, but since the caller is dealing with JDBC constructs anyway (he has to handle the RS and close it and the Statement), there's no point in abstracting JDBC away. Plus he has to deal with SQLE anyway in his use of the RS and Statement. So you might as well just throw SQLE.
    So since you're going to just throw SQLE anyway, just get rid of the try/catch altogether and declare your method throws SQLException

  • Yet another Try Catch question. Iterating through a ForEach loop

    Confused on error handling in a Powershell ForEach loop. I’m looping through a list of registry keys, attempting
     to open each one. If it succeeds, I do a bunch of stuff. If it fails, I want to skip to the next iteration.
    If I was doing It in VBScript I’d do this:
    For Each Thing In colThings
    Open Thing
    If Err.Number <> 0 Then
    “oops”
    Else
    Do stuff
    Do stuff
    Do stuff
    End If
    Next
    This is what I came up with in PowerShell. It seems to work, but just doesn’t seem powershell-ish. There must be a better way to use the catch output than just creating a $return variable and assigning it success or fail?
    ForEach ($subKeyName in $subKeyNames)
    try{$subKey = $baseKey.OpenSubKey("$subKeyName")}
    catch{$return = "error" }
    If($return -eq "error" )
    “Oops”
    Else
    Do stuff
    Do stuff
    Do Stuff

     
    I totally get what you're saying about formatting. I don't' have any habits yet, since I've only been working in Powershell since... well, what time is it now?
    Unfortunately, It Has Been Decreed that we are no longer to use VBScript for any engineering solutions at work, so my 15 years experience in it now needs to be transitioned over asap. I don't have the luxury of crawling before I run. I'm trying not to be
    frustrated, but it's like an English major waking up one day and being told "You must now speak French exclusively. Here's a book."
    The Do Stuff example of my ForEach loop is about 50 lines of code involving matching values in subkeys of this registry key with another and collecting output. I tried wrapping the whole thing in a try section based on some examples, but it seemed odd, that's
    why I'm asking. I'm used to tightly focused error handling at the point where an error may occur.
    In this example I'm only interested in whether or not I can open the subkey (it exists, but I may not have permission). If I can't, there's no point in continuing with this iteration of the loop, I want to skip to the next one. So why include all the "Do
    Stuff" in the the try section? From a readability viewpoint, it doesn't seem helpful.
    Also, there may be more error handling deeper in the code. If I then put that in a try/catch, and then something else inside that, now I have nested try/catches mixed in with nested if/elses, all wrapped in a For loop.
    Again, I can see how it works logically, but for readability not so much, and having all these braces 50 lines apart to match up is giving me eye strain :).
    It sounds like David is agreeing with jrv, that putting the entire ForEach loop code into a try/catch is the conventional way to do it. I guess it makes as much sense as putting it all in an If-else-Endif, and I just need to adjust my paradigm.
    But if not, my specific question was more along the lines of, is there a built in way to tell that the catch section has been executed, rather than me using it to populate an arbitrary variable and then read it? In VBScript, you execute something, and the
    next line, you check the Err.number. I wasn't sure if you could do that with a try/catch.

  • [Forum FAQ] Introduce Windows Powershell Remoting

    This article will introduce three methods of Windows Powershell Remoting:
    Method 1: WMI
    Remoting Cmdlet: Get-WMIObject
    Protocols: WMI/RPC/DCOM
    Port: Random port
    Data Encryption: Clear text
    Note: No need of the WinRM’s installation and configuration
    Method 2: PowerShell Remoting Commands
    Remoting Cmdlet: Invoke-Command
    Protocols: HTTP (wsman), MIME, SOAP, XML
    Port: 5985
    Data Encryption: Encrypted
    Note: Support any cmdlets in the parameter scriptblock, however, need the computer install WinRM, and also need to configure the WinRM on the remote computer.
    Method 3: PowerShell Remoting Interactively
    Remoting Cmdlet: Enter-PSSession
    Protocols: HTTP (wsman), MIME, SOAP, XML
    Port: 5985
    Data Encryption: Encrypted
    Note: Support any cmdlets, all cmdlets you type are executed as if they were typed on the console of the remote computer. However, need the computer install WinRM, and also need
    to configure the WinRM on the remote computer.

    2. Powershell remote in the same domain with WinRM installed:  Invoke-Command, Enter-PSSession
    2.1 PowerShell Remoting Commands: Invoke-Command
    If you only have a couple of commands to execute on the remote computer in the same domain, you can use the
    Invoke-Command cmdlet.
    For example: Server1 want to remote manage Server2
    1) Enable powershell remoting on Server2
    Launch Windows Powershell as “Run as Administrator” on server2, and run:
    Enable-PSRemoting –Force
    Note:  
    In Server 2012 (but not Windows 8), PowerShell remoting is enabled by default, so you don't need to do anything.
    2) Run invoke-command on server1
    Invoke-Command -ComputerName server2 -Credential domain\username -ScriptBlock {get-process}
    If the user account run with Powershell has the admin permission, there is no need to specify the credential parameter.
    The script above will run the cmdlet “get-process” on server2, and a temporary connection will be built, the result returned to server1, and the connection broken.
    If you want to run powershell script .ps1 file on server2, however, this script is stored on server1, you can achieve as below:
    Invoke-Command -ComputerName server2 -Credential domain\username -FilePath d:\1.ps1
    2.2 PowerShell Remoting Interactively: Enter-PSSession
    To work interactively, use
    Enter-PSSession to connect to a remote session, all the cmdlets you typed in your local console is executed on the remote system until you leave the remote session by using
    Exit-PSSession.
    After configure the WinRM on server2, you can run
    enter-pssession on server1 (Figure 3):
    Figure 3:  remote with enter-pssession
    2.3 Powershell remote with Pssession:  New-Pssession
    Whenever you use Windows PowerShell Remoting with the ComputerName parameter, a temporary session is created for you and used only for this particular command. Once the command
    completes, the session is automatically closed.
    If you start to access remote systems more often or would like to keep the session state, a more efficient way is to create sessions yourself and keep them around until you no longer
    need them. To achieve this, instead of specifying the parameter computername, you can also specify Pssession in the Session parameter of the cmdlets
    invoke-command and enter-pssession (Figure 4).
    Figure 4:  persistent session
    If there is no need to use the Pssession, you can use the cmdlet
    Remove-PSSession to close the session.

Maybe you are looking for

  • IPhone 4S no longer will send or receive texts or calls even though it shows I'm connected to my Sprint Server.

    Hello everyone, I'm in need of some major help with my IPhone 4S.  I'm very confused and frusterated!  My friend had originally purchased two IPhone 4S phones about two years ago.  I know this because he decided to give me his second IPhone 4S that w

  • Error updating two reports on same page! Could you have a look please?

    Hey guys! I have the following situation : two updateable reports on one page with IDs 'DATE_REPORT' and 'WORK_REPORT' two pl/sql processes on submit after c.... named 'SUBMIT_DATE' and 'SUBMIT_WORK' two buttons named 'SAVE_DATE' and 'SAVE_WORK' Fina

  • HT1923 SYNCING ISSUES

    i cannot get my iphone to sync to my iphone 5 and i have tried updating my itunes on my computer but it wont let me load it as it is a 35 bite or something and i cannot find a verson for new itunes for 64?? PLEASE HELP CANT SYNC MY IPHONE TO MY ITUNE

  • Oracle9i AS (invalid user/password,During creating of database)

    Hello! I have installed oracle 9i in Advance server 2000 (domain controller) and when i try to create a database (any type) via Database Configration Assistent then during creating of database it give me the message invalid username/password. The poi

  • Cannot hear sound in calls

    Something happened to my phone. There is no sound on either side when a call is in progress. If i attach head phones, i can hear their sound but they still cannot hear my sound. Has been happening from past couple of days. The phone did not fall down