Same code – different output. ISE vs PS Console and VSCode.

Hey Guys,

Help needed here… I was just finishing another function for UK Power Cuts (still dirty as pile of dung I know, but works :P) while I noticed something weird.

Scottish and Southern have power cuts info in Javascript generated tables, the thing is, each position might be slightly different / have different fields – for instance one position will not have information about estimated time Engineer will be on place.

Let me show you what I mean on the, picture as we all know it is worth a thousand words:ScottishAndSouthern.jpg

Continue reading “Same code – different output. ISE vs PS Console and VSCode.”

Search Power Cuts In The UK Using PowerShell!

power-cut-call-105

So recently I’ve met this problem that we lost power in one of our offices in the UK, however we didn’t know the reason – might have been UPS malfunction, some bypass troubles, etc. Finally we identified there was a power cut by calling local users.

To make similar problem identification more swift and robust (basically to include that in our IT infrastructure monitoring solution) I’m preparing (still under development ^^) a module that might help in identification if there is a power cut for certain post code.

Continue reading “Search Power Cuts In The UK Using PowerShell!”

PowerShell script for Exchange mailbox item (email, meeting, contacts, etc.) removal.

You might have a situation when someone – it might have even been you – send or receive an email that shouldn’t be sent or received.

It might have been a SPAM sent to your organization or an email that supposed to be send to your colleague but was send to a bunch of other people and had naked ladies in the attachment.

After sending such email reaction chain is as follows:

First you noticed that you have might clicked “Send” button, maybe you clicked CTRL + Enter combination, but you still not sure…

omg-what-have-i-done-jpg

Continue reading “PowerShell script for Exchange mailbox item (email, meeting, contacts, etc.) removal.”

Exchange mailbox/folders permissions – dependency graph between users.

Following solution uses GraphViz application to visualize mailboxpermissions dependencies in the company.

Some time ago I published a scripts for reading mailbox permissions:

https://paweljarosz.wordpress.com/2016/03/04/script-to-check-mailbox-permissions/

and mailbox folder permissions:

https://paweljarosz.wordpress.com/2016/05/28/powershell-script-to-check-permissions-on-mailbox-folders-also-recursively/

If some of you are wondering what GraphViz is, a quick look on google graphics and phrase “graphviz”, gives us an idea of how gorgeous graphs it can create:

fancy_graphviz.JPG

All the GraphViz needs is to have properly formatted input file – that’s it!

68543429.jpg

The need of having such script showed up as one time I was standing in front of migrating users to Exchange Online. I started to wonder how shall I visualize in a simply way, who need to be migrated together…

vlcsnap-2012-06-20-22h11m40s86.png

It was not an easy task, going though a excel/csv file, or even creating lists were not satisfying for me, so I started to think about it more, even during meals…

hqdefault

And then I found GraphViz:

http://www.graphviz.org/

It was looking really good! So now just a matter of quick reading about it checking if it will apply…

tumblr_m1kpqqLxkj1r8yo2fo1_1280

…reviewing the idea…

eeddcbaa20c45eb5c3e1e4e3c73c330f

…some calculations…

ik53723e34

And after all that research the idea became clear…

homer-simpson-donut-dream

As I mentioned at the beginning, input file can be done with one of the mailbox permissions / mailbox folder permissions reading scripts – links provided on the top (you might need to change delimiters a little bit as I guess in these files are “;” but go for adventure and modify something :))

The proper input should look like:

The_Input_File

So it has columns named “Mailbox”, “User” and “AccessRights”

And now the script. In organization I was building script for – it appeared that we have so many permissions I almost shat brikcs when I saw the actual output (graph)…

Just take a look by yourself, here is just a very small piece of graph when I was checking dependencies of just one mailbox – mine:

giphy.gif

Silly_Permissions

Let’s go closer:

Silly_Permissions

really

Imagine now that whole dependency graph contained like 10 more same chunks/pieces, 10 more, 10 fuck*ng times!

Well, I needed somehow to…

dealwithitdrgrant.gif

So the idea of migrating people together in chunks fell down and broke into pieces :] but at least we have that nice script.

  1. First thing is to get GraphViz application and install it:

Here you can find it:

http://www.graphviz.org/Download_windows.php

