#System.Collections.ArrayList
Explore tagged Tumblr posts
jesusninoc · 7 years ago
Text
Obtener empresas del IBEX 35 en formato JSON
Obtener empresas del IBEX 35 en formato JSON
Tumblr media
[System.Collections.ArrayList] $arraylist = New-Object System.Collections.ArrayList # Obtener empresas del IBEX 35 $web = Invoke-WebRequest 'http://www.bolsamadrid.es/esp/aspx/Mercados/Precios.aspx?indice=ESI100000000' $result = $web.AllElements | Where Class -eq “DifFlBj” | %{$_.innerText} $result += $web.AllElements | Where Class -eq “DifFlSb” | %{$_.innerText} $result += $web.AllElements |…
View On WordPress
0 notes
palslive-blog · 6 years ago
Text
Finding orphaned API Connections in Logic Apps
So, Logic Apps has a concept of API Connections, where the information to connect to things like Azure Storage, Azure Service Bus etc. is stored. These connections can be used by one Logic App, or they can be used by several within the Resource Group.
So far it is brilliant.
The issue comes when the team has created lots of Logic Apps and connections for development and testing purposes. Because when you delete the Logic Apps, the API Connections stay.
Within each Logic App, you can check which API COnncetions are used, nice. But for an API Connection, you can’t check which Logic Apps is using it, or if it is even used, crap!
Since the Logic Apps have connections to the API Connections, this should be easily done with Powershell, right? Wrong! It turns out that the information about the API Connections is located in some custom named collection objects. Not being in an array, they don’t have an enumerator, and are not possible to iterate.
Well, with some string work I finally got a script that lists the unused API Connection in a subscription. (And the used ones in Green if you include what is commented)
The script doesn’t delete anything, so it is safe to run, but I don’t take any responsibility for wrongly deletes objects. So be careful and verify the results.
$Tab = [char]9 $logigAppStringCollection = New-Object System.Collections.ArrayList foreach($res in Get-AzureRmResource -ODataQuery "`$filter=resourcetype eq 'microsoft.logic/workflows'" | Sort-Object $_.ResourceGroupName) { $logicApp = Get-AzureRmLogicApp -ResourceGroupName $res.ResourceGroupName -Name $res.Name $logigAppStringCollection.Add($logicApp.Parameters.'$connections'.Value) | Out-Null } foreach ($i in Get-AzureRmResource -ODataQuery "`$filter=resourcetype eq 'microsoft.web/connections'" | Sort-Object $_.ResourceGroupName) { $used = 'Unused' foreach($logicAppString in $logigAppStringCollection) { try { if ($logicAppString.ToString().Contains($i.ResourceId.ToString())) { $used = 'Used' } } catch{ } } if ($used -eq 'Unused') { Write-Host $used $Tab $i.ResourceId -ForegroundColor Red } #else #{ #Write-Host $used $Tab $i.ResourceId -ForegroundColor Green #} }
0 notes
jimsjoo · 5 years ago
Text
How to use ArrayList in VBA
How to use ArrayList in VBA
VBA에서 자체가 아닌 외부에 있는 사용가능한 데이터구조중 하나가 ArrayList이다. 다음은 ArrayList 사용예이다.
Sub demoSystemCollectionsArrayList() Dim it With CreateObject("System.Collections.ArrayList") For Each it In Array("aa1", "aa2", "aa3", "aa3", "aa2", "aa6") .Add it Next .Sort Debug.Print Join(.ToArray, vbLf) Debug.Print .Reverse Debug.Print Join(.ToArray, vbLf) End With End Sub
View On WordPress
0 notes
dbpmsnews · 7 years ago
Text
Syncing Security Groups with team membership
In this post, I present a PowerShell script to synchronize the membership between security groups and Office 365 groups.   Security groups in Azure Active Directory (AAD) have long been a useful way to manage sets of users in the enterprise -- even going back to on-premises Activ...
"Syncing Security Groups with team membership" by Dan Stevenson originally published September 5th 2018 in Microsoft Teams Blog articles
In this post, I present a PowerShell script to synchronize the membership between security groups and Office 365 groups.
  Security groups in Azure Active Directory (AAD) have long been a useful way to manage sets of users in the enterprise -- even going back to on-premises Active Directory and before that, Windows NT global groups. The Office 365 Groups service is the more modern way to address this need, used by Microsoft Teams, Planner, Outlook Groups, Yammer, Power BI, and more. Of course, they're not connected (yet), which is unfortunate but not atypical given the evolution of platforms and products and sometimes divergent scenarios.
  Many companies use AAD security groups extensively, for good reason, and they have a lot of intellectual capital vested in the creation, curation, and management of those security groups. At Microsoft we've used security groups to manage access to internal support resources, bug databases, and source code systems. These companies logically want to leverage their security groups investment for Microsoft Teams and other Office 365 Groups-based services, but they can't right now. If you add a security group to a team membership list, Teams will do a one-time expansion of the security group (same for a distribution list), but any subsequent changes are not reflected in the team, and vice versa.
  Obviously, a great solution would be to base the team membership directly on a security group, so that any changes to the security group are reflected in the team in Microsoft Teams, and vice versa. This would be similar to how Teams leverages the Office 365 Groups service. The engineering team is aware of this request and it is marked as on the backlog. You can provide additional input on the use case and priority via the User Voice feedback system, item 1861385. Similar user feedback has also been provided to the Office 365 Groups team, and you can read and vote on their feedback system too, item 33942997.
  But while we wait for those engineering teams to get to this work (and deal with a thousand other demands on their time), let's take a look at a short-term solution that will unblock companies looking to synchronize security group membership with team membership. The premise is straightforward: create a PowerShell script that will run periodically, maybe every 12 hours or 24 hours, which synchronizes one or more pairs of security group/Office 365 group. Now, the PowerShell interfaces are a little different for each type of group (see note above re: platform evolution and divergent scenarios), but with a little hacking and slashing, I got it to work reasonably well.
  BIG WARNING: I was a physics major in college who fell backwards into software product management. I'm not a developer, and only sort of an "engineer" (in Canada, they probably wouldn't let me wear the pinky ring). My coding process involves a lot of trial-and-error mixed with Stack Overflow research. This code should not be considered production-ready. Rather, look at it as an illustrated proof-of-concept that actual real developers can use to build actual real code.
  The source code is on GitHub, naturally: https://github.com/danspot/Danspot-Scripts-and-Samples-Emporium 
  Here's roughly what the script does:
