Wednesday, November 27, 2013

more commands and scripts


getting remote command line\process path
wmic /node:10.1.2.3 PROCESS get Caption,Commandline,Processid

IIS Logs (from friend)

Purpose:                              Removes IIS log files older than 30 days and sets the compress switch on all files older than 3 days. This is to save space on the log drive and
                automatically manage IIS log file retention on Exchange CAS servers.

#>
# Variables
$dateNow = (Get-Date).ToString("HHmm_ddMMyyyy")
$deleteDate = (Get-Date).addDays(-30)
$CompressDate = (Get-Date).addDays(-3)


#MAIN SCRIPT
# Cleanup IIS files older than 30days old
Get-ChildItem D:\IIS_Logs -Recurse | where {$_.CreationTime -le $deleteDate -and $_.Attributes -notlike "*Directory*"} | Remove-Item -force
# Compress IIS files created more than 3days ago (omit Directories)
$IISFiles = Get-ChildItem D:\IIS_Logs -Recurse | where {$_.CreationTime -le $CompressDate -and $_.Attributes -notlike "*Compress*" -and $_.Attributes -notlike "*Directory*"} | Select *
foreach($file in $IISFiles){
Invoke-WmiMethod -Path "CIM_DataFile.Name='$($File.FullName)'" -Name compress -Confirm:$false

}

Monday, November 4, 2013

powershell filtering two arrays and using text and variables

Comparing two list/Array/ and work from that...
#
# Active FPS list
#

$OUName= 'OU=File and Print,OU=Servers,OU=MOE Servers,DC=Kool,DC=Kids'
$TheComputers = Get-ADComputer -filter * -searchbase $OUName

#
# Exclude File and Print Server
# ,,
#
$ExcludedFPs="PANDA"
Write-host Excluded File and Print Server - $ExcludedFPs

#Filter the List of objects
$AcutalFPStargets=Compare-Object $TheComputers.name $ExcludedFPs | where {$_.sideindicator -eq "<="} | % {$_.inputobject}

