Showing posts with label powershell. Show all posts
Showing posts with label powershell. Show all posts

Monday, March 6, 2017

Exchange DAG Failover Report - CollectOverMetrics.ps1

Below is my quick command that requires no customization to run on any installation:

  • Get-DatabaseAvailabilityGroup |%{ .\CollectOverMetrics.ps1 -DatabaseAvailabilityGroup "$($_.name)" -StartTime ((get-date).AddDays(-365)) -EndTime ((get-date)) -MergeCSVFiles}

Note that this script is located in the "Scripts" directory of your Exchange v15 installation. 

Monday, May 30, 2016

Use Splatting, Proxy, and Metadata in Powershell

Use Splatting, Proxy, and Metadata in Powershell

  • Splatting is the ability to use a dictionary or a list to supply parameters to a command.

    Example:
    $MailMessage = @{
        To = “me@mycompany.com
        From = “me@mycompany.com
        Subject = “Hi”
        Body = “Hello”
        Smtpserver = “smtphost”
        ErrorAction = “SilentlyContinue”
    }
    Send-MailMessage @MailMessage
  • Proxy commands are wrappers of existing commands in Windows PowerShell, and to make this possible, a number of different things had to be enabled in the language that can have interesting other uses.
  • Metadata provides information about the command and parameters of different commands, and provides a structure that you can use to “write” a command without typing out the whole script.

https://blogs.technet.microsoft.com/heyscriptingguy/2010/10/18/use-splatting-to-simplify-your-powershell-scripts/

Friday, April 15, 2016

Active Directory Last Logon. Lots of confusion

I am sure that everyone who administrates AD runs into this problem at some point.

Here is an article that thoroughly lays it all out.

http://social.technet.microsoft.com/wiki/contents/articles/22461.understanding-the-ad-account-attributes-lastlogon-lastlogontimestamp-and-lastlogondate.aspx

The summary of this article is, that if you want to find out the TRUE last logon activity for a user, it is best to use the command

Search-ADAccount -AccountInactive -DateTime ((get-date).adddays(-90)) -UsersOnly

If you are ONLY interested in dates that are more than 14 days ago, then you can safely use the "LASTLOGONDATE" attribute.  

Less than 14 days of viewing and you cannot rust this attribute.  You must get fancy and query all of the DC's individually. 

Tuesday, December 29, 2015

Fix Trust Relationship if a simple Computer password reset is required

Fix Trust Relationship if a simple Computer password reset is required

http://blog.blksthl.com/2013/03/18/fix-the-trust-relationship-between-this-workstation-and-the-primary-domain-failed/

This is dead simple, but if you were not aware, you do not necessarily need to rejoin the domain if the trust relationship is broken with AD.  Just resetting the password is all .

Steps using Powershell:
  1. Login locally to the server
  2. Run the PowerShell command:
Reset-ComputerMachinePassword -Server -Credential

Restart-Computer


Thursday, December 24, 2015

Migrating Public Folders Exchang 2007 to 2013

There are lots of great blogs out there on how to do the overall migration of Public folders from previous versions of Exchange to 2013, but few of them detailed how to deal with a few choice issues that I encountered in a recent migration that I performed.


For a good, detailed, checklist of how to do the migration, see any of the following:






My migration was for 50,000 folders, and about 130GB of data.


The issues that I ran into were (but not limited to):

  •     Needing a System Attendant mailbox on each server hosting Public Folders
  •     Spaces at the end of the names of folders
  •     Invalid characters in the Alias attribute, and
  •     Invalid SMTP email addresses in Mail-Enabled Public Folders

Each of these had to be fixed before I could start the migration.


System Attendant Mailbox required

This is actually fairly well documented, but I had missed it and the symptoms in no way pointed me to the root cause of the problem.

Basically, each server that hosts a Public Folder requires this System Attendant mailbox.  In my case I had no Mailbox Databases on the PF servers.

The symptom is that in the detailed log of the PublicFolderMigrationRequest indicated "

Transient Error: MapiExceptionUnknownUser: Unable to make connection to the server. (hr=0x80004005, ec=1003)


This was resolved by creating a mailbox database on each server, and then also restarting the "Microsoft Exchange System Attendant" service.  That created the system attendant ID automatically.


