04 December 2014

Load assemblies in powershell


Add-Type -AssemblyName "System.Windows.Forms"

Add-Type -AssemblyName "mscorlib.dll"

Add-Type -Path "c:\windows\system32\inetsrv\microsoft.web.administration.dll"

13 November 2014

Enable delete confirmation dialog in windows 8

right click on Recycle Bin, select Properties and check the option "Display delete confirmation dialog"


27 October 2014

Verify active directory user and password

Add-Type -AssemblyName System.DirectoryServices.AccountManagement

$context = [System.DirectoryServices.AccountManagement.ContextType]::Domain

$principalc = New-Object System.DirectoryServices.AccountManagement.PrincipalContext($context, 'local.intra', 'testuser','pass')

$principalc.ConnectedServer

$principalc.ValidateCredentials('testuser','pass')

16 October 2014

Test if property exist for an object

$user = Get-ADUser username
if($user.PSObject.Properties.Match('SurnameWXZ').Count){'Yes'}
else {'No'}

Use -f formating operator in powershell

syntax for –F format operator is

{<index>[,<alignment>][:<formatString>]}



basic help information is available in powershell: Get-Help about_Operators

a detailed blog post on technet about -f operator.

08 October 2014

The most useful websites and web apps

The Most Useful Websites and Web Apps

