Monday, October 26, 2015

RDP session timeouts copy with powershell

#
# using an account as a template update other account to same value.
#yes.. not the best way.
#

$basic=Get-adUser jeff -Properties userParameters | select userParameters

$userlist=Get-aduser -Filter {samaccountname -like "nerds*"}
foreach ($target in $userlist){
$user=get-aduser $target.SamAccountName -Properties userParameters
$user.userParameters=$basic.userParameters
Set-ADUser -instance $user
$user=$null
}

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
}

Tuesday, October 6, 2015

Powershell : Clone DNS

$xraydns=Get-DnsServerResourceRecord -zonename "elephant.com.au" -ComputerName acdc001 -RRType A
foreach ($dns in $tangodns){
Add-DnsServerResourceRecordA -ZoneName "panda.com.au" -ComputerName acdc001 -Name $dns.hostname -IPv4Address $dns.recorddata.IPv4Address.IPAddressToString #-WhatIf
}

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

Saturday, August 1, 2015

windows 10 | cleanups debloat

if you dare...

follow this
- https://www.reddit.com/r/Windows10/comments/3f38ed/guide_how_to_disable_data_logging_in_w10/


my Debloat script...
Help from
- http://blogs.technet.com/b/deploymentguys/archive/2013/10/21/removing-windows-8-1-built-in-applications.aspx
- https://www.reddit.com/r/Windows10/comments/3diylq/powershell_commands_to_uninstall_unwanted_builtin/

#
# Cleans up Windows 10 Bloatware... Perform at your own risk :) !
#

$Removelist=@"
Microsoft.BingFinance                   
Microsoft.BingWeather
Microsoft.BingNews
Microsoft.Windows.Photos                
Microsoft.WindowsCamera
Microsoft.XboxApp                       
Microsoft.ZuneMusic                     
microsoft.windowscommunicationsapps
Microsoft.SkypeApp                      
Microsoft.ZuneVideo                     
Microsoft.WindowsSoundRecorder          
Microsoft.WindowsScan                   
Microsoft.WindowsReadingList            
Microsoft.WindowsPhone                  
Microsoft.WindowsMaps                   
Microsoft.Reader                        
Microsoft.People                        
Microsoft.Office.OneNote                
Microsoft.MicrosoftSolitaireCollection  
Microsoft.MicrosoftOfficeHub            
Microsoft.BingTravel                    
Microsoft.BingSports                    
Microsoft.BingHealthAndFitness          
Microsoft.BingFoodAndDrink
#Microsoft.3DBuilder
"@

$removelist=$Removelist.split("`n")

ForEach ($App in $removeList){

$app=$App.Trim()

$Packages = Get-AppxPackage | Where-Object {$_.Name -eq $App}

if ($Packages -ne $null){

Write-Host "Removing Appx Package: $App"

foreach ($Package in $Packages)

{

Remove-AppxPackage -package $Package.PackageFullName 

}

}

else

{

Write-Host "Unable to find package: $App"

}

$ProvisionedPackage = Get-AppxProvisionedPackage -online | Where-Object {$_.displayName -eq $App}

if ($ProvisionedPackage -ne $null)

{

Write-Host "Removing Appx Provisioned Package: $App"

remove-AppxProvisionedPackage -online -packagename $ProvisionedPackage.PackageName 

}

else

{

Write-Host "Unable to find provisioned package: $App"

}

}





Thursday, July 23, 2015

Powershell | Array, Element, SQL

working on extracting elements from a array then uploading into SQL

#test array
$comp = New-Object System.Object
$comp | Add-Member -type NoteProperty -name DSAType -value "xtra"
$comp | Add-Member -type NoteProperty -name Hostname  -value "Host"
$comp | Add-Member -type NoteProperty -name Fails -value "failures"

#foreach ($comp in $warrantarray){
$cl=$null
$dl=$null
($comp|gm)|where{$_.membertype -eq 'noteproperty'}|% {
$cl+=$_.Name+","
$dl+=($comp).($_.name)+","
}
$cl=$cl.Substring(0,$cl.Length-1)
$cl
$dl=$dl.Substring(0,$dl.Length-1)
$dl
# do sql stuf... but write-hosting here...

write-host "INSERT INTO $dbTable ($cl) VALUES ($dl)"

#}

also possible to this way.

http://sphints.blogspot.com.au/2014/03/powershell-write-array-of-objects-to.html

Wednesday, July 8, 2015

BBQ Linux - IPC \ PACMAN update error

Just performed my 2nd built of antergos
for some reason PACMAN was having issues. :|

ran
# dirmngr  << dev
from https://bbs.archlinux.org/viewtopic.php?id=190380

and all was working again...

Thursday, June 25, 2015

XenApp Changelog - Last 7 days




Add-PSSnapin Citrix.common.commands
$connectionstring="Data Source=lc28xensql;Initial Catalog=xencfglog;User Id=xencfgviewer;Password=xencfgviewer;Provider=SQLOLEDB;"
$timeperiodfrom=(Get-Date).AddDays(-7)
Get-CtxConfigurationLogReport -ConnectionString $connectionstring -TimePeriodFrom $timeperiodfrom | format-table -Property Date,account,tasktype,itemtype,itemname,description -AutoSize

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}

Tuesday, April 21, 2015

removing windows 2012 data deduplication volume

thanks to nickwhittome.com/2014/10/01/disabling-data-deduplication-on-windows-server-2012r2

#The unoptimise command
start-dedupjob -Volume E:   -Type Unoptimization
#Check the status
get-dedupjob

Then...

#Clean up the Garbage
start-dedupjob -Volume
E: -Type GarbageCollection
#Check the status
get-dedupjob


Then...
 
Disable-DedupVolume -Volume E:

Adobe Reader 10 - Access Denied opening PDF - solved

Some Operational team members moved some data to a Windows 2012 R2 server.
The Citrix Environment is currently in a 'change freeze' and was running 10.0.1.0 of adobe readerX.


When a pdf was opened from network share "access denied"
It could be fixed by untick protected mode.. but then we are unprotected right.

Note: Upgrading the Adobe reader also fixed this issue but 'Change Freeze'

so




Root Cause : Citrix version of Adobe Reader PDF is not trusting any de-duplicated pdf files as they have been “modified”

Process to replicate

  1. robocopy  "E:\Data\Group" E:\temp   *.pdf /s  /move
  2. robocopy   "E:\temp" "E:\Data\Group"   E *.pdf /s /move
  3. [pdf file attribute was A]
  4. Forced Dedup Job - Start-DedupJob E: -Type Optimization 
    (note our server was set to MinimumFileAgeDays 0)
  5. [pdf file attribute was APL]


so either



Set-DedupVolume –Volume E: -ExcludeFiletype pdf
 or
 Just disabled dedup on this volume.

/thx

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'

Monday, March 23, 2015

force a machine password change


nltest.exe /sc_change_pwd:mydomain.corp.mycompany.com


now with more info...
http://blogs.msdn.com/b/sudhakan/archive/2010/01/07/experimenting-with-windows-machine-account-passwords-and-vm-snapshots.aspx

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