13 December 2012

Find exchange servers in domain

If you need to find exchange servers in a domain you can use one of these options:

1. an active directory  user with mailbox will have 2 attributes (msExchHomeServerName and homemdb) that will contain the name of the mailbox server that has his mailbox - once conected to one server you can use exchange console to find the rest of them;

Get-ADUser samaccountname -Properties msExchHomeServerName, homemdb |Select-Object msExchHomeServerName, homemdb |Format-List


2. active directory computer type objects contain "exchange" word in servicePrincipalName attribute; you can use only your organizational unit that contain your servers if you have one to narrow your search:

Get-ADComputer -Filter * -SearchBase 'OU= SERVERS, DC=domain_name,DC=net' -Properties * | Where-Object {$_.serviceprincipalname -like '*exchange*'} |select-object  name


3. active directory configuration partition contain information about exchange servers in domain; you can search for objects of class msExchExchangeServer:

Get-ADObject -LDAPFilter "(objectClass=msExchExchangeServer)" –SearchBase "CN=Configuration,DC=domainname,DC=net" | Select-Object  name


or you can list all objects from "CN=Servers,CN=First Administrative Group,CN=Administrative Groups,CN=INTERNAL,CN=Microsoft Exchange,CN=Services,CN=Configuration,DC=domainname,DC=net" using powershell or ADSI Edit console;

Get-ADObject -Filter * -SearchBase "CN=Servers,CN=First Administrative Group,CN=Administrative Groups,CN=INTERNAL,CN=Microsoft Exchange,CN=Services,CN=Configuration,DC=domainname,DC=net" -SearchScope onelevel

04 December 2012

Error code 0x80041002

Error code 0x80041002 is WMI related and in my case was solved by running the script below; the affected operating system was a Windows 2003 Enterprise Edition SP2 64bits with terminal server role installed;

The problem that i encountered was the server coud not be added to NLB (network load balancer) and the error code in NLB console was 0x80041002;
On the server system log the error was an Event ID: 1020 with the message "TermService clustering failed to update the session directory, hresult=0x80004005."

the script that fix the problem in my case (must be saved with the *.bat extension):


net stop winmgmt
c: 
cd %systemroot%\system32\wbem 
rd /S /Q repository
 
regsvr32 /s %systemroot%\system32\scecli.dll 
regsvr32 /s %systemroot%\system32\userenv.dll
 
mofcomp cimwin32.mof 
mofcomp cimwin32.mfl 
mofcomp rsop.mof 
mofcomp rsop.mfl 
for /f %%s in ('dir /b /s *.dll') do regsvr32 /s %%s 
for /f %%s in ('dir /b *.mof') do mofcomp %%s 
for /f %%s in ('dir /b *.mfl') do mofcomp %%s 
echo DONE reboot 
pause 

03 December 2012

Tutorial applications

Soo far the best free applications that i found for using at tutorial creations was Jing and Wink;

Jing is very simple and with just a few functions it makes a great tool for taking screenshots or a screencast limited to 5 minutes;
Can identify and autoselect a screen region (an application windows, task bar ...etc ) or use the rectangular selection; Can add arrow, text, frame or highlight;
The downside (for some but not for me) is that in order to use the application you need to register on screencast.com;


Wink is much more complex and you can do lots of things with it but giving the large number of options you need to get familiar with it before using it; one big advantage - it creates high compressed flash presentations; can capture periodically at the specified time interval and or on mouse and keyboard input;

16 November 2012

Problem Steps Recorder

Problem Steps Recorder is Windows 7 feature that can be used to capture screenshots for every action you perform; The result is a zipped MHTML file;
Default settings of PSR saves only the last 25 screenshots; the number can be encreased;
If you need to capture screenshots that are running with elevated rigths you need to lunch PSR with elevated rigths to.

15 October 2012

Read performance counters from powershell

in good old command prompt typeperf can be used but from what i manged to test is not working ok on windows 2003 (it is not returning process description; it return just counters event if i use some letters and * wildchar and should return more than one process);