After installation all you need to to read your mailbox permissions – you can choose to read it with scripts from links given at the beginning of that article.

     2. Next thing, is to set up 3 variables:

GraphViz_variables.JPG

$GraphImageFile = “GraphImageFile.png” -> this is the name/path of your output file – actual graph

$GraphGraphVizFile = “GraphVizFile.gv” -> this is the name/path of the input file that will be passed to GraphViz to visualize your data, it will look similar to this one:

GraphViz_File

$CSVPermissionsFile = “Permissions.csv” –> and finally this is the input file for the script – so output from your script that reads permissions from mailboxes

    3. Having CSV we can start reading permissions, so here are some examples.

After running below:

.\PermissionMatrixGraphBuilder.ps1 -users “Pawel Jarosz”, “Wladek Ksiegowicz”

Permissions_1_PS

We will get:

Permissions_1

Users mentioned in “Users” array will be marked on blue, nice arrows will show direction of permissions 🙂

After running:

.\PermissionMatrixGraphBuilder.ps1 -users “Pawel Jarosz”, “Wladek Ksiegowicz” -SingleUser $true

Permissions_2_PS

We will get:

Permissions_2

And finally after running same but with “level” set to 1 we will get:

.\PermissionMatrixGraphBuilder.ps1 -users “Pawel Jarosz”, “Wladek Ksiegowicz” -Level 1

Permissions_3_PS.jpg

That will runthough the whole file ONLY ONE TIME, and what we will get would be something like:

Permissions_3.jpg

So summing up – for me script does a good job when it comes to visualize data that would be actually really hard to see from a excel file.

It is just an easy script, please note that you can add here features like:

  • adding description to each “connection” saying to which folder permissions are given
  • reading mailboxes sizes and adding them to the graph so it can ease planing of migration of certain groups of people
  • remember – possibilities are endless:

 

possibilities1possibilities2

 

Script can be found on TechNet and GitHub.

 

Remove cancelled Outlook meetings using PowerShell and EWS.

I_am_so_Great

 

Recently there was a business demand for removal of meetings that were canceled in our resource mailboxes. Thought it was some sort of  a bug but then saw that problem was “AutomateProcessing” attribute on these was set to “AutoUpdate” not “AutoAccept” (This can be checked using Get-CalendarProcessing cmdlet).

 

So when someone is scheduling a meeting form his own mailbox and is picking up room – creates a meeting, and later changes his mind and removes it, it still is hanging there visible as “Canceled: Subject of the meeting“. And each time (because of that “AutoUpdate”) someone manually needs to go there and remove it.

https://technet.microsoft.com/en-us/library/bb123495%28v=exchg.141%29.aspx

 

After reading a bit about that topic, I realized that PowerShell script I was about to write needs to use EWS and impersonation in Exchange.

There are few things you need before running the script:

  • AD account used by the script
  • Security Group that will contain people who will have impersonation rights (admns/service accounts)
  • Distribution List that will contain room mailboxes – managed by admins/service accounts from Security Group
  • Management Scope in Exchange – narrowing scope for members of the Distribution List
  • Management Role Assigment – glue all that crap together – permission Security Group to Distribution List with “Application Impersonation” rights.

In commands it can look like:

1. Creating Distibution Group

New-DistributionGroup -Name ‘RoomImpersonationGroup‘ -Type ‘Distribution’ –OrganizationalUnit ‘contoso.com/Distribution Lists’ -SamAccountName ‘RoomImpersonationGroup’ -Alias ‘RoomImpersonationGroup’ –managedBy ‘PawelJarosz’

2. Creation of Exchange Management Scope:

$Grupa = Get-DistributionGroup -Identity “RoomImpersonationGroup”
New-ManagementScope “Room Mailboxes Impersonation” -RecipientRestrictionFilter “MemberOfGroup -eq ‘$($Grupa.DistinguishedName)'”

3. Creation of security group “ExchangeRoomImpersonation” in Active Directory

NEW-ADGroup –name “ExchangeRoomImpersonation” –groupscope Universal –path “OU=Offices,DC=Contoso,DC=local” -GroupCategory Security

4. Creation of new Exchange Assigment Role:

New-ManagementRoleAssignment -Name “Room Mailboxes Impersonation Assigment” -Role “ApplicationImpersonation” -CustomRecipientWriteScope “RoomImpersonationGroup” -SecurityGroup “ExchangeRoomImpersonation”

 

If you have all of that or you do not need to configure it as there are some service accounts you will use that are permissioned to impersonate globally – omit all these steps.

Some details about the script:

.SYNOPSIS
DeleteCanceledMeetings.ps1 - Cancelled meetings removal script.

.PARAMETER SearchStartDay
(OPTIONAL) Specifies START date from which sript should start searching of 
appointments.
If not specified the today's date is used.

.PARAMETER SearchEndDay
(MANDATORY) Specifies END date till which sript should start searching of 
appointments.

.PARAMETER Room
(MANDATORY) Specifies mailboxes from which cancelled meetings should be removed.
As this is an array it accepts many mailboxes given after coma.

.PARAMETER HardDelete
(OPTIONAL) Triggers HardDelete action on cancelled meetings if equal "True". 
Without it it generates a on screen report.

.EXAMPLE
.\Get-MailboxPermissions.ps1 -SearchStartDay 10 -SearchEndDay 30 -Room Room1,Room2
Starts searching of meetings 10 days back and 30 days in front 
for 3 rooms Room1,Room2.
Returns a on screen report.