ctrlq.org/screenshots – for capturing screenshots of web pages on mobile and desktops.
dictation.io – online voice recognition in the browser itself.
Most Useful Websiteszerodollarmovies.com – find full-length movies on YouTube.
screenr.com – record movies of your desktop and send them straight to YouTube.
goo.gl – shorten long URLs and convert URLs into QR codes.
unfurlr.come – find the original URL that’s hiding behind a short URL.
qClock – find the local time of a city using Google Maps.
copypastecharacter.com – copy special characters that aren’t on your keyboard.
codeacademy.com – the best place to learn coding online.
lovelycharts.com – create flowcharts, network diagrams, sitemaps, etc.
iconfinder.com – find icons of all sizes.
office.com – download templates, clipart and images for your Office documents.
followupthen.com – the easiest way to setup email reminders.
jotti.org – scan any suspicious file or email attachment for viruses.
wolframalpha.com – gets answers directly without searching   – see more wolfram tips.
printwhatyoulike.com – print web pages without the clutter.
ctrlq.save – save online files to Dropbox or Google Drive directly.
ctrql.rss – a search engine for RSS feeds.
e.ggtimer.com – a simple online timer for your daily needs.
coralcdn.org – if a site is down due to heavy traffic, try accessing it through coral CDN.
random.org – pick random numbers, flip coins, and more.
pdfescape.com – lets you can quickly edit PDFs in the browser itself.
tubemogul.com – simultaneously upload videos to YouTube and other video sites.
scr.im – share you email address online without worrying about spam.
spypig.com – now get read receipts for your email.
myfonts.com/WhatTheFont – quickly determine the font name from an image.
google.com/webfonts – a good collection of open source fonts.
regex.info – find data hidden in your photographs – see more EXIF tools.
livestream.com – broadcast events live over the web, including your desktop screen.
iwantmyname.com – helps you search domains across all TLDs.
homestyler.com – design from scratch or re-model your home in 3d.
join.me – share you screen with anyone over the web.
onlineocr.net – recognize text from scanned PDFs – see other OCR tools.
flightstats.com – Track flight status at airports worldwide.
wetransfer.com – for sharing really big files online.
hundredzeros.com – the site lets you download free Kindle books.
polishmywriting.com – check your writing for spelling or grammatical errors.
marker.to – easily highlight the important parts of a web page for sharing.
typewith.me – work on the same document with multiple people.
whichdateworks.com – planning an event? find a date that works for all.
everytimezone.com – a less confusing view of the world time zones.
gtmetrix.com – the perfect tool for measuring your site performance online.
noteflight.com – print music sheets, write your own music online (review).
imo.im – chat with your buddies on Skype, Facebook, Google Talk, etc. from one place.
translate.google.com – translate web pages, PDFs and Office documents.
kleki.com – create paintings and sketches with a wide variety of brushes.
similarsites.com – discover new sites that are similar to what you like already.
wordle.net – quick summarize long pieces of text with tag clouds.
bubbl.us – create mind-maps, brainstorm ideas in the browser.
kuler.adobe.com – get color ideas, also extract colors from photographs.
liveshare.com – share your photos in an album instantly.
lmgtfy.com – when your friends are too lazy to use Google on their own.
midomi.com – when you need to find the name of a song.
google.com/history – see your past searches, also among most important Google URLs
bing.com/images – automatically find perfectly-sized wallpapers for mobiles.
faxzero.com – send an online fax for free – see more fax services.
feedmyinbox.com – get RSS feeds as an email newsletter.
ge.tt – qiuckly send a file to someone, they can even preview it before downloading.
pipebytes.com – transfer files of any size without uploading to a third-party server.
tinychat.com – setup a private chat room in micro-seconds.
privnote.com – create text notes that will self-destruct after being read.
boxoh.com – track the status of any shipment on Google Maps – alternative.
mondrian.io – create vector drawings in the browser
draw.io – create diagrams and flowcharts in the browser, export your drawings to Google Drive and Dropbox.
downforeveryoneorjustme.com – find if your favorite website is offline or not?
ewhois.com – find the other websites of a person with reverse Analytics lookup.
whoishostingthis.com – find the web host of any website.
labnol.org – software tutorials and how-to guides.
disposablewebpage.com – create a temporary web page that self-destruct.
urbandictionary.com – find definitions of slangs and informal words.
seatguru.com – consult this site before choosing a seat for your next flight.
unsplash.com – download images absolutely free.
zoom.it – view very high-resolution images in your browser without scrolling.
scribblemaps.com – create custom Google Maps easily.
alertful.com – quickly setup email reminders for important events.
picmonkey.com – Picnik is offline but PicMonkey is an even better image editor.
formspring.me – you can ask or answer personal questions here.
sumopaint.com – an excellent layer-based online image editor.
snopes.com – find if that email offer you received is real or just another scam.
typingweb.com – master touch-typing with these practice sessions.
mailvu.com – send video emails to anyone using your web cam.
timerime.com – create timelines with audio, video and images.
stupeflix.com – make a movie out of your images, audio and video clips.
safeweb.norton.com – check the trust level of any website.
teuxdeux.com – a beautiful to-do app that looks like your paper dairy.
deadurl.com – you’ll need this when your bookmarked web pages are deleted.
minutes.io – quickly capture effective notes during meetings.
youtube.com/leanback – Watch YouTube channels in TV mode.
youtube.com/disco – quickly create a video playlist of your favorite artist.
talltweets.com – Send tweets longer than 140 characters.
pancake.io – create a free and simple website using your Dropbox account.
builtwith.com – find the technology stack to know everything about a website.
woorank.com – research a website from the SEO perspective.
mixlr.com – broadcast live audio over the web.
radbox.me – bookmark online videos and watch them later (review).
tagmydoc.com – add QR codes to your documents and presentations (review).
notes.io – the easiest way to write short text notes in the browser.
ctrlq.org/html-mail – send rich-text mails to anyone, anonymously.
fiverr.com – hire people to do little things for $5.
otixo.com – easily manage your online files on Dropbox, Google Docs, etc.
ifttt.com – create a connection between all your online accounts.
Changelog and Updates

The following websites were part of the original list but they are either no longer available or have been replaced with better alternatives.