Spaces at the end of a folder name


The first problem was identified when I ran the command


Get-PublicFolder -Recurse | Export-CSV C:\PFs\2010_PFStructure.csv -NoTypeInformation

  This was easy to fix following this article:


The issue with this simple script is that the script in this article runs against all folders.


Get-PublicFolder -Identity "\" -Recurse -ResultSize Unlimited | Foreach { Set-PublicFolder -Identity $_.Identity -Name $_.Name.Trim() }


To improve this, I modified the command to skip folders that did not need to be updated.  Speeds up the command significantly. I also added a log file entry for each folder being processed.

$Logfile = "Fix-Trimmed-Names-001.log"
Get-PublicFolder -Identity "\" -recurse -ResultSize Unlimited | %{
  write-host "Scanning $($_.identity)";
  add-content $logfile -value "Scanning $($_.identity)";
  if ($_.name -ne $_.name.trim() ) {
    write-host "fixing [$($_.name)]" -foregroundcolor yellow;
    add-content $logfile -value "fixing [$($_.name)]"
    Set-PublicFolder -Identity $_.Identity -name $_.name.trim()
  }
}


 Invalid characters in the Alias attribute

 The Alias property of a Public Folder cannot contain Spaces, Periods, Commas, @, and even an Apostrophe.   The following script removed these characters.  (Note that the script is a little rough, but you can figure it out).


[PS] >type .\Fix-Alias-001.ps1
$Names = get-mailpublicfolder -resultsize unlimited |?{$_.Alias -like "* *"}
#$Names = get-mailpublicfolder -resultsize unlimited |?{$_.Alias -like "*.*"}

foreach ($name in $Names) {
  $newAlias = $name.alias
  $newAlias = $newAlias.replace(" ","_")
  $newAlias = $newAlias.replace("@","&")
  $newAlias = $newAlias.replace("(","{")
  $newAlias = $newAlias.replace(")","}")
  $newAlias = $newAlias.replace(",","~")
  $newAlias = $newAlias.replace(".","~")
  $newAlias = $newAlias.replace("'","~")
  set-mailpublicfolder -identity $name.identity -alias "$newalias"
}


Invalid SMTP email addresses in Mail-Enabled Public Folders

 This seems to have occurred for reasons similar to the Alias issue.  I was told that the users did not intentionally create Public Folders as Email-Enabled, therefore, rather than dig into fixing each of the mailboxes to change teh SMTP name, we elected to simply run a "Disable-MailPublicFolder" against each of the mail-enabled public folders.   End of issue.

Tuesday, October 20, 2015

Export/Import OU's from Active Directory to LAB

This is a quick and dirty but works.


Here is a simple script to export and then import the OU structure from one AD to another, such as when you want to create a lab from a production AD.


To export the Prod OU's to a CSV, enter the following command:


 Get-ADOrganizationalUnit -Filter *|select name,@{n="Path";E={($_.DistinguishedName).replace("OU="+$_.name+",","") }} | ConvertTo-Csv -NoTypeInformation |out-file -FilePath Prod-OUS-4-Import.csv


Next,  edit the domain name in the CSV to change it to the new domain.
Also, clean up the file to remove any OU's that are out of scope. 


Third, run the following script using the CSV to import the names and Path of the OU's

# Command Line Parameters
Param(
 [Parameter(Mandatory=$false,HelpMessage='CSV FIle')][string]$Inputfile=".\Prod-OUS-4-Import.csv"
)

import-module activedirectory
# Read in data
$OUS = import-csv $InputFile
$ous |ft -a  #validate data on screen

# get current OUs for errorchecking
$currentous = get-adorganizationalunit -filter *

# Create ou for each line in CSV
foreach ($ou in $ous) {
 $error.clear()
 $path = "OU=$($ou.name),$($ou.path)"
 #write-host "$path"
 If ( $currentOUS | ?{$_.DistinguishedName -eq $path } ) {
  write-host  "Exists:  OU=$($ou.name),$($ou.path) already exists" -foregroundcolor yellow
 } else {
  new-ADOrganizationalUnit -name $ou.name -path $ou.path  -ProtectedFromAccidentalDeletion:$false  -ErrorAction:silentlycontinue
  if ($error.count -gt 0) {
   write-host "Failed:  OU=$($ou.name),$($ou.path)"  -foregroundcolor red
  } else {
   write-host "Created: OU=$($ou.name),$($ou.path)"  -foregroundcolor green
  }
 }
}




