Archive for the ‘Powershell’ Category

Get IP address of virtual machines running on Hyper-V – FIXED!

Wednesday, March 16th, 2011
Big thank you – goes to Max Trinidad my fellow MVP from Powershell group…
Here is errorless script - much better than mine! :)
Copa, paste and save as .ps1 - then run on your Hyper-V server and you will get IP’s of your virtual machines…

Set-ExecutionPolicy -ExecutionPolicy RemoteSigned

## – Use Line below to list all your Virtualization Class
#get-wmiobject -namespace “root/virtualization” -list

## – Load filter (or function first)
filter Import-CimXml{

    $CimXml = [Xml]$_
    $CimObj = New-Object -TypeName System.Object
   
    foreach ($CimProperty in $CimXml.SelectNodes(“/INSTANCE/PROPERTY”)){
        if ($CimProperty.Name -eq “Name” -or $CimProperty.Name -eq “Data”){
            $CimObj | Add-Member -MemberType NoteProperty -Name $CimProperty.NAME -Value $CimProperty.VALUE
        }
    }
   
    $CimObj
}

## – Collect WMI Virtual information
$getWmiVirtual = Get-WmiObject -Namespace “root\virtualization” -Query “Select * From Msvm_ComputerSystem” | sort-object elementname

## – Build your results from your collected objects
ForEach($v in $getWmiVirtual){
    $vm = $v.ElementName;
    $VmObj = Get-WmiObject -Namespace “root\virtualization” -Query “Select * From Msvm_ComputerSystem Where ElementName=’$vm’”;
    $KvpObj = Get-WmiObject -Namespace “root\virtualization” -Query “Associators of {$VmObj} Where AssocClass=Msvm_SystemDevice ResultClass=Msvm_KvpExchangeComponent”;
    if($KvpObj.GuestIntrinsicExchangeItems -ne $null){
        write-host $vm;
        $KvpObj.GuestIntrinsicExchangeItems | Import-CimXml | where {$_.NAME -match “NetworkAddressIPv4″} | ft;
    }
}

## – End of Script

Get IP address of virtual machines running on Hyper-V

Sunday, February 20th, 2011

I have been searching for an easy solution to somehow “scan” virtual machines and get their IP addresses becouse sometimes you need to find your virtual machines and it is more practical to somehow get a whole list of machines + IPs in stead of loging in from machne to machine and check IP… Well it can be done using Powershell… I have encountered an article but the problem is that here you need to put machine name on which you want to get data… I modified this script a bit so it looks like:

Get-WmiObject -Namespace root\virtualization -Query “Select * From Msvm_ComputerSystem”| sort-object elementname | ForEach-Object {$vm = $_.Elementname
write-host $vm
filter Import-CimXml
{
    $CimXml = [Xml]$_
    $CimObj = New-Object -TypeName System.Object
    foreach ($CimProperty in $CimXml.SelectNodes(“/INSTANCE/PROPERTY”))
    {
if ($CimProperty.Name -eq “Name” -or $CimProperty.Name -eq “Data”)
{

         $CimObj | Add-Member -MemberType NoteProperty -Name $CimProperty.NAME -Value $CimProperty.VALUE

}
    }
    $CimObj
}
$VmObj = Get-WmiObject -Namespace root\virtualization -Query “Select * From Msvm_ComputerSystem Where ElementName=’$vm’”
$KvpObj = Get-WmiObject -Namespace root\virtualization -Query “Associators of {$VmObj} Where AssocClass=Msvm_SystemDevice ResultClass=Msvm_KvpExchangeComponent”
$KvpObj.GuestIntrinsicExchangeItems | Import-CimXml
} | where {$_.NAME -match “NetworkAddressIPv4″} | ft
read-host

So… Copy paste this script to an text file and save it as getip.ps1 and run it using powershell – it does need any other modules you should only run it on Windows Server where you have Hyper-V role installed… (I do not remember but I think you should enable execution policy for ps1 scripts… If you have truble executing your ps1 check here…)

By the way… This script has an error first virtual machine name will not fit in table (I do not know why :) ) and you will get an error when this script will try to analyze your Hyper-V host machine… I do not know how to solve this two errors if someone out there solves it please provide feedback. :) Thank you!

