Monday, March 16, 2009

get-qaduser

Get-QADUser -sizelimit 100 | select lastname,firstname,logonname,lastlogon | sort {$_.lastlogon.value.ticks} |  convertto-html > test.htm

Saturday, March 7, 2009

import-csv



function get-currentScriptDir{

$b = & { $myInvocation.ScriptName }
#$b


# Write-Host '2d output'
$c = split-path $b


# Write-Host  'this is ' `t $c

return  $c

}

$d = get-currentScriptDir

$e = $d+'\testfile.txt'

Write-Host ' this is ' $e


$file2Chk = $d+'\testfile.txt'
$header = "Name","Department","Title"

Import-Csv $file2Chk -Header $header | foreach{

Write-Host $_.Name

}






http://www.scriptinganswers.com/forum2/forum_posts.asp?TID=2636
import-csv c:\tools\subnets.csv | foreach {

$sitename = $_.sitename
$subnetIP = $_.SubnetIP
$loc = $_.Location
$siteLink = $_.SiteLink

...
$link.save()

}


# http://www.leadfollowmove.com/archives/powershell/excel-powershell-and-the-import-csv-cmdlet
# http://www.leadfollowmove.com/archives/powershell/creating-groups-in-active-directory-with-powershell



# Constants from: http://msdn2.microsoft.com/en-us/library/aa772263.aspx
Set-Variable -Name ADS_GROUP_TYPE_DOMAIN_LOCAL_GROUP  -value 4      -option constant
Set-Variable -Name ADS_GROUP_TYPE_GLOBAL_GROUP      -value 2       -option constant
Set-Variable -Name ADS_GROUP_TYPE_LOCAL_GROUP      -value 4      -option constant
Set-Variable -Name ADS_GROUP_TYPE_UNIVERSAL_GROUP    -value 8       -option constant
Set-Variable -Name ADS_GROUP_TYPE_SECURITY_ENABLED    -value -2147483648  -option constant
 
Set-Variable -Name ADS_GROUP_TYPE_SECURITY_DOMAIN_LOCAL  `
  -value ($ADS_GROUP_TYPE_DOMAIN_LOCAL_GROUP  `
  -bor $ADS_GROUP_TYPE_SECURITY_ENABLED)  -option constant
 
Set-Variable -Name ADS_GROUP_TYPE_SECURITY_DOMAIN_GLOBAL  `
  -value ($ADS_GROUP_TYPE_GLOBAL_GROUP  `
  -bor $ADS_GROUP_TYPE_SECURITY_ENABLED)  -option constant
 
Set-Variable -Name ADS_GROUP_TYPE_SECURITY_UNIVERSAL  `
  -value ($ADS_GROUP_TYPE_UNIVERSAL_GROUP    `
  -bor $ADS_GROUP_TYPE_SECURITY_ENABLED)  -option constant
 
# ---------------------------------------------------------------------------------------------------
  
  # Bind to the root of the domain
  $root  = [adsi]""
  $rootdn  = $root.distinguishedname
 
# ---------------------------------------------------------------------------------------------------
function create-group
# ---------------------------------------------------------------------------------------------------
{
Param (
  $Location,
  $Group,
  $scope,
  $Description
  )
  # The domain DN is added so the OU location doesn't need to be a full DN  
  # This also doesn't tie you down to a specific Domain.
  $ou = [adsi]("LDAP://"+$Location+","+$rootDN)
  $newGroup = $ou.create("group", "cn="+$Group)
  $newgroup.put("sAmAccountName", $Group)
  $newGroup.Put("Description", $Description)
  
  switch ($scope)
  {
    "Security Domain Local"      {$Type = $ADS_GROUP_TYPE_SECURITY_DOMAIN_LOCAL}
    "Security Domain Global"    {$Type = $ADS_GROUP_TYPE_SECURITY_DOMAIN_GLOBAL}
    "Security Universal"      {$Type = $ADS_GROUP_TYPE_SECURITY_UNIVERSAL}
    "Distribution Domain Local"    {$Type = $ADS_GROUP_TYPE_DOMAIN_LOCAL_GROUP}
    "Distribution Domain Global"  {$Type = $ADS_GROUP_TYPE_GLOBAL_GROUP}
    "Distribution Universal"    {$Type = $ADS_GROUP_TYPE_UNIVERSAL_GROUP}
  }
  $NewGroup.put("grouptype", $Type)
  $newGroup.SetInfo()
}
 
# ---------------------------------------------------------------------------------------------------
 
# Create-Group "ou=Test OU" "Test Group" "Security Domain Local" "My Test Group"


$data = import-csv d:\coding\ps\groups.csv
foreach ($line in $data)
{
  write-host $line.GrpName $line.Desc $line.GrpType $line.DN
}


GrpName,Desc,GrpType,DN
Test Group1,PowerShell Test Group,Security Domain Local,"cn=users"