Examining GPO Health

I was recently asked to evaluate an Active Directory environment to determine it's health, specifically relating to GPO's and how they were being used.

I discovered that the number and configuration of the OU's, GPO's, and contents, were a clear indication that the administration of GPO's was not well understood by the committee of people who were managing them, and that there were clearly problems being self-inflicted due to these issues.

The question, however, was how can we quickly assess whether the management of GPO's was in trouble, and also how can we quantify the issue?

The first thing to understand is that there are Recommended Best Practices from Microsoft for how to manage GPO's.  See https://technet.microsoft.com/en-us/library/cc785903(v=ws.10).aspx

But how to quantify these subjective suggestions?



First,  "Minimize the Use of the Block Policy Inheritance Feature".  


You can determine the number of OU's that have Blocked Policy Inheritance with the follow PowerShell command:

Get-ADOrganizationalUnit -Filter * | Get-GPInheritance | Where-Object {$_.GPOInheritanceBlocked}| measure

After having seen a "bad" install, I believe that the number should be less than 5% of the total number of OU's.  Or perhaps a raw number of 10-15 might be allowed.



Second, "Minimize the Use of the Enforce Feature".

How do you determine how many GPO's have Enforce Enabled?  How do I know where these are linked?
One quick way is to list all Links that are Enforced.
Use the following command:
Get-ADOrganizationalUnit -Filter * | Get-GPInheritance | Foreach {$_.GPOLinks } | Where {$_.Enforced} |  select DisplayName,Enabled,Enforced,Target

Another is to list the full set of GPO's linked to a single OU.  Example: for the OU=Servers there
Get-ADOrganizationalUnit "ou=servers,ou=corp,dc=mydomain,dc=com" | Get-GPInheritance |%{ $_.inheritedgpolinks }

This command will list the same information that is displayed in the GPMC GUI under the "Group Policy Inheritance" tab.  Note that the Order property is the order of the source GPO order on the applied OU, not the resulting order in the reported OU.  The property is listed in the precedence order of execution (backwards of course).

To report all OUs, and all links in all OU's, requires a bit more work.
$OUs = Get-ADOrganizationalUnit -Filter * | select DistinguishedName,LinkedGroupPolicyObjects,Name
$OUs += Get-ADDomain
$report = foreach ($ou in $OUs) {
   if ($ou.LinkedGroupPolicyObjects) {
   $inher = Get-GPInheritance -target $ou.DistinguishedName
   $count = 0
     foreach ($link in $inher.inheritedGpoLinks) {
       $count += 1
       "" | select-Object -property @{n="ou";E={$inher.Path}},
    @{N="Order";E={$count}},
       @{n="GPOname";e={$link.Displayname}},
    @{N="Enabled";E={$link.enabled}},
    @{N="Enforced";E={$link.enforced}},
    @{N="Target";E={$link.Target}}
     }
   }
  }

$report |export-csv .\GPO-Links-cwInheritance.csv  -NoTypeInformation


Wednesday, June 17, 2015

Querying Event Logs using XML

I have been working for a little while on creating tools for an administrator to be able to manage an Active Directory for Least Privileges Principles, and to secure AD Access.

Specifically here, I will be talking about configuring Monitoring and Alerts for suspicious behavior in the administration of Active Directory.

The first activity to monitor and to generate an alert is a logon by a member of the Microsoft Privileged Groups.  It is assumed that you have read and are following the Microsoft Best Practice of normally having ZERO members of the Privileged Groups (Domain Admins, Enterprise Admins, etc).  Membership in these groups is only granted temporarily in order to perform a specific task.   The Intruder Attack Surface of your Ad is minimized by reducing the time that this elevation of privileges exist.

But what about abuse of privilege, or unauthorized role elevation?

By monitoring and alerting on every logon and logoff on any computer of anyone with this group membership, you are able to track the activities of the role, and able to detect unauthorized access.

