Calculate factorial via powershell scripting

hello guys i written script until calculate the factorial via powershell but i do not know what does not work !
function factorial( [int] $n ) 
    $result = 1; 
    if ( $n -gt 1 ) 
        $result = $n * ( factorial ( $n - 1 ) ) 
    $result 
this function can not work with big number like that 999 how can i solve that problem?

I get similar results, with a slightly different function. I get results up to at least 170. From 180 through at least 990 I get "Infinity" for the answer. At 999 I get your error, which I believe cannot be avoided. Even if you avoided the
call depth error, PowerShell seems to refuse to deal with such large numbers, and simply outputs "Infinity".
This article goes into factorials in depth:http://en.wikipedia.org/wiki/Factorial
It includes a table for very large values, plus a formula for approximating factorials of large numbers. You might be able to code the approximation formula.
Richard Mueller - MVP Directory Services

Similar Messages

  • Hit with Virus that executed via PowerShell Scripting. Can I disable Powershell on my network via Group Policy and what implications does that have for me.

    Our network was hit recently with virus previously unknown, O97M.Crigent.  It is a nasty Macro virus that targets Microsoft Office Documents & Spreadsheets and uses a combination of Macros and Scripts via Powershell. 
    How do I disable PowerShell scripting via Group Policy?
    Will this raise any issues such as random application or network failures or other issues?
    Can I apply it to the entire domain or should I be selective and only apply it to the workstations?
    Network Summary: Windows 2008 Active Directoy Server, 75% Windows 7, 25% Windows XP workstations.
    DouglasOfSanMarcos

    Disabling Windows PowerShell can be done with GPO:
    Computer Configuration | Administrative Templates | Windows Components | Windows PowerShell
    From GPO Description: "This setting exists under both "Computer Configuration" and "User Configuration" in the group policy editor. The "Computer Configuration" has precedence over "User Configuration."
    By default this option is restricted any way on computers.
    I would be very selective when apply it at all:
    Workstations - I would apply to test group of workstations first, just to see that there are no side effects before applying to all computers. 
    Server - I wouldn't apply it at all. I have seen too many issues when setting this policy on Exchange and other systems.
     If you are using a Group Policy to define a PowerShell logon, logoff or computer script, that script will disregard any execution policy set locally or through a GPO.
    http://4sysops.com/archives/set-powershell-execution-policy-with-group-policy/
    http://technet.microsoft.com/en-us/library/hh849812.aspx
    Please take a moment to Vote as Helpful and/or Mark as Answer where applicable. Thanks.

  • Can't access Modal dialog box via Powershell script

    Hi,
    I have a powershell script to login to an IE website and everything works fine excepting when I call a modal dialog box.  I've attached the line where the modula dialog is invoked.  When it gets to this part the script hangs and I'm unable
    to get past this.  I've googled a few articles where it suggests I should run an a scheduled task to scrape for the modal dialog box but I've tried it without much luck.  If you can please give me some pointers on resolving this issue. 
    Thnx
    Sue.
    $ie.Document.getElementsByTagName("button") | ? { $_.innerText -eq 'UNLOCK User' } | Select-Object -first 1 | % { $_.Click() }
    Sue

    Hi,
    I have a powershell script to login to an IE website and everything works fine excepting when I call a modal dialog box.  I've attached the line where the modula dialog is invoked.  When it gets to this part the script hangs and I'm unable
    to get past this.  I've googled a few articles where it suggests I should run an a scheduled task to scrape for the modal dialog box but I've tried it without much luck.  If you can please give me some pointers on resolving this issue. 
    Thnx
    Sue.
    $ie.Document.getElementsByTagName("button") | ? { $_.innerText -eq 'UNLOCK User' } | Select-Object -first 1 | % { $_.Click() }
    Sue

  • Strange behavior from script when dismounting content databases via PowerShell script

    So, this is my first time posting a question here.  I have taught myself PowerShell and for the most between friends, co-workers, or internet forums, I have been able to pick through most of the issues I have seen.  This one has me stuck. 
    So, a little background, I have a script that goes through each web app in a farm, finds the database that hosts the root site, and detaches all other content databases from the farm.  It also writes a csv file so that a process can come along after the
    fact to re-attach the databases.  I use this for patching so psconfig does not take quite as long as we have more than 50 content databases.  Here is the odd part.  After the first content database is detached, the second one is skipped, but
    the remainder are detached.  So, I have two databases left per web app.  One that holds the root site and whatever the second database is after the first detach.  If I comment out the line that actually does the detach, this does not happen. 
    Now, using ISE and adding break points, what I have found is that when I initially populate the array with the content databases ($var=$webapp.contentdatabase) all databases are in there.  When I start the foreach, all databases are in there.  Right
    up to the point that I detach the first database, all databases are still in the array variable.  As soon as I detach that database, the database that I detached gets removed from the array.  It does this even if I set the variable to read only. 
    It only happens with the first database detached in each web app.  I will try to explain this again with an example.  This test farm has 4 databases.  DB1, DB2, DB3, and DB4.  DB1 holds the root site.  The logic pulls the webapp info. 
    It gets the URL of the webapp.  It takes that info and finds the site collection with that name (the root site).  Finds the database name from there.  It then gets a list of all databases in the webapp and starts to loop through.  So the
    first one in the list is DB1.  It has the root site, so logic says do not delete.  It comes back to the loop with the next database DB2.  At this point, the array still has all 4 databases in the array.  DB2 does not host the root site,
    so the logic gathers information and calls dismount-spcontentdatabase.  As soon as that is called, that database is removed from the array.  So, at this point, we have processes postion 0 and position 1 in the array.  Since the original position
    1 has been removed, DB3 is now at postion 1.  So, the loop continues.  Sine we have now skipped DB3, we find DB4 and dismount.  Now, we have in the array DB1,DB3, and DB4.  My test environment has more and all are still there except for
    the first one removed.  I have banged my head against the desk with this one.  If someone has some insight, I would appreciate it.
    Here is the code that does it.
    get-spwebapplication | foreach-object {
     $webapp=$_
     $waname=$webapp.displayname
     $waurl=$webapp.url
     $cdbs=$webapp.contentdatabases
     $rsite=get-spsite $waurl -erroraction silentlycontinue
     $rsitedb=$rsite.contentdatabase
     $rsitedbn=$rsitedb.name
     foreach ($cdb in $cdbs) {
      $cdbs=$cdbs2
      $cdbname=$cdb.name
      #Write-Host "$cdbname" -foregroundcolor red
      if ($cdbname -ne $rsitedbn) {
       $warn=$cdb.warningsitecount
       $max=$cdb.maximumsitecount
       $current=$cdb.currentsitecount
       $dbserver=$cdb.server
       Write-output "$waname,$cdbname,$dbserver,$warn,$max,$current" >> $outfile
       Write-host "dismounting $cdbname" -foregroundcolor green
       dismount-spcontentdatabase -identity $cdbname -confirm:$false
      else {
       Write-host "$cdbname holds root site. No action." -foregroundcolor yellow

    what about keeping an array of all the non-root collections (may be database name) instead of dismounting them in the foreach loop of all the databases? After we have all the databases that need to be deleted, in a for loop starting with 0 and
    counting to the number of databases, check the name of the database for each index and dismount that database
    pseudo code would be
    $dbstobedismounted = @()
    foreach($cdb in $cdbs)
    $dbstobedismounted + = $cdb.Name  //instead of actually dismounting
    for(int i=0;i<$webapp.ContentDataBases.Count;i++)
    $dabasename = $webapp.ContentDataBases[i].Name
    foreach($dbtobedismounted in $dbstobedismounted)
    if($databasename -eq $dbtobedismounted )
    dismount-spcontentdatabase -dentty $webapp.ContentDataBases[i]
    I'm sure you might have to do some modifications to make it work, but the point I'm making is instead of dismounting in the foreach loop, have a list and dismount in another for loop. Hope it helps.
    rani

  • Move Exchange mailboxes to O365 via PowerShell script

    We are having a problem getting our scripting to work. We have to move 200-300 mailboxes (on a daily basis) to O365. This is an ongoing process. Currently we have over 700,000 mailboxes in the cloud. (Those numbers are correct.)
    We want to automate this process by exporting the list of mailboxes from the EMC (2010) to a CSV file.  Then to run a PS script within an Azure Active Directory PowerShell.
    Here is what we currently have ...
    ========================
    $cred = Get-Credential
    domain.com\<exchange-admin-account>
    <password>
    Import-Csv book1.csv | Select-Object -ExpandProperty `Alias' | foreach {New-MoveRequest -Remote -RemoteHostName 'webmail.domain.com' -RemoteCredential $cred -TargetDeliveryDomain 'service.domain.com' -verbose}
    ==============================
    There is a 'disconnect between the first two pipe segments from the last pipe segment.
    For example ... Import-Csv book1.csv | Select-Object -ExpandProperty 'Alias'  works well, and returns a list of the user alias' to the screen.
    Most of the last pipe segment works well, also.
    {New-MoveRequest -Remote -RemoteHostName 'webmail.domain.com' -RemoteCredential $cred -TargetDeliveryDomain 'service.domain.com' -verbose}     This portion work well for us.
    The 'disconnect' is that the data from the first portion does not translate into the variable to the actual MoveRequest. 
    Anyone have any ideas? What are we missing?
    Thank you in advance.

    Does it work if you remove 'foreach' and  { }, as in:
    Import-Csv book1.csv | Select-Object -ExpandProperty Alias |
    New-MoveRequest -Remote -RemoteHostName 'webmail.domain.com' `
    -RemoteCredential $cred -TargetDeliveryDomain 'service.domain.com' `
    -verbose
    When you put the 'foreach' keyword on the right-hand side of a pipe (|), it sends each output object (in your example, alias names) to the code in between { } after the 'foreach' keyword. When the 'foreach' keyword is on the right-hand side of a pipe, it
    is really an alias for 'ForEach-Object'.
    If that does not work, then try it this way:
    Import-Csv book1.csv | Select-Object -ExpandProperty Alias | foreach-object {
    New-MoveRequest -Identity $_ -Remote -RemoteHostName 'webmail.domain.com' `
    -RemoteCredential $cred -TargetDeliveryDomain 'service.domain.com' `
    -verbose
    In this case I am guessing that the alias from the CSV file would be the
    -Identity parameter of New-MoveRequest, so you would have to substitute the correct parameter name if it's not
    -Identity.
    Bill

  • Add a config item to windows computer via powershell script

    Hello All
    I am looking for a script which will add a config item into windows computer . I have some thing like this which will add the configuration item into an incident . But I want to add to a computer record in all windows computer. I think I am failing to find
    the source for windows computer records
    $incident    
    = get-scsmclass
    m.incident$ |get-scsmobject
    -filter "DisplayName -eq 'IR8 - test'"
    $computer    
    = get-scsmclass
    Microsoft.Windows.Computer$|get-scsmobject
    -filter "PrincipalName -eq 'test'"
    $relationship
    = Get-SCSMRelationshipClass
    -name System.WorkItemAboutConfigItem
    New-SCSMRelationshipObject
    -Relationship $relationship
    -Source $incident
    -Target $computer
    -bulk

    I really don't understand what your are trying to do. do you want to add a new windows computer object to the database, or add an existing windows computer object to the list of related items on a work item? 
    if you are trying to create a windows computer by hand, i would recommend against it. there are much easier ways to get that data from SCCM or AD via connectors. maybe you could elaborate on your need?
    If you are trying to relate an existing windows computer to a work item, then your script is correct. you just need to get the computer object in one hand, the work item in the other and mash them together with a New-SCSMRelationship around the correct Relationship
    class. remember that About (System.WorkItemAboutConfigItem) is for the Affected config item, where as Relates (System.WorkItemRelatesToConfigItem) is for the related config items. an arrow affects the target and is related to the archer; don't get them confused.
    the only other interpretation (and the one i find least likely) is that you are trying to relate two computers together, in which case the script is still correct, except, obviously, the relationship class should be System.ConfigItemRelatesToConfigItem,
    and you would need to get a windows computer in each hand. 

  • Uninstalled a program via PowerShell script, but it still shows up in Programs and Features

    I wrote a script that uninstalls a program just fine, but it still shows up in Programs and Features due to its entries still existing in the Registry. 
    Here is a portion of my script:
    Start-Process
    -FilePath MsiExec
    -ArgumentList "/X$($MyProgram.ProdID)",
    '/quiet'
    -NoNewWindow -Wait
    -PassThru 
    I believe the reason it is still showing up in Programs and Features is because I am missing some MsiExec switch to instruct it to be removed. I vaguely recall dealing with this about two years ago and I wrote a script that did exactly this, but now I completely
    forgot what it was. 
    Can someone help me out here, please?
    Thank you

    I realize that, but honestly don't know where else to submit a question like this in the forums? Also, the vendor is Microsoft. What I am trying to uninstall is any Forefront component, because when I deployed the SCEP client via SCCM 2012 the SCEP client
    was not able to uninstall some of the Forefront components. 
    Here is my script:
    $NewLine = "`r`n"
    $NewLine
    Write-Output "Please wait ..."
    #region ---------- Declare WMI Variables to be Used ----------
    $CM12R2ClientInstalled = Get-WmiObject -Class Win32_Product |
    Where-Object -FilterScript { $_.Name -eq "Configuration Manager Client" -and $_.Version -ge "5.00.7958.1000" }
    $FCSInstalled = Get-WmiObject -Class Win32Reg_AddRemovePrograms |
    Where-Object -FilterScript { $_.DisplayName -match "Forefront" }
    $SCEPInstalled = Get-WmiObject -Class Win32Reg_AddRemovePrograms |
    Where-Object -FilterScript { $_.DisplayName -eq "System Center Endpoint Protection" }
    #endregion ---------- Declare Variables to be Used ----------
    #region --------- Check if the SCCM 2012 R2 Client is Installed ---------
    $CM12ClientService = Get-Service -Name CcmExec
    If (($CM12R2ClientInstalled -ne $null) -and ($CM12ClientService -ne $null))
    $NewLine
    Write-Output "The $($CM12R2ClientInstalled.Name) $($CM12R2ClientInstalled.Version) is installed on $($env:COMPUTERNAME)"
    #endregion --------- Check if the SCCM 2012 R2 Client is Installed ---------
    #region -------- Uninstall any Forefront Component if any are Installed ---------
    If ($FCSInstalled)
    $NewLine
    Write-Output "The following Forefront component(s) are installed on $($env:COMPUTERNAME):"
    $NewLine
    $FCSInstalled.DisplayName
    Foreach ($FCS in $FCSInstalled)
    $NewLine
    Write-Output "Preparing to uninstall $($FCS.DisplayName)"
    $UninstallFCS = Start-Process -FilePath MsiExec -ArgumentList "/X$($FCS.ProdID)", 'REMOVEDATA=1' -NoNewWindow -Wait -PassThru
    If ($($UninstallFCS.ExitCode) -eq '0')
    $NewLine
    Write-Output "$($FCS.DisplayName) uninstalled successfully!"
    $NewLine
    #endregion -------- Uninstall any Forefront Component if any are Installed ---------
    #region --------- Install the SCEP Client if it is Not Installed ----------
    If ($SCEPInstalled -eq $null)
    $NewLine
    Write-Output "The System Center Endpoint Protection client is not installed on $($env:COMPUTERNAME)"
    $InstallSCEP = Start-Process -FilePath "C:\Windows\ccmsetup\SCEPInstall.exe" -ArgumentList '/s', '/q', '/NoSigsUpdateAtInitialExp', '/policy "C:\Windows\CCM\EPAMPolicy.xml"' -NoNewWindow -Wait -PassThru
    If ($($InstallSCEP.ExitCode) -eq '0')
    $NewLine
    Write-Output "System Center Endpoint Protection installed successfully!"
    $NewLine
    Else
    $NewLine
    Write-Warning -Message "System Center Endpoint Protection failed to install on $($env:COMPUTERNAME) with exit error: $($InstallSCEP.ExitCode)"
    $NewLine
    #endregion --------- Install the SCEP Client if it is Not Installed ----------
    Else
    $NewLine
    Write-Output "The System Center Endpoint Protection client is already installed on $($env:COMPUTERNAME)!"
    $NewLine
    Else
    $NewLine
    Write-Warning -Message "$($FCS.DisplayName) failed to uninstall on $($env:COMPUTERNAME) with exit error: $($UninstallFCS.ExitCode)"
    $NewLine
    Else
    $NewLine
    Write-Output "No Forefront components are installed on $($env:COMPUTERNAME)!"
    #region ---------- Install the SCEP Client if it is NOT Installed ----------
    If ($SCEPInstalled -eq $null)
    $NewLine
    Write-Output "The System Center Endpoint Protection client is not installed on $($env:COMPUTERNAME)"
    $InstallSCEP = Start-Process -FilePath "C:\Windows\ccmsetup\SCEPInstall.exe" -ArgumentList '/s', '/q', '/NoSigsUpdateAtInitialExp', '/policy "C:\Windows\CCM\EPAMPolicy.xml"' -NoNewWindow -Wait -PassThru
    If ($($InstallSCEP.ExitCode) -eq '0')
    $NewLine
    Write-Output "System Center Endpoint Protection installed successfully!"
    $NewLine
    Else
    $NewLine
    Write-Warning -Message "System Center Endpoint Protection failed to install on $($env:COMPUTERNAME) with exit error: $($InstallSCEP.ExitCode)"
    $NewLine
    #endregion --------- Install the SCEP Client if it is Not Installed ----------
    Else
    $NewLine
    Write-Output "The System Center Endpoint Protection client is already installed on $($env:COMPUTERNAME)!"
    $NewLine
    Else
    $NewLine
    Write-Output "The System Center Configuration Manager 2012 R2 client is not installed on $($env:COMPUTERNAME)!"
    $NewLine

  • Change "Update distribution points on a schedule" in SCCM 2007 via powershell script

    Hi
    I would like to change the Custom Schedule start time in the "Update distribution points on a schedule" on a package in SCCM 2007 with out logging into the SCCM console.
    I have following line code to query the package.
    Get-WmiObject
    -Namespace
    "Root\SMS\Site_$sitecode"
    -Query
    "SELECT * FROM SMS_PackageBaseclass WHERE PackageID='$PackageID'"
    -ComputerName $ServerName
    The problem is I only get the "SourceDate" and "LastRefreshedTime" from the query. I am not sure if I change the "LastRefreshTime" that it would change the start time in the Custom Schedule

    Hi Jason
    I progressed a little bit with you help. I now have the following bit of code.
    $Package = Get-WmiObject  -class SMS_Package -Namespace "Root\SMS\Site_$sitecode" -Filter "PackageID='$PackageID'" -ComputerName $ServerName
    $RefreshPkg = $Package.RefreshSchedule()
    $RefreshPkg.RefreshSchedule
    I get the following error:
    Method invocation failed because [System.Management.ManagementObject] doesn't contain a method named 'RefreshSchedule'.
    At line:7 char:1
    + $RefreshPkg = $Package.RefreshSchedule()
    + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
        + CategoryInfo          : InvalidOperation: (RefreshSchedule:String) [], RuntimeException
        + FullyQualifiedErrorId : MethodNotFound

  • Powershell Script to Enable and Disable SharePoint list versioning

    Hi,
    We have a Sharepoint list with a date and time field named 'Today' which we update overnight
    via PowerShell script to give the current date and this recalculates other calculated fields
    in the list.
    All is fine but we have versioning enabled on the list and so we get a new version created everyday.
    Is there a way to disable the versioning prior to running the update and then re-enable
    after?
    This is the script
    Add-PSSnapin Microsoft.SharePoint.PowerShell
    Start-SPAssignment -Global
    $SPWeb = Get-SPWeb "<SharePointSiteUrl>"
    $List = $SPWeb.Lists["ListName"]
    $Items = $List.Items
    foreach ($item in $items)
     $modifiedBy = $item["Editor"]
     $modified = $item["Modified"]
     $item["Today"] = Get-Date
     $item["Editor"] = $modifiedBy
     $item["Modified"] = $modified
     $item.Update()
     $list.Update()
    $SPWeb.Dispose()
    Stop-SPAssignment -Global  

    Hi
    Here is a quick powershell script to iterate a site collection and remove versioning on all list of base-type Document Library. Also the iteration removes all the current versions of list items. Great for freeing up space and also to make publishing sites
    a little more easy to manage content for trusted content approvers!
    Check the below powershell script
    [void][System.Reflection.Assembly]::LoadWithPartialName("Microsoft.SharePoint")
    # Get site
    $site = new-object Microsoft.SharePoint.SPSite("http://YoServer:1002")
    # Iterate all the webs of the site
    foreach ($web in $site.AllWebs)
    # loop through all lists in web
    foreach ($list in $web.Lists)
    # Ensure list is of base Document Library
    if ($list.BaseType -ne "DocumentLibrary")
    # Move on
    continue
    # Loop through each item
    foreach ($item in $list.Items)
    # Get the file
    $file = $item.File
    # Delete all versions
    $file.Versions.DeleteAll()
    # Remove version from the list
    $list.EnableVersioning = $false
    $list.EnableModeration = $false
    # We still want to ensure check out
    $list.ForceCheckout = $true
    $list.Update()
    $web.Dispose();
    $site.Dispose();
    Please mark the Answer and Vote me if you think that it will help you to resolved your issue

  • How to change maintenance powershell script via GPO?

    Per suggestion reposted from here: http://social.technet.microsoft.com/Forums/windowsserver/en-US/6eece9d6-a524-48aa-8e64-7554f0ec9b31/how-to-change-maintenance-powershell-script-via-gpo?forum=winserverGP
    Posted at http://answers.microsoft.com/en-us/windows/forum/windows_7-desktop/desktop-shortcuts-to-items-on-network-drives/94eddb27-342b-40fc-9ad4-677ff4ee8ebe?page=9&tm=1403700614489 originally.
    There is a very annoying "feature" in Windows 7 called BrokenShortcuts.ps1 which is being called out weekly via maintenance task and if it finds more than 4 "broken" network shortcuts it removes them all. So it means if a user at this
    moment is disconnected from the network he will lose all links to shares, network applications sitting on his desktop. Funny that there was no such script on Vista and i don't see this on Win8. On the post i have attached one user suggested to edit this script
    and change 4 to 500 or whatever high number. That's fine for one time fix. But i need to do this for 200+ users. This file cannot be simply replaced by a script, so i'm wondering is there any way to do it via GPO?
    I have already tried various startup scripts, but i'm not sure which user to put into commands.
    I need to run this on startup:
    takeown /F C:\Windows\diagnostics\scheduled\Maintenance\TS_BrokenShortcuts.ps1
    icacls c:\windows\diagnostics\scheduled\maintenance\TS_BrokenShortcuts.ps1 /grant "some user":F
    copy \\share\folder$\TS_BrokenShortcuts.ps1 C:\Windows\diagnostics\scheduled\Maintenance\ /Y

    You need to take time to study how Windows does these things.  You can control them with GP which is what you asked.  The article shows you how to disable elements of the tasks.  Each task controls a script.  If you disable the task the
    script that deletes shortcuts will be stopped. Other maintenance tasks will continue to run.
    Most of your problem is that you seem to want someone to provide a magical solution.  In technology it is necessary to fully research your issues until you understand all aspects.  After fully studying the issue you should understand the possible
    solutions if they exist.
    You claim to have deployed the patch that Microsoft released to fix the issue.  You claim it didn't work.  If that is the case then you need to call MS and \p[en a support incident.  If  Microsoft determines that you are right about the
    patch not working you will not be charged for the call.
    I know that learning how to support technology is hard and frustrating for newcomers.  In time, by using these incidents to learn, you will become a seasoned technician and all of this will seem trivial.  Until then we can only suggest that you
    do things that most of us are familiar with.  We cannot fix your network for you.
    I think you haven't really posted in the GP forum but posted a question about GP in the server forum.  Try posting in the GP forum.
    http://social.technet.microsoft.com/Forums/windowsserver/en-US/home?forum=winserverGP
    Here is one answer from the GP forum:
    http://social.technet.microsoft.com/Forums/windowsserver/en-US/home?forum=winserverGP
    http://social.technet.microsoft.com/Forums/windowsserver/en-US/600ca14f-8b1b-400c-b27f-a7f5733407ac/windows-scheduled-maintenance-task?forum=winserverGP
    ¯\_(ツ)_/¯

  • Execute PowerShell Scripts via SAP NetWeaver Identity Management

    Hello,
    Has anyone implemented the execution of a PowerShell script from SAP NetWeaver Identity Management (7.1, 7.2, 8.0?).  Currently implementing 8.0, and our client is looking to kick off PowerShell scripts that would generate Active Directory accounts, Exchange accounts etc.
    Thanks!

    Hey Brendan,
    We've done this out of a 7.2 implementation for exchange 2010 admin processes.  We started with running powershell via a command line pass.  It worked pretty well but it wasn't plain sailing.  We used positional parameters to pass data to the scripts in question, we also had to come up with a return process that deals with any errors that might come of the powershell session.  We had some issues with the shell sessions closing after the script completed.
    We've since redesigned and now drop flat files to a constantly running powershell script that acts a bit like an IDM dispatcher (but obviously not integrated with IDM).  It kicks off other powershell sessions and monitors their progress allowing it to process time outs, stack work up, etc.
    We also found timing the processes to be an issue.  If you create an AD account in IDM and then try to immediately move onto mailbox enable (for example) the account we created wasn't yet replicated to exchange so we had to build wait time into various parts of the process.
    Thanks,
    Pete.

  • Executing SCVMM PowerShell scripts via C# conditionally works depending on application type

    I suspect that this is the wrong forum but I could not find one that was appropriate.
    The environment is SCVMM 2012 R2. I have a series of PowerShell scripts that are executed via C# code from a variety of applications -- MVC, WCF, console, unit tests. It seems that successful connection to the VMM server is dependent on the type of application
    being used. For example, console apps and WCF apps can connect successfully but the
    same code running in a unit test or standard MVC app throw the following exception:
    {You cannot access VMM management server SC-01. (Error ID: 1604)
    Contact the Virtual Machine Manager administrator to verify that your account is a member of a valid user role and then try the operation again.}
        CategoryInfo: {ReadError: (:) [Get-SCVirtualMachine], CarmineException}
        ErrorDetails: {You cannot access VMM management server SC-01. (Error ID: 1604)
    Contact the Virtual Machine Manager administrator to verify that your account is a member of a valid user role and then try the operation again.}
        Exception: {"You cannot access VMM management server SC-01.\r\nContact the Virtual Machine Manager administrator to verify that your account is a member of a valid user role and then try the operation again."}
        FullyQualifiedErrorId: "1604,Microsoft.SystemCenter.VirtualMachineManager.Cmdlets.GetVMCmdlet"
        InvocationInfo: Command = {Get-SCVirtualMachine}
        PipelineIterationInfo: Count = 0
        ScriptStackTrace: "at <ScriptBlock>, <No file>: line 1"
        TargetObject: null
    I suspect that somehow, each app is running under different credentials but I cannot see how that is possible. Each app exhibits the stated behavior whether running within Visual Studio (w/ IIS Express) [running under my own account] or published to the
    server running under a specific specified account that definitely has permissions to the VMM environment.
    This behavior is easily reproducible with the following code
    -- PS Script as embedded resource
    Get-SCVirtualMachine -VMMServer "SC-01"
    -- C# code to load and execute script
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.Threading.Tasks;
    using System.Management.Automation;
    namespace LabManagement {
    public class HyperVVirtualMachineManager {
    public IEnumerable<Models.VirtualMachine> GetVirtualMachines() {
    var vms = new List<Models.VirtualMachine>();
    try {
    using (var rs = System.Management.Automation.Runspaces.RunspaceFactory.CreateRunspace()) {
    rs.Open();
    using (var ps = PowerShell.Create()) {
    ps.Runspace = rs;
    var assembly = System.Reflection.Assembly.GetExecutingAssembly();
    var scriptName = "LabManagement.Scripts.GetAllVirtualMachines.ps1";
    using (var s = assembly.GetManifestResourceStream(scriptName)) {
    using (var reader = new System.IO.StreamReader(s)) {
    var script = reader.ReadToEnd();
    ps.AddScript(script);
    var output = ps.Invoke();
    if (ps.Streams.Error.Count > 0) {
    foreach (var item in ps.Streams.Error) {
    // do something
    if (output.Count > 0) {
    foreach (var o in output) {
    // do something
    rs.Close();
    catch (RuntimeException ex) {
    // do something
    return vms;
    -- Console app (Success)
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.Threading.Tasks;
    namespace VirtualLabManagement.ConsoleTests {
    class Program {
    static void Main(string[] args) {
    // Arrange
    var svc = new LabManagement.HyperVVirtualMachineManager();
    // Act
    var hosts = svc.GetVirtualMachines();
    // Assert
    -- Unit Test (Fails)
    [TestMethod]
    public void TestMethod1() {
    // Arrange
    var svc = new LabManagement.HyperVVirtualMachineManager();
    // Act
    var hosts = svc.GetVirtualMachines();
    // Assert
    Assert.IsNull(hosts);
    As you can see, the code is exactly the same between the different executions but the ability to connect differs.

    Hi Sir,
    I would like to check the following items:
    1. "a variety of applications -- MVC, WCF, console, unit tests." they are all installed on same computer?
    2. VMM server still installed on same computer as these app resides in ?
    (if it is possible please detail the topology of the environment )
    If they are running at same account on same computer , I would suggest you to post this issue into Code UI forum for further assistance :
    https://social.msdn.microsoft.com/Forums/vstudio/en-US/home?forum=vstest
    Best Regards,
    Elton JI
    Please remember to mark the replies as answers if they help and unmark them if they provide no help. If you have feedback for TechNet Subscriber Support, contact [email protected] .

  • Executing powershell script via task scheduler

    Hello,
    I am trying to execute powershell script via windows task scheduler which will forcefully delete all email in a mailbox, but I am getting the below errors
    Operational Code - 2
    Task Category - Action Completed --- Task Scheduler successfully completed task "\IL98" , instance "{2b193375-cbd2-4986-918d-3cfd4027d6b6}" , action "C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe" with return code 0.
    Last Run Result - 0X0
    When I am adding additional cmdlets in the script "Set-ExecutionPolicy Unrestricted", I am getting Last Run Result 0X5 rest of the error remains the same.
    Powershell version - 3.0
    Task Scheduler version - 1.0
    If I try to run the script manually via Exchange Powershell the script executes without any errors
    Thanks in Advance,
    Ankush Shah

    I figured out the problem, there wasn't any problem with the script but I had to correct inputs in windows task scheuler
    Below is the resolution:
    Under Actions:
        Program/Script --> ws\System32\WindowsPowerShell\v1.0\powershell.exe
        Add Argument --> -noexit -command ". 'C:\Program Files\Microsoft\Exchange Server\V14\bin\RemoteExchange.ps1'; Connect-ExchangeServer -auto
    ; <filepath>"
    Eariler I was writing the filepath after double quote "
    Also I have selected the option "Run with Highest Privilages" to avoid
    0x5 error

  • Executing PowerShell script via JAVA

    Hi,
    I have simple powershell script as below :
    # Filename: Hello.ps1
    Write-Host
    Write-Host 'Hello World!'
    Write-Host "Good-bye World! `n"
    # end of script
    I wish to run this script via JAVA by the below JAVA code -
    import java.io.*;
    public class PsJava {
    public static void main(String[] args)
    throws IOException{
            Runtime runtime = Runtime.getRuntime();
    String cmds = (String)
    "cmd /C powershell C:/Documents and Settings/vvenkata/My         Documents/Hello.ps1";
            Process proc = runtime.exec(cmds);
            proc.getOutputStream().close();
            InputStream inputstream = proc.getInputStream();
                InputStreamReader inputstreamreader =
    new InputStreamReader(inputstream);
                BufferedReader bufferedreader =
    new BufferedReader(inputstreamreader);
    String line;
    while ((line = bufferedreader.readLine()) != null) {
                System.out.println(line);          
    Thanks
    Now, why is that I am not able to see any print statements from Hello.ps1 ? Can anyone help me on this?

    Hi,
    I have place my powershell script in the 'C' directory. and i have changed my JAVA code as below, but it still doesn't give any output in my Eclipse Console.
    import java.io.*;
    public class PsJava {
    public static void main(String[] args)
    throws IOException{
            Runtime runtime = Runtime.getRuntime();
    String cmds = (String)
    "cmd /c powershell c:/Hello.ps1";
            Process proc = runtime.exec(cmds);
            proc.getOutputStream().close();
            InputStream inputstream = proc.getInputStream();
                InputStreamReader inputstreamreader =
    new InputStreamReader(inputstream);
                BufferedReader bufferedreader =
    new BufferedReader(inputstreamreader);
    String line;
    while ((line = bufferedreader.readLine()) != null) {
                System.out.println(line);          
    Please advice me on this. If I have to create a batch file, then can you let me know how do I do that?
    Thanks

  • Executing powershell scripts via Task Scheduler

    Hi,
    I have a powershell script that I wrote that when executed from the shell works fine but when executed from task scheduler does not work.
    In my script, an email is sent out based on the results of the execution.  When I run this from the shell, email goes out, when scheduled, no email and there is no indication of errors having occurred anywhere in the system.
    Has anyone run into a similar issue?
    I did change my powershell execution policy to be unrestricted (both in the x86 and x64 consoles).  I am running Windows 2008 R2.
    Thanks - Greg.

    Hi,
    In addition the above suggestions, please also refer to the below threads:
    Using Task Scheduler for a powershell script on server 2008
    http://social.technet.microsoft.com/Forums/en-US/ITCG/thread/e298d613-47b8-4492-92d1-0b55cc8497c1
     Using Windows Task Scheduler to execute Powershell Script frequently
    http://social.technet.microsoft.com/Forums/en-US/winserverpowershell/thread/5901a6ad-ba18-4817-82a9-f75d2d6b439f
    Hope this helps.
    Best Regards,
    Yan Li
    Yan Li
    TechNet Community Support

Maybe you are looking for