Error with SMLets in an Orchestrator called PowerShell Scripts

Hi!
This is likely so simple I am overlooking the problem but...
I have a "Run .Net Script" activity in an Orchestrator 2012 SP1 Runbook.  It calls SMLets.  The issue is it runs in the PowerShell ISE on the Runbook server without issue.  It runs in the Runbook Tester just fine.  But if I
call the runbook with the PowerShell script, it errors out on the first call the a SMLets provide cmdlet.
A Few Detail:
We loaded the latest SMLets from CodePlex.  We can use the cmdlets in both the 32-bit and 64-bit environments.
The very first line of the PowerShell script is: Import-Module SMLets
The first SM cmdlet is: $class = Get-SCSMClass System.WorkItem.Activity.ReviewActivity$
The Runbook Containing the PowerShell Script:
And lastly, the Event of the error thrown:
In trying to make this work we have tried to run the script remotely on the SCSM server (New-PSSession and Invoke-Command).  Failures due to rights on the SCSM server. 
My opinion is the issue is a rights issue but we cannot find the difference between any of the accounts testing/debugging and the Orchestrator Runbook Service account.  I can run the PowerShell and the Runbook Tester when logged on as the
Orchestrator Runbook Service account.  It works until I have to call the runbook with the PowerShell Activity.  It just like my Account.  We've even set the account on the security tab of the Invoke Runbook Activity.
Is there something I've overlooked?  Something in the install of the SMLets, maybe? A clue?  Help?
If nothing else, thank you for letting me voice my issue onto the 'Net.  Maybe someone else has been down this road and can tell me where the off-ramp is.  ;-)
Ray Watters,
Chicago, IL

Hi,
also make sure that your PS scriptruns with Windows PowerShell (x86) (32bit)
http://www.sc-orchestrator.eu/index.php/scoblog/64-using-64bit-powershell-cmdlets-in-the-run-net-script-activity-from-orchestrator
or with PowerShell V2
http://www.sc-orchestrator.eu/index.php/scoblog/102-running-powershell-30-with-the-run-net-script-activity
Regards,
Stefan
www.sc-orchestrator.eu ,
Blog sc-orchestrator.eu