virustotal.com – scan any suspicious file or email attachment for viruses.
isnsfw.com – when you wish to share a NSFW page but with a warning.
truveo.com – the best place for searching web videos.
tabbloid.com – your favorite blogs delivered as PDFs.
warrick.cs.odu.edu – you’ll need this when your bookmarked web pages are deleted.
tempalias.com – generate temporary email aliases, better than disposable email.
whisperbot.com – send an email without using your own account.
errorlevelanalysis.com – find whether a photo is real or a photoshopped one.
google.com/dictionary – get word meanings, pronunciations and usage examples.
wobzip.org – unzip your compressed files online.
namemytune.com – when you need to find the name of a song.
snapask.com – use email on your phone to find sports scores, read Wikipedia, etc.
pastebin.com – the site has been blocked in India.
encrypted.google.com – Google now redirects all logged-in users to the https version of google.com by default so this is no longer necessary.
bounceapp.com – replace this with a version that works on mobile.

How to repair WMI classes on Windows 2003

1. Open a command prompt.
2. Disable Windows Management Instrumentation service
sc config winmgmt start= disabled
3. Stop Windows Management Instrumentation service
net stop winmgmt
4. Change the current folder to %windir%\system32\webm
cd %windir%\system32\wbem
5. Register all WBEM dlls:
for /f %s in ('dir /b *.dll') do regsvr32 /s %s
6. Run the following command:
regsvr32 %windir%\system32\tscfgwmi.dll
7. Add all classes and class instances to the WMI repository:
for /f %s in ('dir /b *.mof *.mfl') do mofcomp %s
8. Register provider host:
wmiprvse /regserver
9. Register WBEM Server (WMI Service)
winmgmt /regserver
10. Run the following two commands:
winmgmt /clearadap

winmgmt /resyncperf


source

02 October 2014

Restore active directory object

it only works if:

  • forest functional level is 2008 R2 (only if all domain controllers are running Windows 2008 R2)
  • Active Directory Recycle Bin was enabled before the object was deleted.


Get-ADObject -Filter {samaccountname -like '*marius*'} -IncludeDeletedObjects -Server adc | Restore-ADObject -PassThru

How to filter for null values with Get-ADUser cmdlet


Get-ADUser -Filter {title -notlike "*"}

29 September 2014

Find duplicate elements in array


($array | Group-Object | Where-Object {$_.Count -gt 1}).Values

29 August 2014

SCOM 2007 - error 0x80090303

Event ID 21001
The OpsMgr Connector could not connect to MSOMHSvc/hostname.local because mutual authentication failed. Verify the SPN is properly registered on the server and that, if the server is in a separate domain, there is a full-trust relationship between the two domains.

Event ID 20057
Failed to initialize security context for target MSOMHSvc/hostname.local. The error returned is 0x80090303 (The specified target is unknown or unreachable). This error can apply to either the Kerberos or the SChannel package.

my setup: certificate based authentication for servers in workgroup.

problem identified: MOMCertImport tool wrote the wrong certificate serial number to the registry so the wrong certificate was used for authentication.

registry key: HKLM\SOFTWARE\Microsoft\Microsoft Operations Manager\3.0\Machine Settings\ChannelCertificateSerialNumber

this registry key must contain the certificate serial number from : Local Computer / Personal / Certificates folder

!!! the certificate serial number is wrote in the registry in reverse order.!!!



20 August 2014

Script to rename groups in FIM


Add-PSSnapin FIMAutomation

$filter = "/Group[(starts-with(DisplayName,'recipients%'))]"

# import grups from FIM
$fimgroups = Export-FIMConfig -Uri http://faber:5725/ResourceManagementService -CustomConfig $filter -OnlyBaseResources

