Monday, April 18, 2016

Powershell: Get services and accounts used to run them on all computers using Jobs


cls
####################
#By Tony Unger
#Purpose: inventory all services and user accounts running them with jobs
#
##
$myCol = @()
$i =0  
$servers = get-adcomputer -filter * | select -expand name 

$scriptblock = {
 param([string]$server)

get-wmiobject win32_service -computername $Server | select *

}

$ServersCount = $Servers.count

foreach($server in $Servers){
    $i++
    $running = @(Get-Job | Where-Object { $_.State -eq 'Running' })
 Write-Progress -Activity "Gathering computer info" -status "Currently on $server -- $i of $ServersCount" -percentComplete ($i / $ServersCount*100)
 if ($running.Count -le 50) {
        Start-Job -ScriptBlock $scriptblock -Name $server -ArgumentList $server, $creds 
    } 
 else {
         $running | Wait-Job
    }
}

while ($running.Count -ge 1) {
      sleep 1 
    $running = @(Get-Job | Where-Object { $_.State -eq 'Running' })
} 


foreach ($job in Get-Job ){

 $recjobs = Receive-Job -Keep -Job $job 
 foreach ($recjob in $recjobs){
    $Detail = New-Object PSObject 
     
  $Detail | Add-Member Noteproperty Caption $recjob.Caption
  $Detail | Add-Member Noteproperty Name $recjob.name 
  $Detail | Add-Member Noteproperty Startname $recjob.startname
        $Detail | Add-Member Noteproperty Server $recjob.__SERVER
  $myCol += $Detail

 }
}

Wednesday, February 3, 2016

Powershell: RDP log user account off of all servers using jobs.

#Log User account off all servers
# Tony Unger
# 

$Domain = "Microsoft.com"
$Servers = Get-ADComputer -Filter {(OperatingSystem -Like "Windows Server*")-and (enabled -eq "true")} -Property SamAccountName -Server $Domain Select -expand Name
$username = read-host "Enter Users Name:"
$i = 0

$scriptblock = {
 param(
 [string]$server,
 $Username
 )

$queryResults = (qwinsta /server:$server $Username| foreach { (($_.trim() -replace "\s+",","))} | ConvertFrom-Csv)
 foreach ($queryResult in $queryResults){
  Logoff /server:$server $queryResult.id
 }
}
$TotalServersCount = $Servers.count
foreach($server in $Servers){
$i++
    $running = @(Get-Job | Where-Object { $_.State -eq 'Running' })
 Write-Progress -Activity "logging off user" -status "Currently on $server -- $i of $TotalServersCount" -percentComplete ($i / $Servers.count*100)
 if ($running.Count -le 50) {
        Start-Job -ScriptBlock $scriptblock -Name $server -ArgumentList $server, $username
    }
 else {
         $running | Wait-Job
    }
}

while ($running.Count -ge 1) {
      sleep 1
    $running = @(Get-Job | Where-Object { $_.State -eq 'Running' })
 Remove-Job -State Completed
}

Thursday, December 24, 2015

Powershell: VMware one liner to list total vm that are powered on each host

This one liner will query each host and id its cluster total vms and how many VMs are powered on
Get-VMHost | Select @{N="Cluster";E={Get-Cluster -VMHost $_}}, Name, @{N="Total_VMs";E={($_ | Get-VM).Count}},@{N="Powered_On";E={($_ | get-vm | ? {$_.powerstate -like "*ON*"}).count}} | Sort Cluster, Name | fl

Thursday, July 9, 2015

Powershell: Jobs - Search for shares in ad windows servers

Job script to search for shares in a active directory environment. Update $Domain to your domain and run
#Tony Unger 
#Tonyunger.com
#Scans all AD servers for Shares 
#50 servers at a time
#Will Prompt for creds
$i =0  
import-module activedirectory 
cls
$creds = Get-Credential 
$myCol = @()
$Domain = "microsoft.com"

$Servers = Get-ADComputer -server $Domain -Filter {(OperatingSystem -Like "Windows Server*")-and (enabled -eq "true")} -Property SamAccountName | Select -expand Name

$scriptblock = {
 param(
 [string]$server,
 $creds
 )
 Get-WmiObject Win32_Share -ComputerName $server -Credential $Creds | select *

}
foreach($server in $Servers){
$i++
    $running = @(Get-Job | Where-Object { $_.State -eq 'Running' })
 Write-Progress -Activity "Gathering computer info" -status "Currently on $server -- $i of $Servers.count" -percentComplete ($i / $Servers.count*100)
 if ($running.Count -le 50) {
        Start-Job -ScriptBlock $scriptblock -Name $server -ArgumentList $server, $creds 
    } 
 else {
         $running | Wait-Job
    }
}

while ($running.Count -ge 1) {
      sleep 1 
    $running = @(Get-Job | Where-Object { $_.State -eq 'Running' })
} 


foreach ($job in Get-Job ){

 $recjobs = Receive-Job -Keep -Job $job 
 foreach ($recjob in $recjobs){
    $Detail = New-Object PSObject 
  $Detail | Add-Member Noteproperty Name $recjob.name 
  $Detail | Add-Member Noteproperty Path $recjob.path 
  $Detail | Add-Member Noteproperty Server $recjob.__SERVER
  $myCol += $Detail
 }
}
$myCol
$myCol | export-csv -Path c:\TEMp\shares\output.csv -notype 


Friday, June 5, 2015

Windows: Multiple users, one user gets a blue flash while attempting to launch applications while the other user works fine

I came across an interesting issue where if more then one user is on a Win 2012 r2 server there would be a blue flash while one of the users attempted to launch an application. While the other user would work just fine launching applications. If the user that was working fine logged off the user that was previously not working then would be able to launch applications.

In the event log i saw something similar to this:


Faulting application name: explorer.exe, version: 6.3.9600.17667, time stamp: 0x54c6f7c2
Faulting module name: unknown, version: 0.0.0.0, time stamp: 0x00000000
Exception code: 0xc0000005
Fault offset: 0x0000000000000000
Faulting process id: 0xdd4

Faulting application path: C:\Windows\explorer.exe
Faulting module path: unknown

Faulting package full name:
Faulting package-relative application ID:

Well it turns out Winzip 19+ was installed on the server and seems to have been the root cause of the issue. I found the fix to be disabling Explorer File Association Helper in Winzip Options



Tuesday, April 21, 2015

Powershell - Com+ Application Recycle

Needed a script to recycle a com+ application nightly and this is what i came up with. This script will write each recycle it does to the event log under application. Run locally or via a scheduled task.
#Recycle COM+ Application and write to the event log the status
# 1.0 Release
# Run script locally
# Write to the event log


########################################
#Configurable
########################################
#Com+ ApplicationName
$ComPlusLikeAppName = "Put the name of Com+ Application here a like statement is used to eval so you can get away with putting part of it"
#EventLog to write to.
$eventlog = "Application"
#Source for eventlog.
$source = "RecycleComObject"
#Successful Event ID
$SEventID = 0
#Error Event ID
$EEventID = 666
#Process that COM+ runs under
$process = "dllhost.exe".
########################################

#Clear
$CurrentMemory = $null
$PRocessID = $null
$Commandline = $null
$GUID = $null
$AppID = $null
$Message = $null
$ConvertedMemory = $null
$CheckProcessID= $null 



#Clear errors
$ErrorMsg = $null
$error.clear()

#Create event source for writing to the eventlog if does not already exist.
if(![System.Diagnostics.EventLog]::SourceExists($source)) {
                [System.Diagnostics.EventLog]::CreateEventSource($source , $eventlog);
}

$RecycleReason = 1
$comAdmin = New-Object -com COMAdmin.COMAdminCatalog
$applist = $comAdmin.GetCollection("Applications") 
$applist.Populate()
$AppID = $applist | where {$_.Name -like "*$ComPlusLikeAppName*"} | select -expand key


#Find Process ID
$Commandline = Get-WmiObject Win32_Process -Filter "name = '$process'" | select ProcessID,CommandLine
$ProcessID = $Commandline | where {$_.Commandline -like "*$AppID*"} | Select -expand ProcessID


#If two process with the same GUI assume dllhost is in middle of recycle
if ($ProcessID.count -gt 1){
$Message = "Please wait up to 15 minutes(default) as there are two PID with the same $AppID" 

Write-EventLog -LogName $eventlog -Source $source -EventId $SEventID -EntryType Information –Message $Message

exit

}


#
#Get GUID from Process ID
$GUID = $comAdmin.GetApplicationInstanceIDFromProcessID($ProcessID)

#GetCurrentMemory 
$CurrentMemory = get-process -id $ProcessID | select -ExpandProperty "PrivateMemorySize"

#Event Messages


write-host "Process ID:$ProcessID"
Write-host "ApplicationID:$AppID"
write-host "GUID:$GUID"
$ConvertedMemory = [math]::truncate($CurrentMemory / 1MB)
Write-Host "CurrentMemory:$ConvertedMemory"




try {
$comAdmin.RecycleApplicationInstances($GUID,$RecycleReason)
}
catch {
#If error is caught 
  $ErrorMsg = [system.exception]"caught a system exception `n $error"
}
Finally
 {
    start-sleep -seconds 5
#Check if there is an increase in the amount of PID
$Commandline = Get-WmiObject Win32_Process -Filter "name = '$process'" | select ProcessID,CommandLine
$CheckProcessID = $Commandline | where {$_.Commandline -like "*$AppID*"} | Select -expand ProcessID


$NewProcessID = $CheckProcessID | where {$_ -notlike "*$ProcessID*"} 
write-host "NewProcessID:$NewProcessID"
$Message = " Process ID:$ProcessID `n ApplicationID:$AppID `n GUID:$GUID `n MemoryBeforeRecycle:$ConvertedMemory MB `n New Process ID:$NewProcessID"


    if($ErrorMsg -ne $null){
         $Message += $ErrorMsg
     Write-EventLog -LogName $eventlog -Source $source -EventId $EEventID -EntryType error –Message $Message
        exit 
}

if ($ProcessID -eq $null -or $AppID -eq $null -or $GUID -eq $Null -or $ConvertedMemory -eq $null -or $NewProcessID -eq $null) {
Write-EventLog -LogName $eventlog -Source $source -EventId $EEventID -EntryType error –Message "$Message `n Value Missing"
        exit 
}

else {
Write-EventLog -LogName $eventlog -Source $source -EventId $SEventID -EntryType Information –Message $Message
}


}

Sunday, April 5, 2015

Windows 10 - ox80073cff Mail, Calendar, and People apps won't install

ox80073cff  
  • In this build, the Mail, Calendar, and People apps may be broken due to a licensing issue with the Store Beta. To get these apps working again, you need to follow these steps:
    • Open powershell as administrator
    • Run the command Get-appxprovisionedpackage –online | where-object {$_.packagename –like “*windowscommunicationsapps*”} | remove-appxprovisionedpackage –online
    • Re-install Mail, People and Calendar from the Store (green tile)
http://blogs.windows.com/bloggingwindows/2015/03/18/windows-10-technical-preview-build-10041-now-available/

If you now get this error 0x80246007 try running: from and administrator command prompt

DISM /Online /Cleanup-Image /RestoreHealth

KQL - Group Object Audits ADDS

This is a KQL written for Azure Sentinel. Purpose is to search for eventid from Active Directory Domain Services related to Group objects....