Here is how it is done.

(see http://blogs.technet.com/b/askds/archive/2008/03/11/special-groups-auditing-via-group-policy-preferences.aspx for background on these instructions )
  • Configure a GPO that creates a Registry entry for "SpecialGroups".  
    1.   First, Document all of the SID's for the groups that you wish to monitor.  
      1. In PowerShell, import the Active Directory Module.
      2. For each group in scope, type a Get-ADGroup -id "Domain Admins", etc.
      3. Note the SID of that group.
    2. Create a GPO To distribute the Special Group Registry key
      1. GPMC -> Edit GPO -> Computer Configuration -> Preferences -> Windows Settings - Registry
      2. Create a new Registry Entry:
        Key Path: HKLM\SYSTEM\CurrentControlSet\Control\Lsa\Audit
        Value Name: SpecialGroups
        Value Type: REG_SZ
        Value Data: S-1-5-21-3496112146-2253716704-1307938399-512;S-1-5-21-3496112146-2253716704-1307938399-519;S-1-5-32-544
        (Note: use the SID's that you documented in step 1, separated by ";"
    3. Apply the GPO to all computers that you want to monitor for "SpecialGroups" Logon.
    4. The final step is to set up monitoring of Event ID 4964.    (I will add a PowerShell script to run for this purpose...  Stay tuned.)

Tuesday, August 5, 2014

Using activedirectory powershell module with 2003 domain controllers


See the following for step by step how to use active directory powersSell cmdlets against 2003 domain controllers
http://blogs.technet.com/b/ashleymcglone/archive/2011/03/17/step-by-step-how-to-use-active-directory-powershell-cmdlets-against-2003-domain-controllers.aspx

Also, in order to run RSAT on Windows 7, with 2003 or 2008 DC's:
This is still untested, but it looks like the author has figured out how to add the Active Directory PowerShell modules to Windows 7.

Why would you want to do this?

Well, I am writing PowerShell script to document AD, and I would like to be able to run them in an older AD environment, such as an upgrade candidate, etc.

With a Win 7 workstation, I am hoping that I can load it up and run the script against an old 2003 server.

System Requirements:
This information was found on a forum (http://social.technet.microsoft.com/Forums/windowsserver/en-US/094f9dd3-669a-4bea-9f81-f2ea009384d1/powershell-v2-and-active-directory-module)

Also see: http://www.mikepfeiffer.net/2010/01/how-to-install-the-active-directory-module-for-windows-powershell/

I decided to post the content here just in case I loose access to the blog.


In summary:
I found a very Simple and Elegant way to make the AD PowerShell Module Portable.
you will need 3 simple things
1.) the ActiveDirectory Module Directory from a system that has it already installed. 
Standard path on a 64bit windows 7
C:\Windows\System32\WindowsPowerShell\v1.0\Modules
2.)  Global Assembly Cache Utility
Available from the Windows SDK
gacutil.exe
3.) the Microsoft.ActiveDirectory.Management dll assembly
found on a system that already has the RSAT and powershell enabled. Microsoft.ActiveDirectory.Management.dll
Now in order to make this work you need to install the dll using the gacutil program.  commandline is as follows.
GACUTIL.exe -I Microsoft.ActiveDirectory.Management.dll
Once installed you must copy the entire directory from item 1 to the powershell module location.
Once copied you can then use the import command to import it and start using the cmdlets.  below is my batch file I wrote to automate this for deployment during SCCM.
We want our help desk to be able to clone security groups assigned to our computers for application deployment so that when they image a replacement computer the new computer will automatically get the previously assigned applications.  Also see below for that powershell script as well.  Hope this helps the community.
And for the people/MS that say it can not be done,  here to you :)

REM ************************************
REM SET Working Directory
REM ************************************

@setlocal enableextensions
@cd /d "%~dp0"

REM ************************************
REM Copy Module
REM ************************************

if not exist C:\Windows\System32\WindowsPowerShell\v1.0\Modules\ActiveDirectory mkdir C:\Windows\System32\WindowsPowerShell\v1.0\Modules\ActiveDirectory
xcopy /y /e .\ActiveDirectory\*.* C:\Windows\System32\WindowsPowerShell\v1.0\Modules\ActiveDirectory

