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

Wednesday, October 21, 2015

Update Outlook Store Display Name - with powershell

# Outlook Store Display Name
# http://blogs.msdn.com/b/emeamsgdev/archive/2012/10/29/outlook-code-change-the-name-of-the-root-folder-in-outlook-2010-after-an-smtp-address-change.aspx

$outlook = New-Object -ComObject 'Outlook.Application'
$stores = $Outlook.GetNamespace("MAPI").Session.stores

Foreach ($Store in $stores){
If ($store.ExchangeStoreType -eq "0") {
       
        $updatestore=$store.GetRootFolder()
        $updatestore.Name="Work-Email"       
        }
}

Thursday, October 15, 2015

Powershell | Event Log Message content

Security Event Log Taken from 2003 Domain Controller
fixed with http://www.cwflynt.com/logFixer/
Filtered with Eventvwr on Windows 10 saved as evtx

Loaded into powershell and filtered on the message content.


#
# Eventlog filtering
#
$logdetail=Get-WinEvent -path .\filteredchanges.evtx
$results=@()

Foreach($event in $logdetail){
        $mess=$event.message -split "`n"
        $a=$Mess| select-string "Target Account Name"
        $a=$a.ToString().split(":")[1]
        $b=$mess | select-string "Don't Expire Password"
        $c=$mess | select-string "Logon Hours"
        $c=$c.ToString().split(":")[1]
        $d=$mess | select-string "Caller User Name"
        $d=$d.ToString().split(":")[1]

                        $tempObJ = "" | Select Name,Expired,Logon,Changetime,userid
                        $tempObJ.Name = $a
                        $tempObJ.ChangeTime = $event.TimeCreated
                        $tempObJ.Expired = $b
                        $tempObJ.Logon = $c
                        $tempObJ.userid = $d
                        $results+=$tempObJ
}

Friday, August 7, 2015

XenApp 6.5 published Windows Explorer using powershell

based on http://support.citrix.com/article/CTX131423

Using a Batch launcher for flexibility to run a powershell script instead of autoit.

[ExplorerLauncher.cmd]
@echo off
%SystemRoot%\system32\WindowsPowerShell\v1.0\powershell.exe -executionPolicy bypass -file "C:\Program Files\AppScripts\ExplorerLauncher.ps1"
exit

[explorerlauncher.ps1]

#$Process = [Diagnostics.Process]::Start("notepad")
$process = Start-Process notepad -WindowStyle Minimized -PassThru
$id = $Process.Id
Write-Host "Pre-Launch Process created. Process id is $id"
Write-Host "sleeping for 2 seconds"
Start-Sleep -Seconds 2
Write-Host "Loading explorer"
Start-Process "Explorer" -ArgumentList "Z:\"
Write-Host "sleeping for 2 seconds"
try {
Stop-Process -Id $id -ErrorAction stop
Write-Host "Successfully killed the process with ID: $ID"
} catch {
Write-Host "Failed to kill the process"
}
Start-Sleep -Seconds 2
Write-host "Exiting Launch completed"
exit

Friday, May 15, 2015

LSPCI using WMI ( WMIC )


From Command Prompt:
Wmic path win32_pnpentity where "deviceid like '%PCI%'" get name,deviceid

with powershell:
gwmi win32_pnpentity | where{$_.deviceid -match "PCI"} | select name,deviceid

Tuesday, May 12, 2015

POWERSHELL | Comparing File ACL



#Generate the Base line acl

$TheACL=Get-Acl \\$server\$testpath\LCFSTEST\test.txt
$TheACL|Export-Clixml $logfolder\'base_'$testpath.xml

#ACTION - Modify permissions

$TheACL=Get-Acl \\$server\$testpath\LCFSTEST\test.txt

#Import the BASE ACL

$BaseACL=Import-Clixml $logfolder\'base_'$testpath.xml
If (diff $($TheACL.Access) $($BaseACL.Access) -Property Filesystemrights) { Write-Host Different Check $testpath Permissions}

Thursday, April 16, 2015

Active Directory ProxyAddress Email Addresses SMTP Extract with powershell

Bit of fun with extracting SMTP secondary addresses from user account.