#now... do stuff 
foreach ($server in $AcutalFPStargets){
Variables in text.. so I can remember sometimes need brackets othertimes not... @#$@#
if(!($user.homedirectory -like '*'+($server).name+'*'))

$path = "\\"+$server.Name+"\users"

Tuesday, October 8, 2013

Quick Audit of Active Directory OUs Users


$splat=$null
$Splat = @()
$95days = (get-date).adddays(-95)
$AlltheOus=Get-ADOrganizationalUnit -filter * -SearchBase "OU=Humans,DC=coolkids,DC=local" -Properties CanonicalName
foreach($OU in $AlltheOus) {
  $objectCount=(Get-adobject -Filter * -SearchBase $ou.distinguishedname -searchscope Onelevel|Measure-Object).count
  $u=Get-ADUser -filter * -searchbase $ou.distinguishedname -Properties passwordneverexpires,passwordlastset -searchscope Onelevel
  $total=($u | measure-object).count
  $Enabled=($u | where {$_.Enabled} | Measure-Object).count
  $Disabled=$total-$Enabled
  $nonExpirePassword=($u | where {$_.passwordneverexpires} | Measure-Object).count
  $passwordolder90=($u | where {$_.passwordlastset -lt $95days} | Measure-Object).Count
 $Splat +=  New-Object psobject -Property @{
    Name=$ou.CanonicalName;
    TotalObjects=$objectCount;
    TotalUsers=$Total;
    Enabled=$Enabled;
    Disabled=$Disabled;
    PasswordNonExpire=$nonExpirePassword;
    Password90days=$passwordolder90;
    OU=$OU.Distinguishedname
    }
}

$splat | Select-Object Name,TotalObjects,TotalUsers,Enabled,Disabled,PasswordNonExpire,Password90days,OU | Sort-Object name| export-csv C:\temp\QuickOUAudit.csv -NoTypeInformation -force

Friday, September 27, 2013

Reporting Citrix user session into SQL - Alternative to edgesight

Updated 27/09/2013
Since we moved to  XenAPP 6.5 we noticed that was unable to get handy reports about usage what application users were loading. Not a bit fan of edgesight ! :(

After many months we have arrived at this solution, every 15mins a powershell script will query the XenApp farm and write the content up to SQL DB.

Assume you will know how to create table\permissions in the SQL database.
Pretty lean on my SQL leave it up to you to workout.
Created a database 'xenuserinfo' manually and then made sure it was selected when executing the SQL scripts

SQL Script:

/* To prevent any potential data loss issues, you should review this script in detail before running it outside the context of the database designer.*/
BEGIN TRANSACTION
SET QUOTED_IDENTIFIER ON
SET ARITHABORT ON
SET NUMERIC_ROUNDABORT OFF
SET CONCAT_NULL_YIELDS_NULL ON
SET ANSI_NULLS ON
SET ANSI_PADDING ON
SET ANSI_WARNINGS ON
COMMIT
BEGIN TRANSACTION
GO
CREATE TABLE dbo.XData
 (
 UsageDate datetime NULL,
 AccountName nvarchar(50) NULL,
 Application nvarchar(50) NULL,
 FarmName nvarchar(10) NULL
 )  ON [PRIMARY]
GO
ALTER TABLE dbo.XData SET (LOCK_ESCALATION = TABLE)
GO


CREATE TABLE dbo.XCount
 (
 UsageDate datetime NULL,
 SessionCount smallint NULL,
 FarmName nvarchar(10) NULL
 )  ON [PRIMARY]
GO
ALTER TABLE dbo.XCount SET (LOCK_ESCALATION = TABLE)

GO

COMMIT

Then I used the console to add permissions etc.

Now the powershell script that will run every 15mins, notice there are 2 entries to save me time when making graphs. At the 15 minute mark it looks backwards to see if there are any logons, if so then upload to database. Doubt it would get secondary launches (ie loading another app off same server).

Performing the session count as we are working in shared license environment = trust no-one!.

 Don't forget to install the SDK

#Add-PSSnapin citrix.xenapp.commands
#CPS Version
$time2 = Get-Date -Format "MMM dd yyyy HH:mm"
$time1 = Get-Date
$tminus15 = $time1.addminutes(-15)

# Check logons in the last 15 minutes
$allSessions = Get-XASession  | where-object -filterscript { ($_.state -eq 'Active') -or ($_.state -eq 'Disconnected') -and ($_.LogOnTime -gt $tminus15)} 
$FarmInfo=Get-xafarm 
$FarmName=$Farminfo.FarmName

 ## Hello SQL
$dbconn = New-Object System.Data.SqlClient.SqlConnection("Data Source=TheSQLServer; Initial Catalog=XenUserInfo; Integrated Security=SSPI")
$dbconn.Open()

 
 ## Write User App info to SQL
$allSessions | foreach {
$ACC=$_.accountname
$APP=$_.browsername
$LOT=$_.LogonTime.ToString("MMM dd yyyy HH:mm")
$CLN=$_.ClientName
$dbwrite = $dbconn.CreateCommand()
$dbwrite.CommandText = "INSERT INTO dbo.XLCPLData (UsageDate,AccountName,Application,FarmName,LogonTime,ClientName) VALUES ('$time2','$ACC','$APP','$Farmname','$LOT','$CLN')"
$dbwrite.ExecuteNonQuery()
$ACC=$null
$APP=$Null
$LOT=$Null
$CLN=$null
} 

 ## Write Session Count to SQL 
$dacount=$FarmInfo.SessionCount
$dbwrite1 = $dbconn.CreateCommand()
$dbwrite1.CommandText = "INSERT INTO dbo.XLCPLCount (UsageDate,SessionCount,FarmName) VALUES ('$time2', '$dacount','$Farmname')"
$dbwrite1.ExecuteNonQuery()

 ## Finished with SQL --- GoodBye
$dbconn.Close()
$allSession=$null

now off to create pretty graphs in excel

Update -

or.
Muck around with data in powershell ie generate csv etc.

## Hello SQL Grab my data from the last 30days
    $query = "select * FROM dbo.XLCPLData where LogonTime > GETDATE()-30 and Application != ''"
    $connection = New-Object System.Data.SqlClient.SqlConnection("Data Source=LCLABXENWIDS; Initial Catalog=XenUserInfo; Integrated Security=SSPI")
    $adapter = new-object system.data.sqlclient.sqldataadapter ($query, $connection)
    $table = new-object system.data.datatable
    $adapter.Fill($table) | out-null
    $applist=$table | sort-object Application -Unique | select -Property application
    
## Go generate pretty graphs or whatever.
## Use $table to see the list connections
## Use $applist to see the list of unique apps
##    Then you can use a foreach loop to generate content or csv.

Monday, September 9, 2013

Update DNS Server setting on Multiple Servers with powershell

Had to update the DNS server settings on a few servers (80+).
Because I had a mix 23/28/28r2/12 servers decided wmi was the path forward + powershell.
  • issues with when doing contains, until I performed a convert to string [String]


  • Stumped by the String setting for a little while was trying .tostring()

  • Script in 3 parts:
    1. check all the servers to see if hard code to old DC
    2. Update the DHCP server options on all authorised DHCP servers
    3. Purge any scope with setting for old DC to use the server option

    Btw: some servers dont reply correctly to WMI so... prepared to check manually (and maybe fix wmi)

    #StartHere :)
    $OUName= 'OU=Servers,DC=KoolKids'
    $TheComputers = Get-ADComputer -filter * -searchbase $OUName
    $results = @()
    
    Foreach ($server in $TheComputers) {
    if(Test-Connection $server.name -Count 1 -quiet){
                $NICs = Get-WMIObject Win32_NetworkAdapterConfiguration -computername $server.name| where{$_.IPEnabled -eq “TRUE”} 
                    Foreach($NIC in $NICs) {
                    $FTW=$NIC.DNSServerSearchOrder
                    $FTW =[String]$FTW
                   # write-host $FTW
                    If ($FTW.contains("10.10.3.1")) {
                                           $results += New-Object PSObject -Property @{
                                           Server = $server.name
                                           DNS = $FTW
                                              }
                                #update the DNS Server for this NIC
                                $DNSServers = "172.18.0.10","172.18.0.11"
                                $NIC.SetDNSServerSearchOrder($DNSServers)
                        }
                    }
            }
        }
    #set the default server scope options to correct setting
     foreach ($dhcpserver in Get-DhcpServerInDC){
     if(Test-Connection $dhcpserver.DNSName  -Count 1 -Quiet){
                #Remarked out so that all active DHCP servers get updated!
                #If ($FTW.contains("10.10.3.1")) { 
                 $FixScope=[System.Net.Dns]::GetHostAddresses($dhcpserver.DNSName).IPAddressToString, "172.18.0.10", "172.18.0.11"
                 Set-DhcpServerv4OptionValue -ComputerName $dhcpserver.DNSName -OptionId 6 -Value $FixScope
                #}
            }
     }
    
     #clear out the scope options
     # WARNING SERVER OPTIONS MUST HAVE a SETTING OR BAD THINGS HAPPEN
      foreach ($dhcpserver in Get-DhcpServerInDC){
                 foreach ($TheScope in (Get-dhcpserverv4scope -computername $dhcpserver.DnsName)){
                         $target=$null
                         $Target=Get-DhcpServerv4OptionValue -ComputerName $dhcpserver.DNSName -OptionId 6 -ScopeId $TheScope.ScopeId -ErrorAction SilentlyContinue
                         $Target=[String]$target.Value
                          If ($Target.contains("10.10.3.1")) {
                          Remove-DhcpServerv4OptionValue -ComputerName $dhcpserver.DNSName -OptionId 6 -ScopeId $TheScope.ScopeId 
                          }
            }
     }
    
    

    Powershell Strings


    $a = "This", "Is", "a", "cat"

    # Operator join

    # This Is a cat
    $a -join ' '

    # ThisIsacat
    -join $a

    # using conversion to [string] (and optionally use the separator $ofs)

    # This Is a cat
    [string]$a

    # This-Is-a-cat
    $ofs = '-' # ! after that all casts work in this way until $ofs changes !
    [string]$a

    Wednesday, August 28, 2013

    Powershell Add Users CSV to AD Group

    Hi,

    Need import a list of users into a group.
    Add-groupmember normally has a break down if the user already exists.
    so added some checks and balances before adding them.
    user account that are written to screen dont exist in AD

    #Grab the Users
    $lolz = Import-Csv .\users0813.csv
    #locate the Group
    $group = get-adgroup remoteaccess
    #get existing members
    $groupmembers = Get-ADGroupMember $group
    
    #go Silent so that can peform the get-aduser without erros
    $ErrorActionPreference="SilentlyContinue"
    foreach ($user in $lolz) {
    
    #check if user exist in AD
    $target=get-aduser $user.'default login'
    if (!$target){
    # display missing ppls
      Write-Host $user.'default login'
      } Else {
        # check if already a member of the group
        If(!($groupmembers.samaccountname -contains $user.'default login')){
        #add to group
        Add-ADGroupMember $group -Members $user.'default login'
        }
      }
      #set back to null for next persome
      $target=$null
    }
    $ErrorActionPreference="Continue"
    
    

    Thursday, June 27, 2013

    windows eventlogs filtering

    using eventlog forwarding\subscriptions to pass event to central monitoring server
    which then is indexed by splunk.
    (this saves having to put out universal forwarders or other things on our Domain Controllers)

    so AD is tracking changes with eventlogs 5136
    it also tracks changes like dnsnode updates etc.
    as we only want the user object changes (at the moment)
    and exclude certain eventdata

    Using a custom view to pull the 5136 events from remove domain controllers

     <querylist>
     <query Id="0" Path="Security">
       <select Path="Security">
              *[System[(EventID=5136)]] and *[EventData[Data[@Name='ObjectClass'] and (Data='user')]]
         </Select>
          <suppress Path="Security">
           *[EventData[Data[@Name='AttributeLDAPDisplayName'] and (Data='userCertificate')]]
         </Suppress>
      </Query>
    </QueryList>
    

    was getting locale errors with eventlogs so had to set system language to english(united states)


    good link for info about Auditing AD:
    http://blogs.technet.com/b/askpfeplat/archive/2012/04/22/who-moved-the-ad-cheese.aspx

    Monday, June 17, 2013

    Added prettyify to my blog


    Using the code from here https://code.google.com/p/google-code-prettify/
    Followed the guide http://www.simplebloggertutorials.com/2013/03/add-syntax-highlighter-blogger.html

    :)

    Add\Import multiple CSV to excel




    # Now get a list of all csv files in current directory :)
    $targetcsv=dir *.csv
    
    #Create a new Excel object and add a new workbook. 
    $Excel = New-Object -ComObject excel.application 
    $Excel.visible = $true
    $workbooks = $excel.Workbooks.Add()
    $worksheets = $workbooks.worksheets
    #Delete the extra worksheets and rename the first worksheet.
    $worksheets.Item(3).delete()
    $worksheets.Item(2).delete()
    #Add worksheets based on the count of files
    $count=1
    
    foreach ( $CSVFile in $targetcsv ){
            IF ($count -ne 1){ $worksheets.Add()}
            #Write-Host $CSVFile.BaseName
            #Select worksheet 
            $worksheet = $worksheets.Item(1)
            #Give it a updated name
            $worksheet.Name = $CSVFile.BaseName
     
            #Grab the CSV
            $TxtConnector = ("TEXT;" + $CSVfile.fullname)
            $CellRef = $worksheet.Range("A1")
     
            #Import the text file
            $Connector = $worksheet.QueryTables.add($TxtConnector,$CellRef)
            $worksheet.QueryTables.item($Connector.name).TextFileCommaDelimiter = $True
            $worksheet.QueryTables.item($Connector.name).TextFileParseType  = 1
            $worksheet.QueryTables.item($Connector.name).Refresh()
            $worksheet.QueryTables.item($Connector.name).delete()
            
            #make pretty
            $worksheet.UsedRange.EntireColumn.AutoFit()
            #loop for fun!
            $count=$count+1        
            write-host $count
    
            }
    
    

    Wednesday, May 22, 2013

    Windows 2012 data dedupe antivirus exclusions

    Since I couldn't find any on the interwebs, some monitoring lead to.

    Process - fsdmhost.exe
    Folder - <drive>\System Volume Information\Dedup\*

    /NM

    Tuesday, May 21, 2013

    Backup Folder Security to CSV with Powershell


    thanks to whoever I stole the rescurse depth limit from :)

    # Get the folder security and save it to csv
    # -------------------------
    $Date= get-date -Format yyyyMMdd
    #Group path already includes two '\' so add 2 to folder level required
    $Depth=3
    # Obtain the files
    $Rfolders=Get-ChildItem E:\group -recurse -Attributes Directory | % {$_.FullName.ToString()} | foreach {$var=$_;$count=(0..($_.length - 1) | where {$var[$_] -eq "\"}).count;if($count -le $Depth) {$_}}
    # Obtain the folder security information and log to file
    $LogFile = 'E:\group\GroupSecurityBackup_'+$date+ '.log'
    $Rfolders | Get-Acl | Export-Csv $LogFile -Force

    # Restoring individual folder
    #--------------------------
    # 1st- Import Acl back
     $ResFolder = import-csv E:\group\GroupSecurityBackup_<date>.log
    #
    # 2nd- Check acl for a specific folder
    $Resfolder |Get-Acl | where {$_.path -like "*E:\group\test1\test2"}
    #
    # 3rd- To restore acl for a specific folder (this example we are exporting to another folder)
    $acl = get-acl E:\group\testme
    $acl.SetSecurityDescriptorSddlForm(($Resfolder |Get-Acl | where {$_.path -like "*E:\group\test1\test2"}).sddl)
    set-acl E:\group\testme $acl

    # Restoring Complete Tree Rebuld and ReSecure
    # ---------------------------
    $ResFolder = import-csv E:\group\GroupSecurityBackup_<date>.log
     foreach ($folder in $ResFolder) {
       write-host $folder.Path
       mkdir $folder.Path
       $acl = get-acl $folder.Path
       $acl.SetSecurityDescriptorSddlForm($folder.Sddl)
       set-acl $folder.Path $acl
       } 

    Monday, May 6, 2013

    powershell test file date time

    $testfile="d:\temp\testflie_"+(Get-Date -Format yyyyMMdd-HHmm).ToString()+".log"

    result
    d:\temp\testflie_20130506-1735.log

    Tuesday, April 23, 2013

    How to Create Custom Active Directory LDAP Searches


    Cool stuff from
    http://blogs.msdn.com/b/muaddib/archive/2011/10/24/active-directory-ldap-searches.aspx

    Also see the post below on creating queries for individual UserAccountControl flags.
    How to use the UserAccountControl flags to manipulate user account properties
    http://support.microsoft.com/kb/305144 
    Now on to the queries.
     All XP ComputersAlthough this can be done easy enough with the GUI, I wanted to show the syntax so it can be used as a building block for more complex theories.  One thing to notice is the query parameter "objectCategory=computer".  By including this as part of our query we reduce the number of objects that have to be searched making for a faster query and less performance impact on the DC performing the query.
    (&(objectCategory=computer)(operatingSystem=Windows XP*))
    Windows XP Computers with Service Pack 2 Installed(&(objectCategory=computer)(operatingSystem=Windows XP Professional)(operatingSystemServicePack=Service Pack 2))
    Windows XP Computers with Service Pack 1 Installed
    (&(operatingSystem=Windows XP*l)(operatingSystemServicePack=Service Pack 1)))
    Windows XP Computers with No Service Pack Installed
    This one is structured a Little different.  Notice the "!" before operating SystemServicePack and the "*".  The "!" means NOT so the statement reads "NOT equal to anything" instead of NULL or empty quotes ("") like some other languages.
    (&(operatingSystem=Windows XP Professional)(!operatingSystemServicePack=*))) 
    Windows Server 2003 No Service Pack 1(&((objectCategory=computer))(operatingSystem=Windows Server 2003)(!operatingSystemServicePack=*)))
    Windows Server 2003 Service Pack 1 Installed (&(objectCategory=computer)(operatingSystem=Windows Server 2003)(operatingSystemServicePack=Service Pack 1)) 
    Windows 2000 Professional (&(objectCategory=computer)(operatingSystem=Windows 2000 Professional))
    Windows 2000 Server (&(objectCategory=computer)(operatingSystem=Windows 2000 Server))
    All Windows Server 2003 Servers
    (&((objectCategory=computer))(operatingSystem=Windows Server 2003))
    SQL Servers (running on Windows 2003) (please verify in your environment)
    (&(objectCategory=computer)(servicePrincipalName=MSSQLSvc*)(operatingSystem=Windows Server 2003))
    SQL Servers any Windows Server OS(&(objectCategory=computer)(servicePrincipalName=MSSQLSvc*)(operatingSystem=Windows Server*))
    Windows Vista SP1(&(objectCategory=computer)(operatingSystem=Windows Vista*)(operatingSystemServicePack=Service Pack 1))
    Windows Server 2008 Enterprise(&(objectCategory=computer)(operatingSystem=Windows Server® 2008 Enterprise)(operatingSystemServicePack=Service Pack 1))
    Windows Server 2008 (all versions)
    (&(objectCategory=computer)(operatingSystem=Windows Server® 2008*))
    Windows Server 2008 R2 Enterprise
    (&(objectCategory=computer)(operatingSystem=Windows Server 2008 R2 Enterprise))
    Sample User Attribute Query (ExtensionAtrribute5)
    (&(objectCategory=user)(&(extensionAttribute5>=20080101)(extensionAttribute5<=20080520)))
    WIndows Server 2008 ALL
    (&(objectCategory=computer)(operatingSystem=Windows Server 2008*))
    Windows Server 2008 RTM
    (&(objectCategory=computer)(operatingSystem=Windows Server 2008 *)(!operatingSystemServicePack=*))
    Windows Server 2008 SP1
    (&(objectCategory=computer)(operatingSystem=Windows Server 2008*)(operatingSystemServicePack=Service Pack 1))
    Windows 7 RTM(&(objectCategory=computer)(operatingSystem=Windows 7*)(!operatingSystemServicePack=Service Pack 1))
    Windows 7 SP1(&(objectCategory=computer)(operatingSystem=Windows 7*)(operatingSystemServicePack=Service Pack 1))

    Monday, April 22, 2013

    Troubleshooting Server unable to look up internal FDQN "result too large", unable to RDP to server, but can browse and read eventlogs



     nslookup internaldomain.local
     Troubleshooting Server unable to look up internal FDQN "result too large", unable to RDP to server, but can browse and read eventlogs

    Quick answer: port exhaustion, kb out there to fix this stuff.

    nslookup
     internalserver.internaldomain.local can't find internaldomain.local: unspecified error


    1. clear dns servers
    2. added dns servers in Core Data centre
    3. tried different dns servers in nslookup
    3a. tried local dns server
    4. modified host file with internal.local to server

    fail

    Check firewall (disable)
    netsh advfirewall set allprofiles state off
    result:
    ok

    Check Group Policy
    Gpupdate /force
    result:
    Updating Policy...User Policy update has completed successfully.Computer policy could not be updated successfully. The following errors were encountered:The processing of Group Policy failed. Windows could not resolve the computer name. This could be caused by one of more of the following: a) Name Resolution failure on the current domain controller. b) Active Directory Replication Latency (an account created on another domain controller has not replicated to the current domain controller).
    To diagnose the failure, review the event log or run GPRESULT /H GPReport.html from the command line to access information about Group Policy results.

    check time
    w32tm /query /peers

    more nslookup
    set debug
    internaldomain.local
    result
    -------------
    truncated answer
    connect failed: result too large
    -------------

    check server's services
    net stop dnscache
    net start dnscache

    net stop workstation
    net start netlogon

    Check Ports!
    netstat -a -n
    problem located - port exhaustion !!! 10000's of time_wait

    ----Hotfix Time---- (with bonus hotfix)
    Windows6.1-KB2553549-v3-x64
    Windows6.1-KB2264080-x64

    there is a better rollup available(windows6.1-kb2775511-x64) but my server is not SP1. 

    enjoy.

    Thursday, April 18, 2013

    Change CD DVD drive letter RAGE - task sequence



    FOR /F "tokens=1 delims=:" %%A IN ('WMIC logicaldisk get drivetype^,deviceID^| FIND "5"') DO (
    echo select volume %%A >%temp%\movecdrom.txt
    echo assign letter z noerr >>%temp%\movecdrom.txt
    diskpart /s %temp%\movecdrom.txt
    )

    uses wmic to locate which drive letter is actually the cdrom\dvd then moves it to Z drive.

    Wednesday, March 27, 2013

    Microsoft Anti-Virus Exclusion List

    http://social.technet.microsoft.com/wiki/contents/articles/953.microsoft-anti-virus-exclusion-list.aspx

    Monday, March 18, 2013

    Build Import of DHCP Reservations - Powershell


    Just followed ‘example 2’  - in the powershell command example  http://technet.microsoft.com/en-us/library/jj590686.aspx

    Eg
    Scopeid,IPAddress,Name,Clientid,Description
    10.192.66.0,10.192.66.101,xx_L1_AP01,50-57-AC-9e-b1-26,SW - Gi1/0/47
    10.192.66.1,10.192.66.102,xx_L1_AP02,d8-67-AC-95-5a-35,SW - Gi2/0/47
    10.192.66.2,10.192.66.115,xx_L3_AP01,d4-8c-AC-04-72-e9,SW - Gi7/39
    10.192.66.3,10.192.66.116,xx_L3_AP02,d4-8c-AC-2f-2b-ea,SW - Gi7/40

    PS C:\> Import-Csv Path Reservations.csv | Add-DhcpServerv4Reservation -ComputerName koolkids.lc.local

    pretty cool.
    J

    Thursday, February 14, 2013

    Powershell and DNS

    Was trying to search for static address in a large subnet that I was working on.

    start off with reading - http://gallery.technet.microsoft.com/scriptcenter/DNS-Server-PowerShell-afc2142b

    retrieve the records with
    $records = Get-DnsServerResourceRecord -ZoneName koolkids.internal -computer kcdc

    tried
    $records| ? recorddata -like "10.10.*"

    got nothing returned... :(

    then check the types:
    $records | get-member
    DistinguishedName         Property   string DistinguishedName {get;}
    HostName                  Property   string HostName {get;}
    PSComputerName            Property   string PSComputerName {get;}
    RecordClass               Property   string RecordClass {get;}
    RecordData                Property   CimInstance#Instance RecordData {get;set;}
    RecordType                Property   string RecordType {get;}
    Timestamp                 Property   CimInstance#DateTime Timestamp {get;}
    TimeToLive                Property   CimInstance#DateTime TimeToLive {get;set;}

    notice that is was CimInstance#Instance for the RecordData
    can't remember how to convert it to string on the fly.
    so my colleague suggested 
    $records | out-gridview

    then do the filtering from there, which work nice.

    if after a few coffees I remember how to sort this out. I will update.