# PowerShell script create users in a named OU
# Author: Guy Thomas 
# Version 2.4 August 2008 tested on PowerShell v 1.0

$OuBorn = 'OU=PowerShell,DC=cp2,DC=mosel'
$Freshmen = 'E:\powershell\QAD\bunch4.csv'
import-csv $Freshmen |`
where {new-QADUser -ParentContainer $OuBorn `
-name $_.name -sAMAccountName $_.sAMAccountName `
; enable-QADUser $_.name }


# The Complete script looks like this : http://mow001.blogspot.com/2006/05/powershell-import-shares-and-security.html

# ImportShares.ps1  
# This script will Import the Shares from a CSV file   
# made by ExportShares.ps1 complete with securityInfo  
#   
# /\/\o\/\/ 2006      
# http://mow001.blogspot.com   

# Import the CSV file 

$ShareList = Import-Csv ShareInfo.csv 

# get the Unique Shares 

$sharelist | select -unique name,Path,Description |% { 

  $name = $_.name 
  $path = $_.Path 
  $description = $_.Description 
  "Processing : $name $path $description" 

  $sd = new-object system.management.managementclass Win32_SecurityDescriptor 
  $sd.DACL = @() 
  $ace = new-object system.management.managementclass Win32_ace 
  $Trustee = new-object system.management.managementclass win32_trustee 

  # Get all records in CSV file for the current share 

  $sharelist |? {$_.name -eq $name} |% { 

    # Convert SID to Binary version : 

    $sid = new-object security.principal.securityidentifier($_.sid) 
    [byte[]]$ba = ,0 * $sid.BinaryLength 
    $sid.GetBinaryForm($ba,0) 

    # Make Trustee Object 

    $Trustee.Domain = $_.Domain 
    $Trustee.get_Properties()['name'].set_Value($_.domain) 
    $Trustee.SID = $ba 

    # Make ACE Object 

    $ace.AccessMask = $_.AccessMask 
    $ace.AceType = $_.AceType 
    $ace.AceFlags = $_.AceFlags 
    $ace.trustee = $trustee.psobject.baseobject 
  
    # Add ACE to the DACL 

    $sd.DACL += $ACE.psObject.baseobject 
  } 

  $MC = new-object system.management.ManagementClass win32_share 
  $InParams = $mc.GetMethodParameters('Create') 

  # fill Parameters 

  $InParams["Access"] = $sd.PsObject.BaseObject 
  $InParams["Description"] = $_.Description 
  $InParams["Name"] = $_.name 
  $InParams["Password"] = [string] 
  $InParams["Path"] = $_.Path 
  $InParams["Type"] = 0 

  $R = $mc.InvokeMethod('Create', $inParams, $Null) 
  "Result : $($R.ReturnValue)" 
  
}



# You can use array slicing, get the rows from row 13 till the end of the file: http://en.wikipedia.org/wiki/Array_slicing#2006:_Windows_PowerShell


PS > $csv = get-content report.csv
PS > $csv[12..$csv.length] | out-file report1.csv 
PS > import-csv report1.csv  

Friday, March 6, 2009

count ad objects

PS C:\test> get-qadobject -SizeLimit 0 | where {$_.type -eq "user" -or $_.type -eq "group" -or $_.type -eq "computer" -or $_.type -eq "organizationalunit"} | sort type| group type | format-table Name,Count -auto 

Name               Count 
----               ----- 
computer               7 
group                 48 
organizationalUnit     7 
user                  53 



How Many Objects?

Monday, February 23, 2009

sever audit




check powerpacks: Local System (Local System / Local Users and Groups) and Network
$administratorsAccount = Get-WmiObject Win32_Group -filter "LocalAccount=True AND SID='S-1-5-32-544'"


$administratorQuery = "GroupComponent = `"Win32_Group.Domain='" + $administratorsAccount.Domain + "',NAME='" + $administratorsAccount.Name + "'`""
$user = Get-WmiObject Win32_GroupUser -filter $administratorQuery | select PartComponent |where {$_ -match $userToFind}
$user


 ENUMERATING users\GROUPS IN A COMPUTER

local accts

List the Local Users on a Set of Computers

Submitted by: Robert Cott


List Members of the Local Administrators Group

Submitted by: Anonymous Submission


Add Users to the Local Administrators Group or other local group

Submitted by Jimmy Godard



sub localAccts(strComputer)
Dim objNetwork,  objComputer, objUser 
Set objNetwork = CreateObject("Wscript.Network") 
strComputer = objNetwork.ComputerName 
'Set objComputer = GetObject("WinNT://" & strComputer) 
objComputer.Filter = Array("user") 
For Each objUser In objComputer 
    Wscript.Echo objUser.Name & ", " & objUser.Description 
Next 

end Sub