use typeperf /? or technet (http://technet.microsoft.com/en-us/library/bb490960.aspx) for usage information;

with powershell we have Get-Counter cmdlet but the use of * wildchar and letters at the same time is not supported on windows 2003 and XP;

best sollution i found was to use WMI from powershell:


Get-WmiObject win32_PerfFormattedData_PerfProc_Process -Filter "Name like 'powersh%'" | Select-Object Name, PercentProcessorTime


Name                      PercentProcessorTime
----                            --------------------
powershell               98
powershell#1           0


14 October 2012

Performance counter with PID information

In order to retreive a process PID from performance counters you need to create the nex registry key which will add the process PID to the process name:

Location: HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\PerfProc\Performance
Type: DWORD
Name: ProcessNameFormat
Value: 2

After the new key is added the performance counter process name will look like this:

InstanceName
-----------------
svchost_1144
spoolsv_1032
frameworkservice_1360


Source: http://support.microsoft.com/kb/281884

12 October 2012

Generate CPU load

a neat trick to generate cpu load:

$result = 1; foreach ($number in 1..2147483647) {$result = $result * $number};

can be extend to:

foreach ($loopnumber in 1..2147483647) {$result=1;foreach ($number in 1..2147483647) {$result = $result * $number};$result}

source: http://waynes-world-it.blogspot.ro/2009/05/generating-100-cpu-with-calc-or.html

11 September 2012

Update Rollup version for Exchange Server 2010

to find what exchange version update rollup you have installed use the command:


Get-Command exsetup| %{$_.fileversioninfo}


FileVersion      : 14.01.0323.006
ProductVersion   : 14.01.0323.006


after yhat you can navigate to technet and verifivy rollup version:

http://technet.microsoft.com/en-us/library/hh135098.aspx

26 August 2012

WMI Query


PowerShell v3:

Get-CimInstance -Query "SELECT * FROM Win32_Process WHERE Name Like 'power%'"

Get-CimInstance -Class Win32_Process -Filter "Name Like 'power%'"


PowerShell v2:

Get-WmiObject -Query "SELECT * FROM Win32_Process WHERE Name Like 'power%'"


for more information:

http://msdn.microsoft.com/en-us/library/ms186146(v=vs.80).aspx


23 August 2012

Last logon date and hour


net user username /domain


The request will be processed at a domain controller for domain domainname.

Account active               Yes
Account expires              Never
Password last set            8/13/2012 9:13:14 AM
Password expires            10/12/2012 9:13:14 AM
Password changeable      8/13/2012 9:13:14 AM
Last logon                       8/23/2012 12:28:36 PM
Group Memberships    

The command completed successfully.

16 August 2012

Find process owner

In order to find a process owner you must use WMI;

(Get-WmiObject -Class win32_process |Where-Object {$_.name -eq 'powershell.exe'}).getowner().user

to retrive all processes owned by a user:

Get-WmiObject -Class win32_process | Where-Object {$_.getowner().user -eq 'username'}

Check “Manager can update membership list” checkbox for AD groups

If you need to give a user permission to update active directory security or distribution group members you need to give the user write permission on the active directory group object;

This can be done using the Add-ADPermission cmdlet which is availbale only on exchange management shell (it is not included in ActiveDirectory module):


Add-ADPermission -Identity ‘AD_Group_Name’ -User ‘AD_Username’ -AccessRights WriteProperty -Properties “Member”

13 August 2012

Resyncronize time on windows




NET TIME /domain:mydomainname /SET /Y 

03 August 2012

Password Never Expires

If you need to enable or disable the "PasswordNeverExpires" for active directory users you can use the command:

Set-ADUser -Identity SamAccountName -PasswordNeverExpires $false


01 August 2012

Difference between single quote and double quote

 ' vs "
It is a known best practice in powershell to use double quotes only when is necessary;
Only between double quotes powershell will:

  • look for the backtick ` excape character and interpret the sequence properly;
    Example: `t will insert a tab; `n will insert new line;
  • look for the dollar $ character and interpret what follows as the name of a variable and replace the variable name with the variable content.
    Example: if $cars = 10;
    "number of cars is $cars" became: "number of cars is 10" 
These rules don't apply to single quotes and this is why is a best practice to only use double quotes only when needed;

26 July 2012

Powershell 3.0 Release Candidate

Powershell 3.0 release candidate (Windows Management Framework 3.0) is now available for download;
http://www.microsoft.com/en-us/download/details.aspx?id=29939


It can be installed on:

  • Windows 7 Service Pack 1
  • Windows Server 2008 R2 SP1
  • Windows Server 2008 Service Pack 2
You also need to install Microsoft .NET Framework 4.0;


24 July 2012

Active Directory Ldap attributes and classes

If you need detalied information about active directory ldap attributes like size of the field or the data type accepted you can use the msdn documentation:


Active Directory classes: http://msdn.microsoft.com/en-us/library/ms680938(v=vs.85)

12 July 2012

Rename-ADObject

If you try to change the "name" ldap attribute of an Active Directory object using the Set-ADUser / Set-ADComputer or any other comdlet that can modify object properties you will get an error message like this:


Set-ADUser : The attribute cannot be modified because it is owned by the system


In order to chnage the "name" ldap attribute use the Rename-ADObject cmdlet.

Example: Rename-ADObject -Identity $user -NewName $newName

09 July 2012

Title case using ToTitleCase method

to transform the first letter of a word (or the first letter of every word of a phrase) to title case you can use ToTitleCase method of Get-Culture command:

(Get-Culture).TextInfo |Get-Member


ToTitleCase    Method     string ToTitleCase(string str)

06 July 2012

Test AD Group Membership

$Group = [ADSI]"LDAP://CN=Group Name,OU=Groups,DC=office,DC=net"
$User= [ADSI]"LDAP://CN=User Name,OU=Users,DC=office,DC=net"

If ($Group.IsMember($user.ADsPath) -eq $True){
    "User is member of group"
    }
else{
    "User is not member of group"
    }


More information about ADSI:
http://msdn.microsoft.com/en-us/library/windows/desktop/aa772212(v=vs.85).aspx

More information about IADsGroup interface and IsMember method:
http://msdn.microsoft.com/en-us/library/windows/desktop/aa706021(v=vs.85).aspx

27 June 2012

Export Ldap multivalue attributes

When you try to export to a CSV file a multivalue Ldap attribute like "MemberOf" or "ProxyAddresses" you will find in CSV file only a description of your attribute data type:

PS C:\temp> Get-ADUser marius.dumitru -Properties memberof|Export-Csv -NoTyeInformation user_groups.csv



You can use "join" function to export the multivalue attribute:

Select-Object name, @{Name="MemberOf"; Expression={[string]::join(";",($_.MemberOf))}}



30 May 2012

Verify function result

Usually a function returns an unpredictable number of results (an array object when is more than one);

We can use the count() method to count the returned number of results when we have more than one result returned, but if the function returns only one or no result at all the count() method cannot be used because the returned object will not be an array;

The solution is to use an array variable in which to save the result; This way you will allways have an arry even if it have only one or no elements in it;


function Retrive-Services{ Get-Service -DisplayName w* }

$var = @(Retrive-Services)

if ($var.count -ge 1){
     $var.gettype()
     "array-ul have " + $var.Count + " records."
     
    foreach ($v in $var){
         $v.name # here you will ussualy do some work;
    }
}
elseif ($var.count -eq 0){
    $var.gettype()
    "array-ul have zero records"
}

Array of custom objects in PowerShell

create a custom object in Powershell v1:

$CustomObject = @()

$obj = New-Object pscustomobject
$obj | Add-Member -property NoteProperty -name somename -value somevalue

$CustomObject += $obj


create a custom object in Powershell v2:

$CustomObject = @()

$obj = New-Object pscustomobject -Properties @{propertyname1= value1; propertyname2=value2}


$CustomObject += $obj


create a custom object in Powershell v2 (variation of method above):

$CustomObject = @()

$hash = @{
    propertyname1 = value1
    propertyname2 = value2
    propertyname3 = value3
}

$obj = New-Object pscustomobject -Properties $hash


$CustomObject += $obj


15 May 2012

netsh - enble / disable network interface


netsh interface set interface name="Local Area Connection" admin=disabled
sleep 10
netsh interface set interface name="Local Area Connection" admin=enabled

19 April 2012

Export DHCP scope rezervation settings

Lunch command prompt window with "Run As Administrator" option (or the command will not work):


netsh dhcp server file://server_name/ scope 192.168.1.0 dump > rezervations.txt




To find a rezervation for speciefic MAC address:

netsh dhcp server \\server_nema scope 192.168.1.0 show reservedip | find "MAC-ADDRESS"

("MAC-ADDRESS" must include dashes)

Retrieve active directory user OU.

User's organizational unit information can be easily extracted from user's DistinguishedName ldap attribute:

$user = Get-ADUser marius.dumitru
$ou = $user.DistinguishedName.Substring($user.DistinguishedName.IndexOf("OU="))

result:

OU=Some users,DC=domain,DC=intra

02 March 2012

PowerShell 3.0 - Beta

Windows Management Framework 3.0 - Beta is now available for download for:

  • Windows 7 Service Pack 1 (32-bit & 64-bit);
  • Windows Server 2008 R2 Service Pack 1 (64-bit only);
  • Windows Server 2008 Service Pack 2 (32-bit & 64-bit) – NEW! Beginning with this Beta release.


Windows Management Framework 3.0 contains Windows PowerShell 3.0, WMI and WinRM. 


Download link: http://www.microsoft.com/download/en/details.aspx?id=28998

01 March 2012

23 February 2012

List organizationalUnit objects.

Get-ADObject -Filter {ObjectClass -eq "organizationalUnit"}| Select-Object Name, DistinguishedName

20 February 2012

Export-Csv -InputObject

Export-Csv does not accept an array of strings as an input object;
The array must be first coverted into objects because Export-Csv need a custom object with multiple properties, not a series of single property strings;

For Export-Csv each objects is a new row of data in the resulted csv file;
Properties of the object will become columns headers and property values - rows;

To overcome this you can use:

$string = "name","age", "location" >> exported_data.csv # this will be the header;
$string = $name + "," + "21" + "," + "Romania" >> exported_data.csv # first csv line;