$user=get-aduser testuser -prop,proxyAddresses

$user|select samaccountname,@{Name=”AdditionalAddresses”;Expression={($_.proxyAddresses| Foreach-object {$_.split([environment]::NewLine)} | Where-Object {$_ -match “smtp”} | ForEach-Object {$_.substring(5)}) -join "|"}}


so..

#
#Export Detailed AD Membership info
#dump a full member list text file only once per day
#

$outputfile = $savepath + "\" + $dayofweek + "_theuserlist.xlsx"
del $outputfile
$allpandas = get-aduser -filter {extensionattribute5 -eq "Pandas"}  -Properties displayname,title,company,department,lastlogondate,physicalDeliveryOfficeName,proxyAddresses,EmailAddress
$allpandas = $allpandas|select samaccountname,givenname,surname,displayname,title,company,department,UserPrincipalName,physicalDeliveryOfficeName,lastlogondate,EmailAddress,@{Name=”AdditionalAddresses”;Expression={($_.proxyAddresses| Foreach-object {$_.split([environment]::NewLine)} | Where-Object {$_ -match “smtp”} | ForEach-Object {$_.substring(5)}) -join "|"}}
$allpandas | C:\scripts\Export-XLSX.ps1 -Path $outputfile -WorkSheetName 'pandas'

Friday, March 20, 2015

Audt Drive Mappings - Group Policy Objects with Powershell

We have bunch of GPOs that perform drive mappings
Unfortunately another team normal does the site work.

so after a little while with servers moving all over the place servers disappear but GPO still had mappings and groups . RAGE

so a bit of powershell to check all the paths

diving into the get-gpo was interesting.

got stumped on test-path when access is denied for a little while until worked out the errorvariable was the way around it.

http://pastebin.com/VvgZpWnA

Friday, March 13, 2015

powershell html table color

Came across some code to change arrays into some nice html code.
has the ability to colour code cells.

#
# $finalrepinfo is array
#
$html = $finalRepInfo|ConvertTo-Html -Fragment
 
$xml = [xml]$html

$attr = $xml.CreateAttribute("id")
$attr.Value='diskTbl'
$xml.table.Attributes.Append($attr)


$rows=$xml.table.selectNodes('//tr')
for($i=1;$i -lt $rows.count; $i++){
    $value=$rows.Item($i).LastChild.'#text'
    if($value -ne $null){
       $attr=$xml.CreateAttribute('style')
       $attr.Value='background-color: red;'
       [void]$rows.Item($i).Attributes.Append($attr)
    }
  
    else {
       $value
       $attr=$xml.CreateAttribute('style')
       $attr.Value='background-color: green;'
       [void]$rows.Item($i).Attributes.Append($attr)
    }
}

#embed a CSS stylesheet in the html header
$html=$xml.OuterXml|Out-String
$style='<style type=text/css>#diskTbl { background-color: white; }
td, th { border:1px solid black; border-collapse:collapse; }
th { color:white; background-color:black; }
table, tr, td, th { padding: 2px; margin: 0px } table { margin-left:50px; }</style>'

ConvertTo-Html -head $style -body $html -Title "Replication Report"|Out-File ReplicationReport.htm


Friday, March 6, 2015

Microsoft Forefront Eventlog | Powershell

thru complex number of reasons... need to monitor forefront via eventlogs - dont have centralised reporting.

1.could of setup alerts on each box to email when a virus detections
2.powershell to check eventlogs and do stuff with it.

had issue with eventlog culture on non powershell4 box.

#
# Virus Detections Last 1 days
#

$LogEntries =@()
$daysAgo = (get-date) - (new-timespan -day 1)

# BugFix for PS3 and anything other than en-us
$orgCulture = Get-Culture
[System.Threading.Thread]::CurrentThread.CurrentCulture = New-Object "System.Globalization.CultureInfo" "en-US"

#
# Target
#
$ou='OU=MOE Servers,DC=lc,DC=local'
$computers=Get-ADComputer -Filter * -SearchBase $ou