function Get-ScriptPath{     Split-Path $myInvocation.ScriptName 
}
cls
$a = Get-ScriptPath
$a


$b = & { $myInvocation.ScriptName }


$b
split-path $b   


split-path info


# PowerShell's Split-Path can do this for you: 
# parent path: 
split-path c:\myproject\Csharpproject\memo.txt -Parent 
# same as above, w/o the -Parent switch: 
split-path c:\myproject\Csharpproject\memo.txt 
# file name: 
split-path c:\myproject\Csharpproject\memo.txt -Leaf 

# ...and more: 
split-path c:\myproject\Csharpproject\memo.txt -Qualifier 
split-path c:\myproject\Csharpproject\memo.txt -NoQualifier 
split-path c:\myproject\Csharpproject\memo.txt -IsAbsolute 


Get the Data You Need

Select-Properties: a helper for exporting DirectoryEntry objects

Microcode: PowerShell Scripting Tricks: Select-Object (Note Properties) vs Add-Member (Script Properties)











ServerAuditReports

Day 7: Manage Users

scheduledTasks

powershellPing

# This is the key part

$ping = new-object System.Net.NetworkInformation.Ping
$Reply = $ping.send($strComputer)
if ($Reply.status –eq “Success”) 
{
# do somethine if online
}
else 
{
# do somethine if NOT online
}
$Reply = ""

Get-QADComputer -sizeLimit 0 -osName *Server* | Where-Object { (Get-WmiObject Win32_PingStatus -Filter "Address='$($_.DNSHostName)'").StatusCode -eq 0 } | Foreach-Object { 
  # Do your other work here
}