REM ************************************
REM Install Microsoft Active Directory Assembly
REM ************************************

gacutil.exe -i Microsoft.ActiveDirectory.Management.dll
REM ************************************
REM Set Powershell Execution Policy
REM ************************************

powershell set-executionpolicy remotesigned
REM ************************************
REM Run Computer Membership Clone
REM ************************************

powershell ./ADCompMemberof.ps1
exit

######################################################################
Powershell script to copy group membership of a computer object in AD
  # Create TS Environment COM Object
$TS = New-Object -ComObject Microsoft.SMS.TSEnvironment
$Target=$TS.Value('_SMSTSMachineName')
$Source=$TS.Value('OldComputer')

$array = @()
$groups = Get-AdComputer -Identity $source -property "MemberOf" 

Foreach($group in $groups.memberOf) {
$array +=$group
}

Get-ADComputer -Identity $target | Add-ADPrincipalGroupMembership -MemberOf $array

Tuesday, April 22, 2014

PowerShell Tips #2 - Working with Multi-Instance or Nested Properties

The objective here is to create reports of objects that contain properties with multiple instances, or nested properties.

Example is Get-DNSServer

Get-DNSServer by itself, with no parameters, produces a very detailed, multiple-heading report with a ton of detail.   The internal code to produce this report will be the subject of another technote.

For this exercise though, see the outout from the command

PS C:\ > Get-DnsServer |gm -MemberType Property

Name                       MemberType Definition
----                       ---------- ----------
PSComputerName             Property   string PSComputerName {get;}
ServerCache                Property   CimInstance#Instance ServerCache {get;set;}
ServerDiagnostics          Property   CimInstance#Instance ServerDiagnostics {get;set;}
ServerDsSetting            Property   CimInstance#Instance ServerDsSetting {get;set;}
ServerEdns                 Property   CimInstance#Instance ServerEdns {get;set;}
ServerForwarder            Property   CimInstance#Instance ServerForwarder {get;set;}
ServerGlobalNameZone       Property   CimInstance#Instance ServerGlobalNameZone {get;set;}
ServerGlobalQueryBlockList Property   CimInstance#Instance ServerGlobalQueryBlockList {get;set;}
ServerRecursion            Property   CimInstance#Instance ServerRecursion {get;set;}
ServerRootHint             Property   CimInstance#InstanceArray ServerRootHint {get;set;}
ServerScavenging           Property   CimInstance#Instance ServerScavenging {get;set;}
ServerSetting              Property   CimInstance#Instance ServerSetting {get;set;}
ServerZone                 Property   CimInstance#InstanceArray ServerZone {get;set;}
ServerZoneAging            Property   CimInstance#InstanceArray ServerZoneAging {get;set;}
ServerZoneScope            Property   CimInstance#InstanceArray ServerZoneScope {get;set;}


What I am interested in reporting is the IP Addresses of the Forwarders, which is contained in the "ServerForwarder" property.


So, we now type "(get-dnsserver).ServerForwarder" and get the following:

UseRootHint        : True
Timeout(s)         : 3
EnableReordering   : True
IPAddress          : {10.1.1.4, 10.2.1.20}
ReorderedIPAddress : {10.1.1.4, 10.2.1.20}


Now type:
PS C:\ > (get-dnsserver).ServerForwarder | GM