Get the security group ID and Office 365 group ID; in the script, this is done via lookup based on user input, but in a real app, this should probably be read in from a configuration file
Scan the membership of the security group
Make sure all those users are also in the Office 365 group
Remove anybody in the Office 365 group who is not in the security group
  In this diagram, you can see how one user ("Rajesh") is in the AAD security group but not the Office 365 group, so that user should be added to the latter. And another user, "Stewart" is in the Office 365 group but not the security group, so that user should be removed. Bye Stewart!
Tumblr media
  Here's the key part of the code that scans the security group and adds missing members (in a brute force way) to the Office 365 group:
    # loop through all Security Group members and add them to a list # might be more efficient (from a service API perspective) to have an inner foreach # loop that verifies the user is not in the O365 Group Write-Output "Loading list of Security Group members" $securityGroupMembersToAdd = New-Object System.Collections.ArrayList foreach ($securityGroupMember in $securityGroupMembers) { $memberType = $securityGroupMember.GroupMemberType if ($memberType -eq 'User') { $memberEmail = $securityGroupMember.EmailAddress $securityGroupMembersToAdd.Add($memberEmail) } } # add all the Security Group members to the O365 Group # this is not super efficient - might be better to remove any existing members first # this might need to be broken into multiple calls depending on API limitations Write-Output "Adding Security Group members to O365 Group" Add-UnifiedGroupLinks -Identity $O365GroupID -LinkType Members -Links $securityGroupMembersToAdd
  And here's the part of the code that removes users who are in the Office 365 group but not the security group. Probably the trickiest part of the script was finding and aligning the user ID between the two different groups schemas.
    # loop through the O365 Group and remove anybody who is not in the security group Write-Output "Looking for O365 Group members who are not in Security Group" $O365GroupMembersToRemove = New-Object System.Collections.ArrayList foreach ($O365GroupMember in $O365GroupMembers) { $userFound = 0 foreach ($emailAddress in $O365GroupMember.EmailAddresses) { # trim the protocol ("SMTP:") $emailAddress = $emailAddress.substring($emailAddress.indexOf(":")+1,$emailAddress.length-$emailAddress.indexOf(":")-1) if ($securityGroupMembersToAdd.Contains($emailAddress)) { $userFound = 1 } } if ($userFound -eq 0) { $O365GroupMembersToRemove.Add($O365GroupMember) } } if ($O365GroupMembersToRemove.Count -eq 0) { Write-Output " ...none found" } else { # remove members Write-Output " ... removing $O365GroupMembersToRemove" foreach ($memberToRemove in $O365GroupMembersToRemove) { Remove-UnifiedGroupLinks -Identity $O365GroupID -LinkType Members -Links $memberToRemove.name } }
  Important notes:
This script would have to run periodically, perhaps every 6 hours or every 24 hours, maybe on an admin’s desktop, or better yet, using Azure Automation.
Either the security or the Office 365 group should probably be designated as the "primary" and any changes to that would be reflected on the other, "replica" entity, and not vice-versa. For example, if the security group was the primary, but a user changed the team membership in Microsoft Teams (the replica), that change would be overwritten. Given most people interested in this solution probably have a lot invested in security groups, it’s like you'll want to make the security group the primary in this model.
There are sometimes odd ways that emails are handled in the directory, so you may need to tweak the script to handle email addresses for your domain(s), especially if you have multiple email domains or users with secondary email addresses.
This script probably requires more hardening against various situations including, nested security groups, Unicode email addresses, resource and room accounts, etc.
This script may not scale very well as currently written. There may be limits to the number of users that can be added in one operation (so batching may be required). There are a lot of foreach loops and brute-force adding of members, which probably isn't super efficient.
It's probably a good idea to not do the cleanup to remove stray team members who are not in the security group. Rather, log that information and have a real human go and double check. You wouldn't want a coding or configuration error to accidentally nuke every member of a team.
In general, I think it's a good idea to create an audit log so all actions taken by the script are output to a log file, which a human can review. That file can then be stored somewhere in case of a bug or error, to make it easier to fix things.
The script right now asks for your credentials (twice, since there are two different APIs being used). There are probably some PowerShell best practices for storing credentials in non-interactive mode, or somehow leveraging the OS credentials. Hard-coding credentials into the script seems like a bad idea.
As noted earlier, to use this in production, you'll probably want to make the script run from a configuration file containing a list of pairs of security group ID and Office 365 group ID. You can get those IDs using some of the same API calls in the sample script (like building a separate script just for that), or via Graph Explorer for Office 365 or Azure AD.
  And there you go! Use the comments to let me know how it works, suggest improvements, link to your own solutions, and more.
  About the author: Dan Stevenson was one of the early creators of Microsoft Teams. He led the product management team behind key features like teams and channels, guest access, Teams for education, and the free version of Teams. He recently moved with his family to Taipei, Taiwan, where he leads Teams customer engineering for the Asia Pacific region.