SBS 2011 – Import PST in Exhange 2011

Tuesday, January 11th, 2011

To enable import and export of mailboxes on SBS 2011 you need to:

Go to Windows SBS console and create a security group – that shuld be universal (by default) for example: Mailbox management

Add administrator / admin account to the group

Then you need to enable “import / export” feature on members of this group. To do that you need to open Exchange Management Shell (Powershell with Exchange 2010 modules) as administrator and write:

New-ManagementRoleAssignment -Name “Import Export Mailbox Admins” -SecurityGroup “Mailbox management” -Role “Mailbox Import Export”

After that you can folow my article to import or export mailboxes

Happy migration :) Exchange 2003 to Exchange 2010 SP1

Wednesday, December 22nd, 2010

We have setup a completely new environment with Exchange 2010 SP1… Old Exchange 2003 had around 100 mailboxes with quota from 300 MB - 1GB. I used Exmerge to export all mailboxes from Exchange 2003 (using ExMerge to extract PSTs from Exchange 2003 database) and sucessfuly used new Powershell cmdlets to import them to users in Exchange 2010…

You first need to add permissions to a group in which you put administrator to be able to use import / export features. You can read about that in this article.

Useful comdlets are:

Importing pst to existing mailbox:

New-MailboxImportRequest -FilePath \\oldserver\share\user1.pst -Mailbox user1

To check status of your import type:

Get-MailboxImportRequest | Get-MailboxImportRequestStatistics

If import fails you can try with option:

New-MailboxImportRequest -FilePath \\oldserver\share\user1.pst -Mailbox user1 -BadItemLimit 10

What it does? Saso (tnx man!) explained to me, that it might happen when you have used some antivirus solution that has “corrupted” some e-mails… So try with BadItemLimit 10 probably we are talking about one or two e-mails with problems.

If you want to remove old importrequest you can use:

Remove-MailboxImportRequest -Identity username\MailboxImport or MailboxImport1 or 2…If you want to look at just a signle mailbox import progress you can use modified cmdlet:

Get-MailboxImportRequest -Identity username\mailboximport | Get-MailboxImportRequestStatistics

At the end you will have alot of Completed malilboximport’s… If you want to cleane up your exchange you can run:

Get-MailboxImportRequest -Status Completed | Remove-MailboxImportRequest

Happy importing! :)

SBS 2008 / Exchange 2007 remote.company.com and TLS…

Sunday, September 5th, 2010

Everyone that has ever installed SBS 2008 has encountered the wizard that create certificate and remote workplace – by default called remote.company.com (yes, you can chose other prefixes but let say that I like remote becouse it is easy to remember for my users…).
SBS wizards generates a certificate for this hostname and uses it for all services (Outlook web access, Active Sync stuff and also for SMTP receive and send connectors…).
The problem is when you want to rename your SMTP receive and send connectors to match the records in DNS. It is a best practice to have same SMTP greetings as the records in DNS so for example if you have a domain company.com and you have an host record A called mail.company.com and MX record pointed to mail.company.com it is correct and I suggest you to folow this rule to have SMTP greeting or fqdn for SMTP connectors to match mail.company.com.

You can rename your connectors however you want by using Exchange management console but you will lose functionality of TLS in SMTP traffic – becouse the certificate remote.company.com does not match fqdn or smtp greeting of a connector that advertise mail.company.com. You will also get an error in Event log saying:

Microsoft Exchange could not find a certificate that contains the domain name mail.company.com in the personal store on the local computer…

 Ok, what can we do now?

Well turn on Exchange Management Shell – that is Powershell with modules for Exchange 2007 management – you can find it in star menu… And first of all we want to see current Exchange certificates that are enabled for Exchange services by using cmdlet:

[PS] C:\Windows\System32>Get-ExchangeCertificate 

and you wil receive something like this:

Thumbprint                                Services   Subject
———-                                ——–   ——-
45EEEB44DF4BFE2EB1B7A7592EA1DF5BF93F44B4  IP.WS      CN=remote.company.com
42F146B12BEF918A6A8FC730F5AA87AC4ACB1CEB  IP..S      CN=remote.company.com
817F1311CB72FB70F962EC0FAD2D8FA857F114A4  ….S      CN=sbssrv01.company.local
4BAAC7906689AFF0129767CF492AAE058B5DF494  ….S      CN=Sites
8F1D9C5FEB6EF0C39F25175AFBDEA54FE9668EF9  …..      CN=xxxxxx-xxxxxxxx-CA
8E4F33523325500F38ECF41FCDFBBE684AFC6145  …..      CN=WMSvc-WIN-K7KGUV5MQ40
 
Now we should create a new certificate that we will use for SMTP connectors by using cmdlet:
 
New-ExchangeCertificate -domainname mail.company.com -PrivateKeyExportable:1
 
Warning! When you are asked if you want to overwrite certificates chose No!
  
Confirm
Overwrite existing default SMTP certificate,
’45EEEB44DF4BFE2EB1B7A7592EA1DF5BF93F44B4′ (expires 14.1.2012 22:37:04), with
certificate ’59D62E7850EE4093AFF1EC73E2623D52058C2B35′ (expires 27.1.2015
17:09:02)?
[Y] Yes  [A] Yes to All  [N] No  [L] No to All  [S] Suspend  [?] Help
(default is “Y”): N
 
so we get output:
Thumbprint                                Services   Subject
———-                                ——–   ——-
59D62E7850EE4093AFF1EC73E2623D52058C2B35  …..      CN=mail.company.com
 
Great!  If we want to be shure that everything is working correctly and that Exchange SMTP service is using our new certificate we can use cmdlet:

[PS] C:\Windows\System32>Get-ExchangeCertificate 

[PS] C:\Windows\System32>

Thumbprint                                Services   Subject
———-                                ——–   ——-
59D62E7850EE4093AFF1EC73E2623D52058C2B35  ….S      CN=mail.company.com
45EEEB44DF4BFE2EB1B7A7592EA1DF5BF93F44B4  IP.WS      CN=remote.company.com
42F146B12BEF918A6A8FC730F5AA87AC4ACB1CEB  IP..S      CN=remote.company.com
817F1311CB72FB70F962EC0FAD2D8FA857F114A4  ….S      CN=sbssrv01.company.local
4BAAC7906689AFF0129767CF492AAE058B5DF494  ….S      CN=Sites
8F1D9C5FEB6EF0C39F25175AFBDEA54FE9668EF9  …..      CN=xxxxxxxxxxx-xxxxxxxxxxxx01-CA
8E4F33523325500F38ECF41FCDFBBE684AFC6145  …..      CN=WMSvc-WIN-K7KGUV5MQ40
We can now see that SMTP connectors are using all certificates (S defnies SMTP service).
Ok… How can you test that TLS works?
You can try it by using telnet client and connect to your server:
telnet mail.company.com 25
 
Exchange should respond something like:
220 mail.company.com Microsoft ESMTP MAIL Service ready at Wed, 27 Jan 2010 17:
12:09 +0100
 
then you can write:
helo test.blablabla.com
 
220 mail.company.com Microsoft ESMTP MAIL Service ready at Wed, 27 Jan 2010 17:
13:07 +0100
helo test.blablabla.si
250 mail.xxxxxxxxxxxxxxxx.si Hello [xxx.xxx.xxxx.xxx]
after that enter command:
starttls

 

server should respond:
220 2.0.0 SMTP server ready
 
Server ready? Super! :)
 
PS.
If you did miss something you will receive error from server saying:
 
starttls
500 5.3.3 Unrecognized command
 
If you get that? Read this tutorial again :)
PS. PS. You do not need to restart anything when you apply this commands… No need for restarting Exchange services…
Special thanks to Saso Erdeljanov for some hints about this issue…

Powershell with task scheduler… This is the way to automate your IT! – remote machine – p2

Tuesday, August 10th, 2010

Ok! Welcome to part two… What is the idea behind this second part… Well with Powershell 2.0 we have now Powershell remoting that allow us to run commands on remote machines… When we are thinking about automating tasks we would like to execute some powershell scripts on servers or machines around our company.

Ok in example 2 we have two servers:
DEMOAD.demo.local – active directory server
and
DEMORDSSRV01.demo.local – member server (in fact remote desktop server but it is not an important info… :) )