.EXAMPLE
.\Get-MailboxPermissions.ps1 -SearchEndDay 90 -Room Room1,Room2,Room3 `
 -HardDetele True
Starts searching of meetings starting from current day and 90 days in front 
for 3 rooms Room1,Room2,Room3 and hard deletes them.
Reruns a CSV report and a log file.

You need to modify these lines in order to get logging working:

DeleteCanceledMeetings_script1

And you are ready to go! 🙂

Please remember that when runnig the script:

Calvin12

Script can be found on my Technet and GitHub

Have fun with IT!

Easy-Peasy zipping PowerShell script.

 

HiEverybody

Many of us might be/have been asked a similar question:

WhatYaDoingWithLogFiles

And the answer is…

zipfiles

🙂 So, intentionally my colleague asked me to write that under PowerShell 2.0 – to use zipping assembly we need to change/create PawerShell.exe.config file, here is well described what needs to be done:

http://tfl09.blogspot.co.uk/2010/08/using-newer-versions-of-net-with.html

Otherwise we will get following error in the PS console:

 

Add-Type : Could not load file or assembly ‘Drive_Or_ShareName\Path\To\The\System.IO.Compression.FileSystem.dll’ or one of its dependencies. This assembly is built by a runtime newer than the currently loaded runtime and cannot be loaded.

 

So remedy for that is simply create/change PowerShell.exe.config, for me I needed to create it (was not there)  with content like below:

<?xml version=”1.0″?>
<configuration>
    <startup useLegacyV2RuntimeActivationPolicy=”true”>
        <supportedRuntime version=”v4.0.30319″/>
        <supportedRuntime version=”v2.0.50727″/>
    </startup>
</configuration>

Like even the script name implies – the script is very simply. It checks source directory (specified under Search_Folder parameter) for any files older than given period in days (Age_Of_Backuped_Data param). It moves all found files to the staging folder (Staging_Folder param), creates zip file in destination folder (Destination_Folder param), ensures that zip has been created and clears the staging area. All operations are being logged (LogFile param).

 Few words about the script itself:

.SYNOPSIS
EasyPeasyZippingScript.ps1 – Easy script zipping files.

.DESCRIPTION
Easy script for wrapping files into the archive older than given period, deleting them from the source folder and saving the .zip file into the destination folder.

.OUTPUTS
Output is the .zip file with name that is set by current date/time.

.EXAMPLE
.\EasyPeasyZippingScript.ps1 -Age_Of_Backuped_Data 90 -Search_Folder D:\Search_here -Destination_Folder D:\Archives_here -Staging_Folder D:\Staging_here -LogFile logfile.log

In the above example EasyPeasyZippingScript.ps1  script moves items from “D:\Search_here” with creation date older than 90 days to the  “D:\Staging_here” staging folder, zips that staging folder. Moves archive to “D:\Archives_here” and clears the “D:\Staging_here” folder. Also logs everything to the logfile.log file.

I’ve put the script on my Technet and GitHub 🙂

Have fun with IT!


A few PowerShell tips – Part 2 – Useful commands / switches.

Few days ago I wrote similar article:

Part 1 : https://paweljarosz.wordpress.com/2016/02/21/a-few-powershell-tips-part-1-the-one-about-help/

only_lowe

Here is another portion of PowerShell features I find worth remembering, and I tend to forget about. Actually this is the reason why all these articles are here ^^

 

Show-Command – GUI to build PowerShell commands

 

Show-Command: That feature came out in PowerShell 3.0. Gives great ability to create commands in situation when you are not feeling so well with the shell yet, or if you simply would like to check all the attributes of a certain command:

PowerShell_Tips1

We can see that there is possibility to set even things like pipeline variable (that particular appeared in PowerShell 4.0 – here is a great article about it: https://rkeithhill.wordpress.com/2013/07/20/powershell-v4-pipelinevariable-common-parameter/) and many others through the GUI.

 

How to check PowerShell version installed

 

By the way, to check PowerShell version commands “host” or “$PSVersionTable” can be used:

PowerShell_Tips2

 

Simply “one-liners” simpler with version 3.0

 

Starting from version 3.0 there there is a possibility to use simplified syntax (but only for simple commands like single property listing etc.), for example in PowerShell 2.0 simply Get-Mailbox would look like:

Get-Mailbox | ? {$_.name -match “test”}

And other, shorter, way we can do the same in PowerShell 3.0:

Get-Mailbox | ? name -match test

PowerShell_Tips3

So there is no need for “$_.”, braces and quotes 🙂

 

Be lazy and set default parameters for cmdlets 🙂

 

Another worth mentioning thing is $PSDefaultParameterValues. Variable is set per session, and can be overwritten. Example usage:

$PSDefaultParameterValues = @{“get-wmiobject:class”=”win32_bios”}

After that when running gwmi cmdlet we wil by default will get win32_bios class:

PowerShell_Tips4

 

 -expandproperty – but why?

 

Exactly!

giphy1.gif

If you haven’t used that yet, you might be asking, why it is a cool thing to use. Here is a good example. You plan to use Get-WmiObject cmdlet that is not accepting pipelining – why? Because yo udo not want to use Get-CimInstance that accepts pipelining and does same…  🙂 Anyway after trying to read Win32_BIOS class you might get:

expand1.JPG

The exit from that situation is to get computer name, and puke it out from cmdlet as string – not an object:

expand2.JPG

expand.JPG

 

Label and expression – custom naming properties

 

This one is more useful you might expect 🙂 Great example can be found here:

https://mva.microsoft.com/en-us/training-courses/getting-started-with-powershell-3-0-jump-start-8276

where Jeff and Jason are explaining how to understand usage of pipe.

Here is also great article about it:

https://blogs.technet.microsoft.com/heyscriptingguy/2013/03/25/learn-about-using-powershell-value-binding-by-property-name/

Ed tells there that we can run a pipeline using property “by value” and “by name”, but there is a problem while we have a different name. And here somes the help! Example:

Let’s say we got one workstation and we would like to read status of particular service form it. If we run it Get-ADComputer and we run a simply pipe on Get-Service – we will ger an error:

GetServiceGetAdComputerNameFailed

BUT WHY!?!?!?!!?

whydawsons.JPG

Hey sure! Telling you now. So what we need to check is: Do we have something, which can let us to connect these two cmdlets to each other?

Firstly let’s check Get-ADComputer:

getAdComputer

Property is with the computer name is “Name”. Now we need to get state of one service on that workstation, we check if Get-Service if there is a change to get hookup:

Get-ServiceProperty

So what we need to do here is…:

GetServiceGetAdComputerName

…and TAAADAAAAM!! All we needed to do is to change the property name.

“n” is alias “name”, you can also use “l” for label in exchagne. “e” is for expression. So that part of a command might look like:

select @{name=’ComputerName’;expression={$_.name}}

or

select @{label=’ComputerName’;expression={$_.name}}

 

-PassThru the command

 

You want to run a command and see a right away output of what you did? No problem, just use “-PassThru” switch!

PassThru.JPG