foreach ($fimgroup in $fimgroups){
   
    $groupNewName = $fimgroup.ResourceManagementObject.ResourceManagementAttributes.Where({$_.AttributeName -eq 'AccountName'}).Value.Replace('recipients ','MR_')
    $fimgroupid = $fimgroup.ResourceManagementObject.ResourceManagementAttributes.Where({$_.AttributeName -eq 'Objectid'}).Value
   
    # To perform an operation on a FIM object, first we need to create an ImportObject:
    $importObject = New-Object Microsoft.ResourceManagement.Automation.ObjectModel.ImportObject
    # "shortcut" for the enum that defines the import state
    $ImportState = [Microsoft.ResourceManagement.Automation.ObjectModel.ImportState]
    # "shortcut" for the enum that defines the operation type
    $ImportOperation = [Microsoft.ResourceManagement.Automation.ObjectModel.ImportOperation]
    # import object properties
    $importObject.ObjectType = 'Group'
    $importObject.TargetObjectIdentifier = $fimgroupid
    $importObject.SourceObjectIdentifier = $fimgroupid
    $importObject.State = $ImportState::Put

    # import change object for account name
    $importChange = New-Object Microsoft.ResourceManagement.Automation.ObjectModel.ImportChange
    # import change properties
    $importChange.Operation = $ImportOperation::Replace
    $importChange.AttributeName = 'AccountName'
    $importChange.AttributeValue = $groupNewName
    $importChange.FullyResolved = 1
    $importChange.Locale = 'Invariant'
    # add changes to importObject
    $importObject.Changes += $importChange

    # import change object for account name
    $importChange = New-Object Microsoft.ResourceManagement.Automation.ObjectModel.ImportChange
    # import change object for displayname
    $importChange.Operation = $ImportOperation::Replace
    $importChange.AttributeName = 'DisplayName'
    $importChange.AttributeValue = $groupNewName
    $importChange.FullyResolved = 1
    $importChange.Locale = 'Invariant'
    # add changes to importObject
    $importObject.Changes += $importChange

    # import change object to FIM
    Import-FIMConfig -Uri http://faber:5725/ResourceManagementService -ImportObject $importObject
}

Find and delete mail messages in queue

To find messages that are in queue:

Get-Message -Queue "server_name\submission" | where {$_.status -eq "Retry"} -Queue "server_name\submission" | where {$_.status -eq "Retry"}


to delete messages:

Get-Message -Queue "server_name\submission" | where {$_.status -eq "Retry"} | Remove-Message -WithNDR $false 

12 August 2014

Invoke-Item

Invoke-Item - performs the default action on the specified item.

The default action depends on the type of specified item.

for example: on a document file ( .doc)  it will open the file withe the associated application (Microsoft Word).

alias for this cmdlet is ii

to open a windows explorer to the current foder use: ii .


24 July 2014

Use FIM powershell cmdlets on another computer

in order to use FIM posershell cmdlets to another computer you need to register the FIM libraries.

first the dll files must be copy from the FIM installation directory to the local computer.
usually is C:\Program Files\Microsoft Forefront Identity Manager\2010\Service\
and we need this files:

  • Microsoft.ResourceManagement.Automation.dll
  • Microsoft.IdentityManagement.Logging.dll
  • Microsoft.ResourceManagement.dll
  • Microsoft.ResourceManagement.Automation.dll-Help.xml (only if if you need help on the imported cmdlets)
we also need gacutil.exe. it's included with Visual Studio (as part of the Microsoft SDK) and the .Net framework (v1 and 1.1 only!)  So it might be in one of the following location:
  •  %programfiles%\Microsoft Visual Studio .NET 2003\SDK\v1.1\Bin\gacutil.exe
  • %programfiles%\Microsoft SDKs\Windows\v6.0\Bin
  • %programfiles%\Microsoft SDKs\Windows\v6.0A\Bin
  • %windir%\Microsoft.NET\Framework\v1.0.3705
  • %windir%\Microsoft.NET\Framework\v1.1.4322

after the files were copyed (to your prefered spapin directory) the libraries must be registred :

open a powershell console with elevated rights and set current directory to where you copyed the dll file.

create an alias for the instalutil.exe
Set-Alias installutil  C:\Windows\Microsoft.NET\Framework\v4.0.30319\installutil
 for x64 use C:\Windows\Microsoft.NET\Framework64\v4.0.30319\installutil

Register libraries:


  1. InstallUtil.exe -i .\Microsoft.ResourceManagement.Automation.dll
  2. gacutil -i Microsoft.ResourceManagement.dll
  3. gacutil -i Microsoft.IdentityManagement.Logging.dll