Similar Messages

  • Problem with a package that calls powershell script

    The long story short: I'm trying to schedule a SSIS package, with SQL Server Agent, that runs a powershell script/command via a proxy account. The problem seems to be that proxy account didn't have the required permissions to run a .ps1 script, so I've
    changed the execution policy to "Unrestricted" of everything that could be changed (from ps command prompt):
    Scope ExecutionPolicy
    MachinePolicy Unrestricted
    UserPolicy Unrestricted
    Process Undefined
    CurrentUser Unrestricted
    LocalMachine Unrestricted
    So far, so good! But when I try to execute the SSIS package that calls the powershell script like this:
    powershell.exe -file D:\script.ps1 -FileName testme
    I get the error:
    AuthorizationManager check failed.
    + CategoryInfo : SecurityError: (:) [], ParentContainsErrorRecord
    Exception
    + FullyQualifiedErrorId : UnauthorizedAccess
    And when I try something more simple like:
    powershell.exe -Command &{Get-ExecutionPolicy}
    I get this:
    Get-ExecutionPolicy : Access denied At line:1 char:3
    + &{Get-ExecutionPolicy}
    + ~~~~~~~~~~~~~~~~~~~
    + CategoryInfo : NotSpecified: (:) [Get-ExecutionPolicy], Managem
    entException
    + FullyQualifiedErrorId : System.Management.ManagementException,Microsoft.
    PowerShell.Commands.GetExecutionPolicyCommand
    It's worth mentioning that I can call the regular cmdlets: dir; get-content, whoami, so powershell.exe is working fine! Anyone with an idea what's going on here?

    Check to make sure Windows Management Instrumentation service (WMI) is Enabled and running. If it’s disabled, try enabling it and starting it to see if that clears the error.
    If all else fails, go to the path noted in the error and delete the PowerShell profile file.
    Arthur
    MyBlog
    Twitter

  • Calling powershell script from a batch file

    Hello All,
    I have a batch script that calls a powershell script. Before calling the script I set the execution policy to unrestricted, but when it gets to the line that calls the batch script i still get the confirmation in the command window: "Do you want to
    perform this operation" I then have to press Y for the PS script to run and then my batch script finishes.
    Does anyone know the setting I need to change in order to suppress the confirmation?
    Note: this is Windows 8, see code below
    set THIS_DIR=%~dp0
    powershell Set-ExecutionPolicy unrestricted
    powershell %THIS_DIR%MyScript.ps1 "param1"

    I may sound like a jerk but you really want to look at PowerShell.exe /?
    PowerShell[.exe] [-PSConsoleFile <file> | -Version <version>]
        [-NoLogo] [-NoExit] [-Sta] [-Mta] [-NoProfile] [-NonInteractive]
        [-InputFormat {Text | XML}] [-OutputFormat {Text | XML}]
        [-WindowStyle <style>] [-EncodedCommand <Base64EncodedCommand>]
        [-File <filePath> <args>] [-ExecutionPolicy <ExecutionPolicy>]
        [-Command { - | <script-block> [-args <arg-array>]
                      | <string> [<CommandParameters>] } ]
    PowerShell[.exe] -Help | -? | /?
    -PSConsoleFile
        Loads the specified Windows PowerShell console file. To create a console
        file, use Export-Console in Windows PowerShell.
    -Version
        Starts the specified version of Windows PowerShell.
        Enter a version number with the parameter, such as "-version 2.0".
    -NoLogo
        Hides the copyright banner at startup.
    -NoExit
        Does not exit after running startup commands.
    -Sta
        Starts the shell using a single-threaded apartment.
        Single-threaded apartment (STA) is the default.
    -Mta
        Start the shell using a multithreaded apartment.
    -NoProfile
        Does not load the Windows PowerShell profile.
    -NonInteractive
        Does not present an interactive prompt to the user.
    -InputFormat
        Describes the format of data sent to Windows PowerShell. Valid values are
        "Text" (text strings) or "XML" (serialized CLIXML format).
    -OutputFormat
        Determines how output from Windows PowerShell is formatted. Valid values
        are "Text" (text strings) or "XML" (serialized CLIXML format).
    -WindowStyle
        Sets the window style to Normal, Minimized, Maximized or Hidden.
    -EncodedCommand
        Accepts a base-64-encoded string version of a command. Use this parameter
        to submit commands to Windows PowerShell that require complex quotation
        marks or curly braces.
    -File
        Runs the specified script in the local scope ("dot-sourced"), so that the
        functions and variables that the script creates are available in the
        current session. Enter the script file path and any parameters.
        File must be the last parameter in the command, because all characters
        typed after the File parameter name are interpreted
        as the script file path followed by the script parameters.
    -ExecutionPolicy
        Sets the default execution policy for the current session and saves it
        in the $env:PSExecutionPolicyPreference environment variable.
        This parameter does not change the Windows PowerShell execution policy
        that is set in the registry.
    -Command
        Executes the specified commands (and any parameters) as though they were
        typed at the Windows PowerShell command prompt, and then exits, unless
        NoExit is specified. The value of Command can be "-", a string. or a
        script block.
        If the value of Command is "-", the command text is read from standard
        input.
        If the value of Command is a script block, the script block must be enclosed
        in braces ({}). You can specify a script block only when running PowerShell.exe
        in Windows PowerShell. The results of the script block are returned to the
        parent shell as deserialized XML objects, not live objects.
        If the value of Command is a string, Command must be the last parameter
        in the command , because any characters typed after the command are
        interpreted as the command arguments.
        To write a string that runs a Windows PowerShell command, use the format:
            "& {<command>}"
        where the quotation marks indicate a string and the invoke operator (&)
        causes the command to be executed.
    -Help, -?, /?
        Shows this message. If you are typing a PowerShell.exe command in Windows
        PowerShell, prepend the command parameters with a hyphen (-), not a forward
        slash (/). You can use either a hyphen or forward slash in Cmd.exe.
    Hope that helps! Jason

  • Load Error with return code 7000 when call sqlldr in interface.

    Hi All,
    I have created a interface to load data from 'File' to 'Oracle' in ODI 11g.
    Below are the running order of this interface.
    1 - Loading - SrcSet0 - Drop work view
    2 - Loading - SrcSet0 - Drop Temp Table
    3 - Loading - SrcSet0 - Create Temp table
    4 - Loading - SrcSet0 - Create Work View
    5 - Loading - SrcSet0 - Generate CTL file
    6 - Loading - SrcSet0 - Call sqlldr
    We are getting the following error while running the step 6.
    org.apache.bsf.BSFException: exception from Jython:
    Traceback (most recent call last):
      File "<string>", line 22, in <module>
    Load Error: See C:\home\oracle\joc\odi/AIM.log for details
      at org.apache.bsf.engines.jython.JythonEngine.exec(JythonEngine.java:146)
      at com.sunopsis.dwg.codeinterpretor.SnpScriptingInterpretor.execInBSFEngine(SnpScriptingInterpretor.java:322)
      at com.sunopsis.dwg.codeinterpretor.SnpScriptingInterpretor.exec(SnpScriptingInterpretor.java:170)
    And it return code 7000 indicated in 'Execution Statistics'.
    If anyone has encountered a similar issue and able to solve it, please share your thoughts with me.
    Thanks in advance for your help.
    Dicksam

    This forum is dedicated to supporting the use of Maven with FMW and the new Oracle Maven Repository.  Given that ODI does not currently provide Maven support, you are unlikely to get a response in this forum.  You might want to try posting in a different forum dedicated to Data Integration, such as the Master Data Management forum.

  • Issue with variables and white space in powershell script that calls a command line command

    Guys,
    I have a question regarding this script. Each time I run it, it creates the share, but with a space after it. Also I need help figuring out how to put in the variable for the folder path.
    Below is the code
    $Users=Import-Csv C:\users2.csv
    foreach($User in $Users){
         $User.SNCORP
         $User.HPB
         $User
         cmd /c "net share "$User.SNCORP"=D:\Users\"$User.HPB" /grant:Everyone,FULL"
    The csv file looks like this
    HPB,SNCORP
    ccarter,carterch$
    This is my output in powershell
    PS C:\> .\shareflip.ps1
    carterch$
    ccarter
    HPB                                                         SNCORP
    ccarter                                                     carterch$
    The syntax of this command is:
    NET SHARE
    sharename
              sharename=drive:path [/GRANT:user,[READ | CHANGE | FULL]]
                                   [/USERS:number | /UNLIMITED]
                                   [/REMARK:"text"]
                                   [/CACHE:Manual | Documents| Programs | BranchCache | None]
              sharename [/USERS:number | /UNLIMITED]
                        [/REMARK:"text"]
                        [/CACHE:Manual | Documents | Programs | BranchCache | None]
              {sharename | devicename | drive:path} /DELETE
              sharename \\computername /DELETE
    Any help is greatly appreciated. 
    Christopher

    There is no need to use cmd /c. You should be able to use:
    net share "$($User.SNCORP)=D:\Users\$($User.HPB)" "/grant:Everyone,Full"
    Use showargs.exe (from the article) at the beginning of this line to see the command line PowerShell is actually running (very useful for troubleshooting).
    -- Bill Stewart [Bill_Stewart]

  • Calling Powershell Script from a vRA Blueprint

    Hi all,
    Need your help! I have a use case where I need to provide user a dropdown list in the Blueprint so that they can select a project number. The project numbers are dynamic and can be exported to a .csv file and I can then write a PS script to capture that.  I’m just not sure on how to present that data in the vRA Blueprint as the list is always changing?  Is there a way to create a custom Control Type in Property Dictionary say “DropDownListFromPowerShell” OR any other solution to address this use case? Any advice will be greatly appreciated.
    Thank you,
    Tony

    you cant do that in IaaS. you would need to use ASD to do those custom server side look ups in your forms.

  • Error when calling powershell from Sun IDM

    Hello Experts,
    In our environment we have a powershell script which takes command-line arguments as input and creates mailbox. To create a mailbox for newly on-boarded user we just need to call this script and pass the args. When i run the script from Gateway server (by physically logging into the server) it works as expected but when i call the same script from Sun IDM (using resource actions) I'm getting the following error,
    The type initializer for 'InstanceContext' threw an exception
    any idea to fix or troubleshoot this?
    We are using Sun IDM 6.0 SP1 and exchange 2007.

    Which version of the Gateway?
    Are you calling the script with afterAction scriptcalls?
    Adapter or connector?
    I do know that the powershellcalls are supposed to have two restrictions which are truly hampering...
    1.0 (which means not remote calls?) and 32 bits.
    If you have any insights, please share :D
    I will start coding agains this next week I think, so I guess I will see all problems then :D

  • App-V PowerShell: Script to Query XenApp Servers for App-V Publishing Errors and Output an Excel Document with the Results

    Please Vote if you find this to be helpful!
    App-V PowerShell:  Script to Query XenApp Servers for App-V Publishing Errors and Output an Excel Document with the Results
    Just posted this to the wiki:
    http://social.technet.microsoft.com/wiki/contents/articles/25323.app-v-powershell-script-to-query-xenapp-servers-for-app-v-publishing-errors-and-output-an-excel-document-with-the-results.aspx

    Hi petro_jemes,
    Just a little claritification, you need to add the value to the variable "[string]$ou", and also change the language in the variable "$emailbody" in the function "Get-ADUserPasswordExpirationDate".
    I hope this helps.

  • User authentication error with Proxy Java Calling web Service in XI

    Hello,
    I have deploy a Web Service in SAP XI 3.0. within a SOAP sender adapter.
    I have also created the Proxy Java Class to access the webservice in the Developer Studio and a Plain Java Class (only with a method main) which uses the proxy classes to consume the web service.
    But when I launch the program a get the next error message:
    java.rmi.RemoteException: Service call exception; nested exception is:
         com.sap.engine.services.webservices.jaxrpc.exceptions.InvalidResponseCodeException: Invalid Response Code: (401) Unauthorized.
         at com.everis.serviciosweb.xi.MI_OUT_STATUSBindingStub.MI_OUT_STATUS(MI_OUT_STATUSBindingStub.java:73)
         at com.everis.llamadas.invocacionWSStatus.main(invocacionWSStatus.java:76)
    Caused by: com.sap.engine.services.webservices.jaxrpc.exceptions.InvalidResponseCodeException: Invalid Response Code: (401) Unauthorized.
         at com.sap.engine.services.webservices.jaxrpc.wsdl2java.soapbinding.MimeHttpBinding.handleResponseMessage
    Where MI_OUT_STATUSBindingStub is my Stub Class.
    I have tried to set USERNAME_PROPERTY and PASSWORD_PROPERTY at runtime from my Stub class to the values that I use to access SAP XI (Integration Repository & Integration Directory) but it still doesn't´t work.
    Have anyone a solution?
    Thanks.

    Hi,
        finally I have fixed it.
    The root of the problem was on the way that I proceed with the generation of wsdl in Integration Directory.
    The second step in the wizard for generation of wsdl ask for a url to call the web service and gives you an option to complete the url automatic. I have use this option and it have proposed my an url of type http://<host>:<port>/sap/xi/engine?entry=.......
    But the SOAP adapter call is in the form http://<host>:<port>/XISOAPAdapter/MessageServlet?channel=<party>:<business service>:<channel>
    So using this type of url in the generation of wsld solves all the problems.
    Regards,
    Antonio.

  • Execute C# in PowerShell: errors with " using System.XML "

    Hi , I'm trying to execute C# code in Power Shell 2.0 .
    My problem is for the references  at the beginning of the code:
    $code = @"
    using System;
    using System.Collections;
    using System.IO;
    using System.Linq;
    using System.Xml;
    using System.Xml.Linq;
       public class Program
            static void Main()
            {  /* the code wich works*/
    Add-Type  -TypeDefinition $code -Language "CSharpVersion3"
    Powershell give me an error saying that " The type or namespace Linq doesn't exist" , and the same for Xml. I have Visual studio express 2013 .
    How can add or import correctly those references? or what is my error?

    Hi Rebegg,
    As this issue is related to Visual Studio, I suggest you create a new thread on Visual Studio forum, more experts will assist you with this issue.
    Visual Studio forum:
    http://social.msdn.microsoft.com/Forums/en-US/home?category=visualstudio
    In addition, about this issue, you have to add your  assemblies to your PowerShellsession before you can reference them to you C# Code, you can use the script like:
    $Assem = (
    ...add referenced assemblies here...
    $Source = @"
    ...add C# source code here...
    Add-Type -ReferencedAssemblies $Assem -TypeDefinition $Source -Language CSharp
    Here are some similar posts for your reference:
    http://ruudvanderlinden.com/2010/10/19/running-inline-c-with-custom-assemblies-in-powershell-2-0/
    http://powershell.com/cs/media/p/133.aspx
    http://blogs.technet.com/b/stefan_gossner/archive/2010/05/07/using-csharp-c-code-in-powershell-scripts.aspx
    I hope this helps.
    Thanks,
    Wendy
    Wendy Li
    TechNet Community Support

  • Help using SMLets in workflow powershell script

    Hello,
    I have written a powershell script in a workflow to help me perform a process. The idea is this: We have an extended Incident class and a custom RMA class, users will sometimes need to launch an RMA from an incident, but never an incident from an RMA or
    an RMA by itself. Therefore, source cardinality I assume is 1 and target cardinality is 2 (unlimited). The RMA NEEDS TO BE ASSOCIATED (related) to the ID # of the Incident Request. So, if you click on the Incident and go to related items, you should see the
    RMA id # there, and when you go to the related items of the RMA, you should see the appropriate IR # there. The workflow is launched by trigger: when an object of the RMA class is created.
    The workflow contains the following powershell script:
    # Load the SMlets module
    Import-Module SMlets
    # Get Date
    $date = ((Get-Date).AddDays(-1));
    # Set ClassName
    $ClassName = Get-SCSMClass -Name Flexity.RMA.Class;
    # Get the RMA Class
    $RMAClass = Get-SCSMObject -Class $ClassName | where{$_.CreatedDate -gt $date};
    # Set DisplayName, Title and Description to RMAx
    foreach ($RMA in $RMAClass)
     {$RMANumber = $RMA.RMA_ID; $RMA | Set-SCSMObject -PropertyHashtable @{"DisplayName"  =  $RMANumber; “Title” =  $RMANumber; ”Description” =  $RMANumber;  
    So I can get the RMA objects created, and properly name them so they show up as RMA{#} but still have not figured out how to get the parent incident and relate it to the appropriate RMA #... Any help would be greatly appreciated!!!!!

    @Anders
    For Service Manager 2010, numbers larger than 1 in a cardinality statement are evaluated as “unlimited” when an MP is imported into Service Manager. This means that MaxCardenality=“2” is the same as MaxCardenality=“2147483647”. Has this changed from 2010
    to 2012?
    @Thomas
    You are indeed correct but I didn't receive any response in there from my last post so I thought it was dead by now. I have also progressed MUCH further from when I had posted that question, so I figured I should just make it a new topic as the topic of
    the question has become much more specific. I will link this post in there to be used as reference.
    I actually ended up figuring this out, let me know what you guys think and if it can be optimized in any way, or if you see any error checking I should add in somewhere.
    Thank you all for your help, especially with your detailed responses Thomas
    My original idea was to have a workflow and that workflow got launched when an object of the RMA class was created, regardless of HOW it was launched through console task or custom control or whatever. However, I ended up using a console task, which when clicked
    launches my script :)
    Code:
    # Creates a variable called IncidentID and points Incident # to it for use within the script
    Param([string]$IncidentID)
    # Load the SMlets module
    Import-Module SMlets
    # Get the Incident Class
    $IncClass = Get-SCSMClass -Name System.WorkItem.Incident$
    # Get the RMA Class
    $RMAClass = Get-SCSMClass -Name flexity.RMA.class
    # Build the Filter String
    $FilterStr = "ID -eq " + $IncidentID
    # Find the Incident we need to link to an RMA
    $Inc = Get-SCSMObject -Class $IncClass -Filter $FilterStr
    $RMAIncText = ["Linked to Incident " + $Inc.ID + ""]
    $RMADescription = $RMAIncText
    New-SCSMObject -Class $RMAClass -PropertyHashtable (@{Title = $Inc.Title; Description = $RMADescription})
    # Find the new RMA to be linked
    $FilterStr = "Description -eq '$RMADescription'"
    $RMA = Get-SCSMObject -Class $RMAClass -Filter $FilterStr
    #Set RMA Number Variable
    $RMANumber = $RMA.RMA_ID;
    #Clean up DisplayName, Title and Description 
    $RMA | Set-SCSMObject -PropertyHashtable @{"DisplayName"  =  $RMANumber; "Title" =  $RMANumber; "Description" =  $RMANumber;   }
    # Create the relationship between the two items
    $RWIClass = Get-SCSMRelationshipClass -Name System.WorkItemRelatesToWorkItem$
    New-SCSMRelationshipObject -Relationship $RWIClass -Source $Inc -Target $RMA -Bulk
    New-SCSMRelationshipObject -Relationship $RWIClass -Source $RMA -Target $Inc -Bulk
    # Unload the SMlets module
    Remove-Module SMlets

  • Powershell script monitor with encrypted password

    I have created a powershell script based monitor in my management pack and everything is ok but I can't get my credentials work inside the script. I want to open pssession to another computer with my credentials. I have triple checked that my pssession is
    working because I can access it from powershell console.
    This works perfectly at local server from PSconsole:
    $EncryptedPassword ="01000000d08c9ddf0115d1118c7a00c04fc297eb01000000534b2....etc...etc..."
    $pw = convertto-securestring -String $EncryptedPassword
    $cred = new-object System.Management.Automation.PSCredential -argumentlist "MyDOMAIN\MyACCOUNT",$pw
    $s = New-PSSession -ComputerName "MyServer" -Port MyPort -Credential $cred
    But when I run the same lines inside my management pack the convertto-securestring
    does nothing, it just wont convert the encrypted password to secure string!
    I have tried this plain text method and it works
    inside my management pack, but I don't want to use it because you can see the password in plain text:
    ConvertTo-SecureString -String "myPlainTextPassword" -AsPlainText -Force
    This is the $error variable, so it's basically says that I don't have anything in the password secure string variable because the convertion did not work for some reason:
    The argument is null. Provide a valid value for the argument, and then try running the command again. Cannot process argument transformation on parameter 'Credential'. PromptForCredential Exception calling ".ctor" with "2" argument(s):
    "Cannot process argument because the value of argument "password" is null. Change the value of argument "password" to a non-null value." The system cannot find the file specified. Exception calling "SecureStringToBSTR"
    with "1" argument(s): "Value cannot be null. Parameter name: s" The system cannot find the file specified. Exception calling "SecureStringToBSTR" with "1" argument(s): "Value cannot be null. Parameter name: s"
    The system cannot find the file specified. 
    So is there some known issue with SCOM Agent / management pack when you are dealing with convertto-securestring
    function with encrypted passwords?
    I used these methods to encrypt the password: Technet article about encryption

    I got it to work!
      <TypeDefinitions>
        <EntityTypes>
          <ClassTypes>
            <ClassType ID="MyClass" Accessibility="Public" Abstract="false" Base="Windows!Microsoft.Windows.LocalApplication" Hosted="true" Singleton="false" Extension="false"
    />
          </ClassTypes>
        </EntityTypes>
        <SecureReferences>
          <SecureReference ID="MyRunAsAccountProfile" Accessibility="Public" Context="System!System.Entity" />
        </SecureReferences>
    <ScriptBody>param (
      [string]$Username,
      [string]$Password
    $API = new-object -comObject "MOM.ScriptAPI" 
    $PropertyBag = $API.CreatePropertyBag()
    $cred = New-Object System.Management.Automation.PSCredential -Argumentlist @($Username,(ConvertTo-SecureString -String $Password -AsPlainText -Force))
    $s = New-PSSession -ComputerName "myserver" -Credential $cred
    Invoke-Command -Session $s -ScriptBlock { $service = Get-Service -Name Spooler}
    $invcom = Invoke-Command -Session $s -ScriptBlock { $service.status}
    Remove-PSSession -Id $s.Id
    if ($invcom.Value -ne "Running") {
    $PropertyBag.AddValue("State","ERROR") 
    $outputLongLine = "Spooler Service is not running on target server!" 
    $PropertyBag.AddValue("Description", $outputLongLine)
    else {
    $PropertyBag.AddValue("State","OK") 
    $outputLongLine = "Spooler is Running on target server."
    $PropertyBag.AddValue("Description", $outputLongLine) 
    $PropertyBag</ScriptBody>
    <Parameters>
    <Parameter>
    <Name>Username</Name>
     <Value>$RunAs[Name="MyRunAsAccountProfile"]/Domain$\$RunAs[Name="MyRunAsAccountProfile"]/UserName$</Value>
    </Parameter>
    <Parameter>
    <Name>Password</Name>
    <Value>$RunAs[Name="MyRunAsAccountProfile"]/Password$</Value>
    </Parameter>

  • The PowerShell script failed with below exception

    I'm receiving the following errors on all SQL Express Servers (every machine that has SQL Express inside).
    it seems that the discovery has found SQL Express but could not connect to the instance.
    details on the alerts:
    Date and Time:
    10/22/2013 12:04:22 PM
    Log Name:
    Operations Manager
    Source:
    Health Service Modules
    Generating Rule:
    Collect Power Shell Module Events
    Event Number:
    22406
    Level:
     Error
    Logging Computer:
    SQLEXPRESS.DOMAIN.COM
    User:
    N/A
    Description:
    The PowerShell script failed with below exception
    System.Management.Automation.RuntimeException: Exception calling "Fill" with "1" argument(s): "A network-related or instance-specific error occurred while establishing a connection to SQL Server. The server was not found or was not
    accessible. Verify that the instance name is correct and that SQL Server is configured to allow remote connections. (provider: SQL Network Interfaces, error: 26 - Error Locating Server/Instance Specified)"
    At line:44 char:19
    + $SqlAdapter.Fill <<<< ($DataSet)|out-null
    at System.Management.Automation.FlowControlNode.Execute(Array input, Pipe outputPipe, ExecutionContext context)
    at System.Management.Automation.ParseTreeNode.Execute(Array input, Pipe outputPipe, ArrayList& resultList, ExecutionContext context)
    at System.Management.Automation.StatementListNode.ExecuteStatement(ParseTreeNode statement, Array input, Pipe outputPipe, ArrayList& resultList, ExecutionContext context)
    Script Name: StolenServerMemory2008.ps1
    One or more workflows were affected by this.
    Workflow name: Microsoft.SQLServer.2008.DBEngine.StolenServerMemoryMonitor
    Instance name: SQLEXPRESS
    Instance ID: {9705795C-4F3B-C2EF-AA7D-C736B40FD6A4}
    Management group: SCOMGROUP 

    Some additional inf.
    http://stackoverflow.com/questions/6466974/unable-to-connect-to-sql-express-error-26-error-locating-server-instance-speci?rq=1
    anyway you can disable this rule/monitor as no control from monitoring solution in that case. Or try to rewrite the same monitor...
    The problem in your case is when function tries to get Max Server Memory MB by connecting to master DB, but you can replace it with performance counter like Target Server Memory (KB)...
    just see the function main in StolenServerMemory2008.ps1 and what you need to replace
    $api = New-Object -comObject "MOM.ScriptAPI"
    $bag = $api.CreatePropertyBag()
    $msg = [Environment]::NewLine
    $err = [Environment]::NewLine
    #try {
    $maxMemoryMB = GetMaxServerMemoryMB $ComputerName $InstanceName
    $stolenPages = (Get-Counter ("\" + $PerformanceCounterObject + ":Buffer Manager\Stolen Pages")).CounterSamples[0].CookedValue
    $pakeSizeKB = 8
    [double]$stolenMemoryMB = $stolenPages * $pakeSizeKB / 1024                                      
    [double]$stolenMemoryPercent = 0
    if($maxMemoryMB -gt 0){
    [double]$stolenMemoryPercent= 100.0 * $stolenMemoryMB / $maxMemoryMB
    $bag.AddValue("StolenMemoryMB", $stolenMemoryMB)
    $bag.AddValue("StolenMemoryPercent", $stolenMemoryPercent)                                  
    $msg += "StolenMemoryMB=$stolenMemoryMB StolenMemoryPercent=$stolenMemoryPercent"
    $msg += [Environment]::NewLine                          
    #debug $api.LogScriptEvent("SQL 2008 Stolen Server Memory data source", $SCRIPT_EVENT_ID, $INFORMATION_EVENT_TYPE, $msg + $err)                     
    #catch {
    #             $header = "Managegement Group: $Target/ManagementGroup/Name$. Script: {0}" -f ($MyInvocation.MyCommand).Name.ToString()
    #             $msg += "Error occured during SQL 2008 Stolen Server Memory data source executing.{0}Computer:{1} {0}Reason: {2}" -f [Environment]::NewLine, $env:COMPUTERNAME, $_.Exception.Message
    #             $api.LogScriptEvent($header, $SCRIPT_EVENT_ID, $ERROR_EVENT_TYPE, $msg + $err)                           
    $bag

  • Powershell script error adding integers

    Hi All, I am trying to add integers but the script is not running. I am using variable "a" with the same line of thinking as
    $arg in $args
    $a in $as
    #  create a script thats adds numbers using foreach
    # put an if statement if the numbers are not valid
    My script begins here:
       set-psdebug -strict
        $total = 0
    foreach($a in $as)
                   if ( $a -as[int] -eq $null)
                { Write-host "this is not a valid number"
                    exit 1
                    $total += $a
                  Write-host "The total is $total"
    I am calling my script with the following line: .\finalexam\foreachadd.ps1 6 6 i
    The error is :
    The variable '$as' cannot be retrieved because it has not been set.
    At C:\cmd.practise\finalexam\foreachadd.ps1:8 char:15
    + foreach($a in $as)
    +               ~~~
        + CategoryInfo          : InvalidOperation: (as:String) [], RuntimeException
        + FullyQualifiedErrorId : VariableIsUndefined
    Thank-you
    SQL 75
    (LearningPowerhsell)

    You need to go back and study the very initial basics of PowerShell.  You are repeatedly guessing wrong and misunderstanding how this works. Without the fundamentals you will be forever lost.
    Try to understand why and how the following works.  Read the basics of using PowerShell variables and loops.
    $as=1,2,'x',4,5,'z'
    $total=0
    foreach($a in $as){
    if($a -as [int]){
            $total+=$a
    }else{
            Write-host "$a cannot be converted to a valid integer 32"
    Write-host "The total is $total"
    You also need to learn how to format your code.  Tat would make it easier for you too see your mistakes.
    \_(ツ)_/

  • Powershell script to get all user profiles with specific email address

    Hello,
    Please help me. I need a powershell script which can do the following things.
    List of all sharepoint user profiles with email address
    [email protected]
    List of all FBA user profiles with email address  [email protected]
         List of all Pending Access Requests
    Any help is much appreciated. Thanks.
    chirag

    The script is not working for me. I changed the url according to my site. See the below error
    New-Object : Exception calling ".ctor" with "1" argument(s):
    "UserProfileApplicationNotAvailableException_Logging ::
    UserProfileApplicationProxy.ApplicationProperties ProfilePropertyCache does
    not have 3f3a5705-0691-4fe8-8643-cccd65363dc9"
    At C:\Scripts\userprofileemails.ps1:11 char:19
    + $profileManager = New-Object
    Microsoft.Office.Server.UserProfiles.UserProfileMan ...
    + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    ~~~
        + CategoryInfo          : InvalidOperation: (:) [New-Object], MethodInvoca
       tionException
        + FullyQualifiedErrorId : ConstructorInvokedThrowException,Microsoft.Power
       Shell.Commands.NewObjectCommand
    You cannot call a method on a null-valued expression.
    At C:\Scripts\userprofileemails.ps1:12 char:1
    + $profiles = $profileManager.GetEnumerator()
    + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
        + CategoryInfo          : InvalidOperation: (:) [], RuntimeException
        + FullyQualifiedErrorId : InvokeMethodOnNull
    Please guide me what to do on this.
    Thanks
    chirag

Maybe you are looking for