Read Full Post
0 notes
stefanstranger · 7 years ago
Text
RT @poshboth: Nice #PowerShell tip to capture any unwanted output: $null = . { $arrayList = [System.Collections.ArrayList]::new() $arrayList.Add('First') $arrayList.Add('Second') }
Nice #PowerShell tip to capture any unwanted output:$null = . { $arrayList = [System.Collections.ArrayList]::new() $arrayList.Add('First') $arrayList.Add('Second') }
— Daniël Both (@poshboth) June 15, 2018
from Twitter https://twitter.com/sstranger June 15, 2018 at 08:51PM via IFTTT
0 notes
charpprogramming-blog · 8 years ago
Text
C# More abstract classes
In the previous chapter, we had a look at abstract classes. In this chapter, we will expand the examples a bit, and throw in some abstract methods as well. Abstract methods are only allowed within abstract classes. Their definition will look like a regular method, but they have no code inside them:
abstract class FourLeggedAnimal {    public abstract string Describe(); }
So, why would you want to define an empty method that does nothing? Because an abstract method is an obligation to implent that very method in all subclasses. In fact, it's checked at compile time, to ensure that your subclasses has this method defined. Once again, this is a great way to create a base class for something, while still maintaining a certain amount of control of what the subclasses should be able to do. With this in mind, you can always treat a subclass as its baseclass, whenever you need to use methods defined as abstract methods on the baseclass. For instance, consider the following example:  Read: C Sharp
namespace AbstractClasses {    class Program    {        static void Main(string[] args)        {            System.Collections.ArrayList animalList = new System.Collections.ArrayList();            animalList.Add(new Dog());            animalList.Add(new Cat());            foreach(FourLeggedAnimal animal in animalList)                Console.WriteLine(animal.Describe());            Console.ReadKey();        }    }    abstract class FourLeggedAnimal    {        public abstract string Describe();    }    class Dog : FourLeggedAnimal    {        public override string Describe()        {            return "I'm a dog!";        }    }    class Cat : FourLeggedAnimal    {        public override string Describe()        {            return "I'm a cat!";        }    } }
As you can see, we create an ArrayList to contain our animals. We then instantiate a new dog and a new cat and add them to the list. They are instantiated as a Dog and a Cat respectively, but they are also of the type FourLeggedAnimal, and since the compiler knows that subclasses of that class contains the Describe() method, you are actually allowed to call that method, without knowing the exact type of animal. So by typecasting to the FourLeggedAnimal, which is what we do in the foreach loop, we get access to members of the subclasses. This can be very useful in lots of scenarios.
0 notes
jesusninoc · 7 years ago
Text
Analizar fichero XML con la lista de radares de España
Analizar fichero XML con la lista de radares de España
$radares = [XML](Invoke-WebRequest "http://www.dgt.es/images/Tramos_INVIVE_12042017.xml").content [System.Collections.ArrayList] $arraylist = New-Object System.Collections.ArrayList $radares.RAIZ.PROVINCIA.CARRETERA | %{ $radar = $_.DENOMINACION + "|" + $_.RADAR.PUNTO_INICIAL.PK [void]$arraylist.Add($radar) } $arraylist | Sort-Object
View On WordPress
0 notes
jesusninoc · 7 years ago
Text
Detectar si el ratón pasa por alguna posición de la pantalla
#Inicializa una nueva instancia de la clase ArrayList que está vacía y tiene la capacidad inicial predeterminada [System.Collections.ArrayList] $arraylist = New-Object System.Collections.ArrayList #Añadir posiciones [void]$arraylist.Add('0,0') for (1) { $dY = ([System.Windows.Forms.Cursor]::Position.Y) $dX = ([System.Windows.Forms.Cursor]::Position.X) if($arraylist.IndexOf("$dX,$dY") -ne -1) {…
View On WordPress
0 notes
jesusninoc · 7 years ago
Text
Detectar si una palabra está contenida en una línea de un fichero
[System.Collections.ArrayList] $arraylist = New-Object System.Collections.ArrayList #Añadir todas las palabras del fichero al ArrayList (el fichero contiene una frase por línea) #Ejemplo de fichero #hola #adios #hola amigo mio #pepito #grillo #amigo ForEach ($elemento in (gc .\palabras.txt)){ #Agrega un objeto al final de ArrayList [void]$arraylist.Add($elemento) } #Agrupar las palabras para…
View On WordPress
0 notes
jesusninoc · 8 years ago
Text
Realizar una comunicación enviando preguntas y respondiendo de forma automática mediante el motor de síntesis de voz en PowerShell (con restricciones para una gramática de reconocimiento de voz)
Introducción
#################################################################################################### #################################################################################################### #Teniendo en cuenta la idea de comunicar dos ordenadores mediante la voz del sistema operativo…
View On WordPress
0 notes
jesusninoc · 8 years ago
Text
Realizar una comunicación enviando preguntas y respondiendo de forma automática mediante el motor de síntesis de voz en PowerShell
Tumblr media
Introducción
#################################################################################################### #################################################################################################### #Teniendo en cuenta la idea de comunicar dos ordenadores mediante la voz del sistema operativo…
View On WordPress
0 notes
stefanstranger · 8 years ago
Text
PowerShell Azure Functions lessons learned
Lately I’m playing with PowerShell Azure Functions and I learned there are some things I needed to learn and that’s why I want to share some more info about this topic.
What are Azure Functions?
Azure Functions is an event driven, compute-on-demand experience that extends the existing Azure application platform with capabilities to implement code triggered by events occurring in virtually any Azure or 3rd party service as well as on-premises systems. Azure Functions allows developers to take action by connecting to data sources or messaging solutions, thus making it easy to process and react to events. Azure Functions scale based on demand and you pay only for the resources you consume. (from Github)
On the Github page about Azure Functions you can find all the info to get started.
PowerShell Azure Functions
Azure Functions enables you to create scheduled or triggered units of code implemented in various programming languages. PowerShell is one of those programming languages.
A good starting point is a blog post from David O’Brien Azure Functions – PowerShell.
If you look at an example from David you see a special variable being used ‘$res’. At first it was not clear to me where this variable was being defined. To find out more I started to create a Function using the Get-Variable cmdlet.
Use the following PowerShell script in your Function to retrieve the automatic variables available in Azure PowerShell functions.
[sourcecode language='powershell' padlinenumbers='true'] write-Output 'Getting variables' $result = Get-Variable | out-string [/sourcecode]
If you run this in your Azure PowerShell function you will see the following in your logs section.
[sourcecode language='powershell' ] 2017-01-29T16:01:51.538 Function started (Id=6528a25c-61cc-4d16-90ad-4869e47dc599) 2017-01-29T16:01:51.867 Getting variables 2017-01-29T16:01:51.898 Name Value ---- ----- $ ? True ^ args {} ConfirmPreference High ConsoleFileName DebugPreference SilentlyContinue Error {} ErrorActionPreference Continue ErrorView NormalView ExecutionContext System.Management.Automation.EngineIntrinsics false False FormatEnumerationLimit 4 HOME Host System.Management.Automation.Internal.Host.Int... input System.Collections.ArrayList+ArrayListEnumerat... InvocationId 6528a25c-61cc-4d16-90ad-4869e47dc599 MaximumAliasCount 4096 MaximumDriveCount 4096 MaximumErrorCount 256 MaximumFunctionCount 4096 MaximumHistoryCount 4096 MaximumVariableCount 4096 MyInvocation System.Management.Automation.InvocationInfo NestedPromptLevel 0 null OutputEncoding System.Text.ASCIIEncoding outputFile D:\local\Temp\Functions\Binding\6528a25c-61cc-... PID 9936 ProgressPreference Continue PSBoundParameters {} PSCommandPath PSCulture en-US PSDefaultParameterValues {} PSEmailServer PSHOME D:\Windows\SysWOW64\WindowsPowerShell\v1.0 PSScriptRoot PSSessionApplicationName wsman PSSessionConfigurationName http://ift.tt/2g2ttdZ... PSSessionOption System.Management.Automation.Remoting.PSSessio... PSUICulture en-US PSVersionTable {PSVersion, WSManStackVersion, SerializationVe... PWD D:\Windows\system32 req D:\local\Temp\Functions\Binding\6528a25c-61cc-... REQ_HEADERS_ACCEPT application/json, */* REQ_HEADERS_ACCEPT-ENCODING gzip, deflate, peerdist REQ_HEADERS_ACCEPT-LANGUAGE en-US, en-GB; q=0.8, en; q=0.6, nl-NL; q=0.4, ... REQ_HEADERS_CONNECTION Keep-Alive REQ_HEADERS_DISGUISED-HOST stsfunctionappdemo.azurewebsites.net REQ_HEADERS_HOST stsfunctionappdemo.azurewebsites.net REQ_HEADERS_MAX-FORWARDS 10 REQ_HEADERS_ORIGIN http://ift.tt/1MC1oPy REQ_HEADERS_REFERER http://ift.tt/2g2o1rE... REQ_HEADERS_USER-AGENT Mozilla/5.0 (Windows NT 10.0; Win64; x64) Appl... REQ_HEADERS_WAS-DEFAULT-HOS... stsfunctionappdemo.azurewebsites.net REQ_HEADERS_X-ARR-LOG-ID b61667f6-86d8-4bd1-a67c-bc0821ee2170 REQ_HEADERS_X-ARR-SSL 2048|256|C=US, S=Washington, L=Redmond, O=Micr... REQ_HEADERS_X-FORWARDED-FOR 217.122.212.62:4004 REQ_HEADERS_X-FUNCTIONS-KEY EOm0H6fRai398YoJRGKkjzAZ7SV2E/zgnOjTaCOVs55W8h... REQ_HEADERS_X-LIVEUPGRADE 1 REQ_HEADERS_X-ORIGINAL-URL /api/HttpTriggerPowerShellDemo?code=fYnNjQpSyo... REQ_HEADERS_X-P2P-PEERDIST Version=1.1 REQ_HEADERS_X-P2P-PEERDISTEX MinContentInformation=1.0, MaxContentInformati... REQ_HEADERS_X-SITE-DEPLOYME... stsfunctionappdemo REQ_METHOD GET REQ_QUERY_CODE fYnNjQpSyoUtXrR3fJ/vXn/L252RcTrzaeVFGP5vsMG6aa... res D:\local\Temp\Functions\Binding\6528a25c-61cc-... result {System.Management.Automation.PSVariable, Syst... ShellId Microsoft.PowerShell StackTrace true True VerbosePreference SilentlyContinue WarningPreference Continue WhatIfPreference False 2017-01-29T16:01:52.976 Function completed (Success, Id=6528a25c-61cc-4d16-90ad-4869e47dc599) 2017-01-29T16:03:40 No new trace in the past 1 min(s). [/sourcecode]
An interesting variable is “res” if we look at the value of this res variable we see that the value in my Azure Function is D:\local\Temp\Functions\Binding\677636fe-4384-42d2-94a4-55d14101ac99\res
But I was still wondering where this variable was configured because in the examples I often saw the variable being used to output the result.
Example where $res variable is being used:
[sourcecode language='powershell' ] $Result = $psversiontable | ConvertTo-Json Out-File -encoding Ascii -FilePath $res -inputObject $Result [/sourcecode]
It turned out this variable is being configured in the integration configuration section of the Azure Function.
So in above example the output result being show when the Azure Http Trigger PowerShell Function is being called stores the output of the Result variable in a file defined in the res variable.  Hope this clarifies the $res variable seen in many examples on the internet about Azure PowerShell functions.
If you are also interested in the available environment variables within Azure PowerShell functions you can use the following PowerShell script in your Azure Function:
[sourcecode language='powershell' ] write-Output 'Getting environment variables' $result = ls env: | out-string write-output $result [/sourcecode]
I hope you have learned some new things about Azure PowerShell functions and you are interested to get started.
  References:
Azure Function on Github
Azure Functions Get Started
David O’Brien Azure Functions – PowerShell
from Stefan Stranger's Weblog – Manage your IT Infrastructure http://ift.tt/2jKSbNt via IFTTT
0 notes