to verify if the snapin has been registred use: Get-Pssnapin -Registred

Later edit:
gacutil is not available by default on windows server 2012 - powershell can help overcame this:

Set-Location 'to fim dll directoy'
[System.Reflection.Assembly]::Load("System.EnterpriseServices, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a")
$publish = New-Object System.EnterpriseServices.Internal.Publish
$publish.GacInstall("Microsoft.ResourceManagement.dll")

$publish.GacInstall("Microsoft.IdentityManagement.Logging.dll")

later edit source

01 July 2014

Report Exchange database limits


Get-MailboxDatabase -Status | Select-Object Name, @{name='Warning';Exp={([string]$_.IssueWarningQuota).Split(' ')[0]+' MB'}}, @{name='ProhibitSend';Exp={([string]$_.ProhibitSendQuota).Split(' ')[0]+' MB'}}, @{name='ProhibitSendReceive';Exp={([string]$_.ProhibitSendReceiveQuota).Split(' ')[0]+' MB'}}

16 June 2014

Test for Null, empty or wite-space characters


$a = $null
$b = ''
$c = ' '

"`$a contains null: " + ([string]::IsNullOrWhiteSpace($a))
"`$b is empty: " + ([string]::IsNullOrWhiteSpace($b))
"`$c has one space: " + ([string]::IsNullOrWhiteSpace($c))

$a contains null: True
$b is empty: True
$c has one space: True


more info about IsNullOrWhiteSpace method

29 May 2014

Forefront Identity Manager criteria group wildcard characters

%   Any string of zero or more characters.
_ (underscore)   Any single character.
[ ]   Any single character within the specified range ([a-f]) or set ([abcdef]).
[^]   Any single character not within the specified range ([^a-f]) or set ([^abcdef]).

source

26 May 2014

System.DirectoryServices.ActiveDirectory Namespace


[ActiveDirectory.Forest]
[System.DirectoryServices.ActiveDirectory.Forest]::GetCurrentForest().Name
[System.DirectoryServices.ActiveDirectory.Forest]::GetCurrentForest().ApplicationPartitions
[System.DirectoryServices.ActiveDirectory.Forest]::GetCurrentForest().Sites
[System.DirectoryServices.ActiveDirectory.Forest]::GetCurrentForest().GlobalCatalogs
[System.DirectoryServices.ActiveDirectory.Forest]::GetCurrentForest().Domains
[System.DirectoryServices.ActiveDirectory.Forest]::GetCurrentForest().ForestMode
[System.DirectoryServices.ActiveDirectory.Forest]::GetCurrentForest().RootDomain
[System.DirectoryServices.ActiveDirectory.Forest]::GetCurrentForest().Schema
[System.DirectoryServices.ActiveDirectory.Forest]::GetCurrentForest().SchemaRoleOwner
[System.DirectoryServices.ActiveDirectory.Forest]::GetCurrentForest().NamingRoleOwner

[Active Directory Domain]:


GetCurrentDomain() can be switch with GetComputerDomain()
[System.DirectoryServices.ActiveDirectory.Domain]::GetCurrentDomain().InfrastructureRoleOwner
[System.DirectoryServices.ActiveDirectory.Domain]::GetCurrentDomain().PdcRoleOwner
[System.DirectoryServices.ActiveDirectory.Domain]::GetCurrentDomain().RidRoleOwner
[System.DirectoryServices.ActiveDirectory.Domain]::GetCurrentDomain().DomainControllers
[System.DirectoryServices.ActiveDirectory.Domain]::GetCurrentDomain().DomainMode
[System.DirectoryServices.ActiveDirectory.Domain]::GetCurrentDomain().Parent
[System.DirectoryServices.ActiveDirectory.Domain]::GetCurrentDomain().DomainMode
[System.DirectoryServices.ActiveDirectory.Domain]::GetCurrentDomain().Children
[System.DirectoryServices.ActiveDirectory.Domain]::GetCurrentDomain().Forest
[System.DirectoryServices.ActiveDirectory.Domain]::GetCurrentDomain().Name