function Ping-Address {

  PROCESS {

    $ping = $false

    $results = Get-WmiObject -query `

    "SELECT * FROM Win32_PingStatus WHERE Address = '$_'"

    foreach ($result in $results) {

      if ($results.StatusCode -eq 0) {

        $ping = $true

      }

     }

     if ($ping -eq $true) {

       Write-Output $_

     }

   }

 }

 

 function Restart-Computer {

   PROCESS {

     $computer = Get-WmiObject Win32_OperatingSystem -computer $_

     $computer.Reboot()

   }

 }









performing-networking-tasks-pinging-from-powershell

Wednesday, February 11, 2009

count events

function CountEvents{


BEGIN {

$errors = 0

$warnings = 0

$info = 0

}

PROCESS {

switch -wildcard ($_.entrytype) {

"err*" {$errors++}

"warn*" {$warnings++}

"info*" {$info++}

default {}

}#switch block

}#process block

END {

"The System log contains " + $errors + " error messages."

"The System log contains " + $warnings + " warning messages."

"The System log contains " + $info + " information messages."

}#end block

}#function block

#get-eventlog "System" -newest 100 CountEvents


======================= anothe approach ==============


$events = get-eventlog "System" -newest 100

function CountEvents{

$count = 0

foreach ($event in $args[0]) {

if ($event.entrytype -like $args[1]) {$count++}

}#foreach block

return $count

}#function block

$errors = CountEvents $events "err*"

$warnings = CountEvents $events "warn*"

$info = CountEvents $events "info*"

"The System log contains " + $errors + " error messages."

"The System log contains " + $warnings + " warning .messages."

"The System log contains " + $info + " information messages."

webcasts 2 watch

TechNet Webcast: Advanced Windows Powershell Scripting (Level 400)





Tuesday, February 10, 2009

Pinging a Server from a Server you are not logged in to

Pinging a Server from a Server you are not logged in to

So if you wanted server remote1 to ping server remote3 you could do something like this:


Get-WmiObject Win32_pingstatus –filter “Address =’remote3’” –computername remote1.| statuscode,address,_server

convert vbscript to powershell

Automating admin scenarios using PowerShell

Wednesday, February 4, 2009

PowerShell Scriptomatic V1.0

Another Pre-Memorial bonus for PowerShell fans is that Windows PowerShell Scriptomatic V1.0 now avaliable and you can download it Here

create AD accts & exchange 2003 mail boxes links

Enterprise Powershell: Creating Mailboxes in Exchange 2003

Find all mailboxes with quota limit is NOT set to default. & more

Creating new AD user accounts from a csv-file data has become even easier



Manage Exchange Server 2003 Using Windows PowerShell and WMI



More About Using PowerShell to Manage Exchange Server 2003


PowerShell Tutorial 12 - Part 1: Active Directory Management
WMI PowerShell for Exchange 2003

How to write a LDAP search filter

Searching Active Directory with Windows PowerShell

Objective 2 - QAD Script to Change Passwords




http://mow001.blogspot.com/2005/12/g...able-from.htmlhttp://mow001.blogspot.com/2006/03/w...-part-one.htmlgr /\/\o\/\/

Prof. PowerShell

date & time



READ MORE: Prof. PowerShell
Show What You Learned About PowerShell
Homework Assignment #1: Creating a formatted report of a selected scoped of peak paged memory.
by Jeffery Hicks
January 2009
Give Me Time
PowerShell's DateTime object will leave you with time on your hands to do other things.
by Jeffery Hicks
January 2009
Stringing Along
Use a PowerShell object's methods to do many of the same tasks for which you'd write VBscript code in long form.
by Jeffery Hicks
January 2009
Get-Unique -- Same But Different
I still prefer the Select-Object cmdlet, but Get-Unique has a way of weeding out the dupes that's, well, different.
by Jeffery Hicks
December 2008
Uniqueness Counts
PowerShell's Select-Object command has a -unique switch that lest you sort through the riffraff.
by Jeffery Hicks
December 2008
Command Performance
The Get-Command cmdlet reveals all that you need to know about PowerShell.
by Jeffery Hicks
December 2008
Reading Assignment
My secret for learning Powershell? Check out these blogs.
by Jeffery Hicks
November 2008
Just DO It!
Lesson in Logic #3: The secret to getting your script block to execute at least one time is the DO loop.
by Jeffery Hicks
November 2008
WHILE You Were Away...
Lesson in Logic #2: The WHILE statement keeps things rolling in your PowerShell scripts.
by Jeffery Hicks
November 2008
Lessons in Logic
Lesson 1: Using an IF



Do You Read Me?
Even sans GUI, Powershell can be made to work interactively. The trick is the Read-Host cmdlet.
by Jeffery Hicks
October 2008
PowerShell to XML
That nifty trick I showed you last time that exports data to CSV? This time, get more with an export to XML.
by Jeffery Hicks
October 2008

Sunday, January 25, 2009

rename computer

Expert PowerShell advice and commentary from Dr. Tobias Weltner.

Function
 Rename-ComputerName ([string]$NewComputerName){ 

 
$ComputerInfo = Get-WmiObject -Class Win32_ComputerSystem 
$ComputerInfo.rename($NewComputerName
 

This script shows you how to rename computer by using WMI

How to use it :

& .\rename-computerName.ps1

rename-computername "MyNewComputerNAME"

And to reboot you can use WMI class Win32_OperatingSystem and its method reboot():

$OS = Get-WmiObject -Class Win32_OperatingSystem

$OS.reboot()

OR

shutdown -r -t 10 -f -c "Restart OS"

Users of PowerShell V2 (currently CTP3) can use the Restart-Computer cmdlet too. :)

DETAILED DESCRIPTION

   The Restart-Computer cmdlet restarts the operating system on the local and remote computers.

   You can use the parameters of Restart-Computer to run the restart operations as a background job, to specify the authentication levels and alternate credentials, to limit the operations that run concurrently, and to force an immediate restart.

   This cmdlet does not require Windows PowerShell remoting unless you use the AsJob parameter.



Friday, January 23, 2009

Get-QADComputer Lastlogintime

=========

also switched lastLogonTimeStamp with pwdLastSet
Re: Get-QADComputer Lastlogintime
Posted: Dec 16, 2008 7:29 AM in response to: alex.stefishen@...
Answered
Reply

Sure. :-)

$limit = (get-date).AddDays(-30).ToFileTime()
$filter = "(&(objectcategory=computer)(|(lastLogonTimestamp<=$limit)(!(lastLogonTimestamp=*))))" $inactivecomputers = Get-QADComputer -ldapFilter $filter -ip lastlogontimestamp -SizeLimit 0 $inactivecomputers | ft name,@{l="LastLogonTimeStamp";e={if($_.lastLogonTimestamp -ne $null){[DateTime]::FromFileTime([Int64]::Parse($_.lastLogonTimestamp))}} } -autosize

Saturday, January 3, 2009

Get-QADComputer Lastlogintime

Get-QADComputer Lastlogintime                      

This code will give you the computers that have been inactive for 30 days:

$limit = (get-date).AddDays(-30).ToFileTime()
$filter = "(&(objectcategory=computer)(|(lastLogonTimestamp<=$limit)(!(lastLogonTimestamp=*))))" $inactivecomputers = Get-QADComputer -ldapFilter $filter -SizeLimit 0


It's faster than piping to where-object.


show the time stamp?



$limit = (get-date).AddDays(-30).ToFileTime()
$filter = "(&(objectcategory=computer)(|(lastLogonTimestamp<=$limit)(!(lastLogonTimestamp=*))))"

$inactivecomputers = Get-QADComputer -ldapFilter $filter -ip lastlogontimestamp -SizeLimit 0

$inactivecomputers | ft name,@{l="LastLogonTimeStamp";e={if($_.lastLogonTimestamp -ne $null){[DateTime]::FromFileTime([Int64]::Parse($_.lastLogonTimestamp))}} } -autosize


managing AD

Manage my AD OU with powergui