foreach ($server in $computers) {
$report=Get-WinEvent -FilterHashtable @{logname='system'; id=1006; ProviderName='FCSAM';StartTime=$daysAgo} -computername $server.dnshostname -ErrorAction SilentlyContinue

    if ($report){
    foreach ($panda in $report){
        $Obj = New-Object -TypeName PsObject
        $Obj | Add-Member -membertype noteproperty -name Server -value ($server.DNSHostName)
        $Obj | Add-Member -membertype noteproperty -name TimeCreated -value ($panda.timecreated)

            foreach ($jeff in (($panda.message).Split("`r"))){
            if ($jeff -match "Name:"){$output=$jeff}
            if ($jeff -match "Severity:"){$output+=$jeff}
             }
        $Obj | Add-Member -membertype noteproperty -name Message -value ($output.Trim())
        $LogEntries += $Obj
    }
#Clear 
$report=$null
$output=$null
}

}

#
# Switch back to Aus
#
[System.Threading.Thread]::CurrentThread.CurrentCulture = New-Object "System.Globalization.CultureInfo" "en-AU"

$LogEntries | sort timecreated -Descending

#
# then do stuff like export to webserver or..
#

Wednesday, December 10, 2014

Elevate'd Privilege - ACLs of Folders - Backup operator

Using PSCX powershell module to give backup operator rights (also might need to do a file server level)
ipmo pscx
$priv=get-privilege
$priv.Enable("SeRestorePrivilege")
$priv.Enable("SeBackupPrivilege")
$priv.Enable("SeSecurityPrivilege")
$priv.Enable("SeTakeOwnershipPrivilege")
set-privilege $priv;
$report=$null
$Report=@()
$InputFile = "C:\temp\Folders.txt"
$OutputFile = "C:\temp\FolderPermissions.csv"
$FolderList = Get-Content $InputFile

ForEach ($Folder in $FolderList)
{
# Get access list items of the folder
$Permissions = (Get-Acl -Path $Folder).Access | 
# Add the path property and assign its value, -PassThru so the object is assigned to $Permissions
forEach-Object { $_ | Add-Member -MemberType NoteProperty -Name Path -Value $Folder -PassThru }

$Report += $Permissions
}

$Report | Select-Object path,IdentityReference,FileSystemRights,IsInherited | Export-CSV $OutputFile -NoTypeInformation 
thanks to whoever's code source I used... so much internet so little time.

Saturday, January 25, 2014

Comparing AD object security

$tango=(Get-Acl "AD:$((Get-ADUser tango).distinguishedname)").access | select identityreference, accesscontroltype
$cash=(Get-Acl "AD:$((Get-ADUser cash).distinguishedname)").access | select identityreference, accesscontroltype
compare $tango $cash
still couldn't get to root cause of the issue.(automated system cant update account)

Sort\Move files based on first letter

#
# Sort Files based on first letter
#
#
$path='P:\vid\Movies'
# Issue : anything starting with "the" can cause the Q-Z to fill up
# comment out if not required
$thefiles=Get-ChildItem $path -af the*.* -recurse -exclude *.txt,*.jpg,*.nfo
foreach($file in $thefiles){
ren $file ($file.Name).Substring(4)
}
#
#
#
Get-ChildItem $path -af -recurse -exclude *.txt,*.jpg,*.nfo,*.xml | Where-Object {$_.Name -match "^[a-e]"} | ForEach-Object {move $_.fullname P:\sorted\A-E}
Get-ChildItem $path -af -recurse -exclude *.txt,*.jpg,*.nfo,*.xml | Where-Object {$_.Name -match "^[f-k]"} | ForEach-Object {move $_.fullname P:\sorted\F-K}
Get-ChildItem $path -af -recurse -exclude *.txt,*.jpg,*.nfo,*.xml | Where-Object {$_.Name -match "^[l-p]"} | ForEach-Object {move $_.fullname P:\sorted\L-P}
Get-ChildItem $path -af -recurse -exclude *.txt,*.jpg,*.nfo,*.xml | Where-Object {$_.Name -match "^[Q-Z]"} | ForEach-Object {move $_.fullname P:\sorted\Q-Z}

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 
                          }
            }
     }
    
    

    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"
    
    

    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, 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.