[Computer Specific]:
[System.DirectoryServices.ActiveDirectory.ActiveDirectorySite]::GetComputerSite()
[System.DirectoryServices.ActiveDirectory.Domain]::GetCurrentDomain().Name
[System.DirectoryServices.ActiveDirectory.Domain]::GetComputerDomain().Name

23 May 2014

User must change password at next logon - active directory attribute

pwdLastSet attribute is set to zero to force the user to change their password at next logon.

set the pwdLastSet attribute to -1 to remove this requirement.

22 May 2014

Use the output of query and run scheduled tasks from a remote computer in powershell



the output will be formated in a csv format and can be assigned to a variable and interpreded:

$taskQuery = schtasks /Query /S computer_name /TN task_name /V /FO CSV

$taskQuery[1].split(',')[3]  - will output:

"Ready"

Export exchange message tracking results in csv

default output of Export-CSV command for the output of Get-MessageTrackingLog will not show all properties in the correct format:


Recipients RecipientStatus
System.String[] System.String[]


Select-Object can be used to properly format the output for the Export-CSV command:


Select-Object Timestamp, Sender, {$_.Recipients}, {$_.RecipientStatus}

22 April 2014

Ctrl + Alt + Del in remote desktop

Ctrl + Alt + End pressed together when you are in a remote desktop windows is equivalent to Ctrl + Alt + Del from the console window.

it is very handy if you need to change you domain account password.

17 April 2014

Word macro to add image border


Selection.InlineShapes(1).Borders.OutsideLineStyle = wdLineStyleDouble
Selection.InlineShapes(1).Borders.OutsideLineWidth = wdLineWidth150pt
Selection.InlineShapes(1).Borders.OutsideColor = wdColorLightBlue

21 March 2014

Change error messages text color

the error messages color can be changed using the following command:

$host.PrivateData.ErrorForegroundColor = 'green'

the change will be lost after closing the shell. in order to make this "permanent" you should put the command in the profile file.


18 March 2014

Custom object - the easy way

the hard way:

$customObject = New-Object PSObject
$customObject | Add-Member NoteProperty Name "Marius"
$customObject | Add-Member NoteProperty Age "33"
$customObject | Add-Member NoteProperty Country "Romania"



the easy way:

$customObject = " " | Select-Object Name, Age, Country
$customObject.Name = "Marius"
$customObject.Age = "33"
$customObject.Country = "Romania"

12 February 2014

Execute sheduled task on remote computer


verify task status:

schtasks /query /S finly /TN "Delta Group Synchronization"


execuite task:
schtasks /query /S computername /TN "Delta Group Synchronization"

Net Logon service - enabling debug logging (dbflag)

Enabling the net logon service debug logging can be done using the nltest command.

example: nltest /dbflag:0x00000004 - logon processing

after you modify the flug restart net logon service.

logfile can be found in %windir%\debug\netlogon.log



After the debugging is finished, you can reset the debug flag to zero by running:

nltest /dbflag:0x0

don't forget to restart net logon service.


full list of dbflag codes cen be found on technet.



05 February 2014

Find user in active directory with missing or empty attribute

Get-ADUser -Filter {-not (employeeid -like "*") }

will return all object that have the property empty.

using $null to match the filter citeria will result in an error:

Get-ADUser : The search filter cannot be recognized

29 January 2014

Disable android system update to 4.4.2

You can disable system update notification on your android device by going to

Settings - > Apps - > Google services framework - > un-tick show notifications.

then Clear data
and Clear cache

15 January 2014

Evaluate excel formula errors

IFERROR function return the value that you specify when a formula evaluates to one of the following errors:

  • #N/A
  • #VALUE!
  • #REF!
  • #DIV/0!
  • #NUM!
  • #NAME?
  • #NULL!
IFERROR(Value / formula that is evaluated, Value_if_error)