Name                      MemberType     Definition
----                      ----------     ----------
EnableReordering          Property       bool EnableReordering {get;set;}
PSComputerName            Property       string PSComputerName {get;}
Timeout                   Property       uint32 Timeout {get;set;}
UseRootHint               Property       bool UseRootHint {get;set;}
IPAddress                 ScriptProperty System.Net.IPAddress[] IPAddress {get=[OutputType([Syste...
ReorderedIPAddress        ScriptProperty System.Net.IPAddress[] ReorderedIPAddress {get=[Outpu...


Notice that a "Property" of the ServerForwarder property is not a Property at all, but rather a ScriptProperty.  It contains multiple values as a sudo-property. 

So lets keep going.   
PS C:\> ((get-dnsserver).ServerForwarder).IPAddress
 

Address            : 67174666
AddressFamily      : InterNetwork
ScopeId            :
IsIPv6Multicast    : False
IsIPv6LinkLocal    : False
IsIPv6SiteLocal    : False
IsIPv6Teredo       : False
IsIPv4MappedToIPv6 : False
IPAddressToString  : 10.1.1.4

Address            : 335610378
AddressFamily      : InterNetwork
ScopeId            :
IsIPv6Multicast    : False
IsIPv6LinkLocal    : False
IsIPv6SiteLocal    : False
IsIPv6Teredo       : False
IsIPv4MappedToIPv6 : False
IPAddressToString  : 10.2.1.20


So how do we query the DNS Server and spit out this magical list of IP Addresses?
Method 1) 
PS C:\ > (((get-dnsserver).ServerForwarder).IPAddress).IPAddressToString
10.1.1.4
10.2.1.20


Method 2)


PS C:\ > Get-DnsServer |%{$_.ServerForwarder | %{($_.IPAddress).IPAddressToString}}

10.1.1.4
10.2.1.20


End of Lesson.

Monday, November 25, 2013

Powershell Tricks and Notes

How to expand parameterizedProperty

Note if you issue the following command:

Get-ADComputer -Filter * |Get-Member

You will get the following result:
  TypeName: Microsoft.ActiveDirectory.Management.ADComputer

Name              MemberType            Definition
----              ----------            ----------
Contains          Method                bool Contains(string propertyName)
Equals            Method                bool Equals(System.Object obj)
GetEnumerator     Method                System.Collections.IDictionaryEnumerator GetEnumerator()
GetHashCode       Method                int GetHashCode()
GetType           Method                type GetType()
ToString          Method                string ToString()
Item              ParameterizedProperty Microsoft.ActiveDirectory.Management.ADPropertyValueCollection Item(string p...
DistinguishedName Property              System.String DistinguishedName {get;set;}
DNSHostName       Property              System.String DNSHostName {get;set;}
Enabled           Property              System.Boolean Enabled {get;set;}
Name              Property              System.String Name {get;}
ObjectClass       Property              System.String ObjectClass {get;set;}
ObjectGUID        Property              System.Nullable`1[[System.Guid, mscorlib, Version=4.0.0.0, Culture=neutral, ...
SamAccountName    Property              System.String SamAccountName {get;set;}
SID               Property              System.Security.Principal.SecurityIdentifier SID {get;set;}
UserPrincipalName Property              System.String UserPrincipalName {get;set;}



Notice that property "Item".

So when you type:

Get-ADComputer -Filter * -Property * |Get-Member

You hope tp get something that expands the properties of "Item".

Now.  What if you get an error:
PS C:\Data\Scripts> Get-ADComputer -Identity lab17dc1 -property * |gm
Get-ADComputer : One or more properties are invalid.
Parameter name: msDS-AssignedAuthNPolicy
At line:1 char:1
+ Get-ADComputer -Identity lab17dc1 -property * |gm
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : InvalidArgument: (lab17dc1:ADComputer) [Get-ADComputer], ArgumentException
    + FullyQualifiedErrorId : ActiveDirectoryCmdlet:System.ArgumentException,Microsoft.ActiveDirectory.Management.Comm
   ands.GetADComputer


Well that is a big Oops.  It is actually a bug in AD.
Here is a workaround for THIS bug.  To get your properties, do the following:

Get-ADComputer -Identity lab17dc1 |Get-ADObject -properties *|gm

Now you get something like:
    TypeName: Microsoft.ActiveDirectory.Management.ADObject
Name                            MemberType            Definition
----                            ----------            ----------
Contains                        Method                bool Contains(string propertyName)
Equals                          Method                bool Equals(System.Object obj)
GetEnumerator                   Method                System.Collections.IDictionaryEnumerator GetEnumerator()
GetHashCode                     Method                int GetHashCode()
GetType                         Method                type GetType()
ToString                        Method                string ToString()
Item                            ParameterizedProperty Microsoft.ActiveDirectory.Management.ADPropertyValueCollection...
accountExpires                  Property              System.Int64 accountExpires {get;set;}
badPasswordTime                 Property              System.Int64 badPasswordTime {get;set;}
badPwdCount                     Property              System.Int32 badPwdCount {get;set;}
CanonicalName                   Property              System.String CanonicalName {get;}
CN                              Property              System.String CN {get;}
codePage                        Property              System.Int32 codePage {get;set;}
countryCode                     Property              System.Int32 countryCode {get;set;}
Created                         Property              System.DateTime Created {get;}
createTimeStamp                 Property              System.DateTime createTimeStamp {get;}
Deleted                         Property              System.Boolean Deleted {get;}
Description                     Property              System.String Description {get;set;}
DisplayName                     Property              System.String DisplayName {get;set;}
DistinguishedName               Property              System.String DistinguishedName {get;set;}
dNSHostName                     Property              System.String dNSHostName {get;set;}
dSCorePropagationData           Property              Microsoft.ActiveDirectory.Management.ADPropertyValueCollection...
instanceType                    Property              System.Int32 instanceType {get;}
isCriticalSystemObject          Property              System.Boolean isCriticalSystemObject {get;set;}
isDeleted                       Property              System.Boolean isDeleted {get;}
LastKnownParent                 Property              System.String LastKnownParent {get;}
lastLogoff                      Property              System.Int64 lastLogoff {get;set;}
lastLogon                       Property              System.Int64 lastLogon {get;set;}
lastLogonTimestamp              Property              System.Int64 lastLogonTimestamp {get;set;}
localPolicyFlags                Property              System.Int32 localPolicyFlags {get;set;}
logonCount                      Property              System.Int32 logonCount {get;set;}
Modified                        Property              System.DateTime Modified {get;}
modifyTimeStamp                 Property              System.DateTime modifyTimeStamp {get;}
msDFSR-ComputerReferenceBL      Property              Microsoft.ActiveDirectory.Management.ADPropertyValueCollection...
msDS-GenerationId               Property              System.Byte[] msDS-GenerationId {get;}
msDS-SupportedEncryptionTypes   Property              System.Int32 msDS-SupportedEncryptionTypes {get;set;}
Name                            Property              System.String Name {get;}
nTSecurityDescriptor            Property              System.DirectoryServices.ActiveDirectorySecurity nTSecurityDes...
ObjectCategory                  Property              System.String ObjectCategory {get;}
ObjectClass                     Property              System.String ObjectClass {get;set;}
ObjectGUID                      Property              System.Nullable`1[[System.Guid, mscorlib, Version=4.0.0.0, Cul...
objectSid                       Property              System.Security.Principal.SecurityIdentifier objectSid {get;}
operatingSystem                 Property              System.String operatingSystem {get;set;}
operatingSystemVersion          Property              System.String operatingSystemVersion {get;set;}
primaryGroupID                  Property              System.Int32 primaryGroupID {get;set;}
ProtectedFromAccidentalDeletion Property              System.Boolean ProtectedFromAccidentalDeletion {get;set;}
pwdLastSet                      Property              System.Int64 pwdLastSet {get;set;}
rIDSetReferences                Property              Microsoft.ActiveDirectory.Management.ADPropertyValueCollection...
sAMAccountName                  Property              System.String sAMAccountName {get;set;}
sAMAccountType                  Property              System.Int32 sAMAccountType {get;set;}
sDRightsEffective               Property              System.Int32 sDRightsEffective {get;}
serverReferenceBL               Property              Microsoft.ActiveDirectory.Management.ADPropertyValueCollection...
servicePrincipalName            Property              Microsoft.ActiveDirectory.Management.ADPropertyValueCollection...
userAccountControl              Property              System.Int32 userAccountControl {get;set;}
uSNChanged                      Property              System.Int64 uSNChanged {get;}
uSNCreated                      Property              System.Int64 uSNCreated {get;}
whenChanged                     Property              System.DateTime whenChanged {get;}
whenCreated                     Property              System.DateTime whenCreated {get;}

 

Tuesday, September 17, 2013

Reg Update to add Powershell to Plugable Protocol Handlers.


With the following registry additions, you can create a new URL protocol handler for PowerShell:

This allows me to do the following:
Start -> Run: ps:3+5
Start -> Run: ps:get-process
Start -> Run: ps:

A new powershell window opens, parses and executes the command and leave the window open.

Import the following to set it up:


Windows Registry Editor Version 5.00
[HKEY_LOCAL_MACHINE\SOFTWARE\Classes\PS]
@="
URL:Powershell Protocol"
"URL Protocol"=""

[HKEY_LOCAL_MACHINE\SOFTWARE\Classes\PS\DefaultIcon]
@="\"C:\\WINDOWS\\system32\\WindowsPowerShell\\v1.0\\powershell.exe\",1"

[HKEY_LOCAL_MACHINE\SOFTWARE\Classes\PS\shell]
[HKEY_LOCAL_MACHINE\SOFTWARE\Classes\PS\shell\open]
[HKEY_LOCAL_MACHINE\SOFTWARE\Classes\PS\shell\open\command]
@="\"C:\\WINDOWS\\system32\\WindowsPowerShell\\v1.0\\powershell.exe\" -NoLogo -NoExit -command $ExecutionContext.InvokeCommand.InvokeScript('%1'.Substring(3))"


Special thanks to  for the original post.

Monday, April 22, 2013

Exchange 2010 Mailbox Sizes, formated output

Here is the command to output a formatted table with the Mailbox size formatted to be human readable.
 
[PS] C:\Users\adminpds>get-mailboxstatistics -server ex-002 |Sort-Object TotalItemSize -Descending |Select-Object Displayname,  itemcount, TotalItemSize, database |ft Displayname,itemcount,@{n="Total Size (MB)";e={"{0:N0}" -f $_.TotalItemSize.Value.ToMB()};a="right"}, database
 

Sunday, April 14, 2013

Installing .NET Framework on Win2012

A "bug" in Windows 2012 is that the source files for .NET Framework are not installed with the default GUI install of Windows 2012.

A quick review of Get-WindowsFeature in Powershell will show that
[ ] .NET Framework 3.5 (NET-Framework-Core) has a status of "Removed".

Documentation on the net indicates that this will "install on demand" from the source media or from Windows Update.   Not true.  Even though this is on the Win2012 Certification Exam, it actually does not work.    

The command to get past this little "bug" is to run DISM.

The command then to install this feature is:
DISM /Online /Enable-Feature /FeatureName:NetFx3 /All /LimitAccess /Source:d:\sources\sxs

Your Welcome.

For reference, see http://msdn.microsoft.com/en-ca/library/hh506443.aspx 

Friday, February 22, 2013

Powershell - Query AD for Servers

The following Script stub will query AD for all active Windows 2008 Servers (can be tweaked) and create a collection of those servers.

# ######################################################################
# - Section for gathering Windows Server Information ...
# -- Define Global Variables --
  $strCategory = "computer"
  $strOS = "*2008*"
 
  # -- Get AD information --
  $objDomain = New-Object System.DirectoryServices.DirectoryEntry
 
  $objSearcher = New-Object System.DirectoryServices.DirectorySearcher
  $objSearcher.SearchRoot = $objDomain
  $objSearcher.Filter = "(&(objectCategory=$strCategory)(operatingSystem=$strOS)(name=*)(!(userAccountControl:1.2.840.113556.1.4.803:=2)))"
 
  # - define Attributes to find -
  $colProplist = "name"
  foreach ($i in $colPropList){$return=$objSearcher.PropertiesToLoad.Add($i)}
 
  # - Find all Computers that fit the Search profile
  $colResults = $objSearcher.FindAll()
 
  # -- Format the Output --
  # convert Collection into an array
  $servers = @()
  foreach ($objResult in $colResults)
  {
    $servers = $servers + $objResult.Properties.item("name") 
  }
  # Sort Server Names
  $servers = $servers | sort-object

Wednesday, February 20, 2013

Powershell - Tip of the Day

Here is a great site to browse for tips and to subscribe to their Tip-of-the-Day.

http://powershell.com/cs/blogs/tips/

Friday, May 27, 2011

Powershell Arrays

1) How do I create a dynamic array
$a = @()

2) How do I append an element to array
$a += "a"
$a += "b"

3) how do I do a UBOUND on an array
.NET array indexes are zero-based, so ubound is length-1:
$a.length - 1