Let say that we will be connected to DEMOAD.demo.local and we will prepare a script and schedule it to get information from DEMORDSSRV01.demo.local

1. First we need to enable Powershell remoting on DEMORDSSRV01.demo.local using Powershell cmdlet:

Enable-PSRemoting

2. We need to test if remoting works so we can test it by using cmdlet:

Test-WSMan -ComputerName DEMORDSSRV01 

this cmdlet should be run on DEMOAD machine. If  everything is ok you should receive something like:

wsmid : http://schemas.dmtf
ProtocolVersion: http://schemas
ProductVendor: Microsoft Corporation
ProductVersion: OS: 0.0.0 SP: 0.0 Stack: 2.0

If you did not enable remoting on DEMORDSSRV01.demo.local you will receive:

Test-WSMan : The WinRM client cannot complete the operation…

If you receive this error try to reenable Powershell Remoting by using cmdlet: Enable-PSRemoting

3. Create a powershell script (a txt file that has extension .ps1) for example remoteprocess.ps1 edit it with your notepad and write inside the cmdlet:
get-process -computername demordssrv01 | out-file c:\remoteprocess.txt

this script will request process list from demordssrv01 and the result will be pipelined to txt file called c:\remoteprocess.txt on demoad.demo.local – so from machine that will execute the query.

4. When you are done with script you just need to create a Basic Task in Task Scheduler. You can check my prevous article (part1) to see other steps to do that.

Powershell with task scheduler… This is the way to automate your IT! – single machine – p1

Thursday, June 17th, 2010

Well using Powershell interactively is something that we see all the time when Microsoft want to show us what and how we can automate our daily taks… But administrators want to know how can we schedule our brand new fantastic powershell scripts…

Ok, this guide will tell you how to do it… How to run separate commands from powershell and how to run a complete scripts so you can realy start to automate your stuff by using Powershell…

Example: I would like to schedule script that lists all processes running on a specific server
1. on my server I will first create a txt file (extension should be renamed to ps1 – as we are writing powershell script) called listproces.ps1
2. into the file I will put my scipt:

get-process | out-file c:\processes.txt

3. start task scheduler on server and Create Basic Task
Name: Powershell list processes
Triger: Chose when you want your script to run
Action: Start a program
Program / script: powershell.exe
Add arguments: -ExecutionPolicy RemoteSigned –Noninteractive –Noprofile –File C:\listproces.ps1

Important! You should set your task to run whether user is logged into a session or not… To do that do the folowing:


Hyper-V FreeBSD shutdown problem workaround

Friday, July 18th, 2008

Thanks to Mike … 

Mike wrote: 

“I’ve found an even easier way to do this.  I found a PowerShell Hyper-V script at:

http://www.codeplex.com/PSHyperv

It has a lot of functions already, and I added a “Kill-VM” function that automates the kill process:

Kill-VM <VM name>

My modified script is attached to this message.

To use it, you need to install PowerShell (Under Server Manager -> Features in Win2008).  Once installed, run PowerShell from Start -> Search, find the script, and type:

. .\hyperv.ps1

Once loaded into memory, type:

Kill-VM <VM Name>

Enjoy”

Click here to download script – hyperv-script.zip

Portable Powershell even on Windows server 2008 core – it is possible!

Wednesday, June 18th, 2008

Look at: http://karlprosser.com/coder/2008/06/17/portable-powershell-v1-and-v2-side-by-side-even-on-server-core/

 Great stuff!!!

Mailbox statistics using Powershell in Exchange 2007

Saturday, January 12th, 2008

1. Sorted by Displayname (Display name, Mailbox size (MB), Item count, Last logon time, Last logoff time, Last loggedon user account)

Get-MailboxStatistics -Database “mailbox database” | Sort -Property DisplayName | ft DisplayName,@{expression={$_.totalitemsize.value.ToMB()};label=”Mailbox Size(MB)”}, itemcount, lastlogontime,lastlogofftime,lastloggedonuseraccount

2. Sorted by Last logon time
Get-MailboxStatistics -Database “mailbox database” | Sort -Property lastlogontime | ft DisplayName,@{expression={$_.totalitemsize.value.ToMB()};label=”Mailbox Size(MB)”}, itemcount, lastlogontime, lastlogofftime