Showing posts with label shell. Show all posts
Showing posts with label shell. Show all posts

Thursday, May 5, 2016

VMware: Powershell Query each ESX Hosts Syslog


This query will report each host and its current Syslog

get-vmhost | select Name,@{Name="SysLog"; Expression={(get-vmhostsyslogserver $_.name)}} | FL

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
}

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
}


}

Monday, October 13, 2014

Powershell: Find all shares on domain using Jobs


Purpose: This script will search AD for all servers and report any shares(includes printers)

This script will do 50 servers at a time
Requires RSAT tools powershell
cls

#Find Shares on all Domain computers 50 at a time
#www.tonyunger.com  
  
cls   
import-module activedirectory
  
#$Global:Servers = Get-Content "C:\temp\computers.txt"  
$Global:Servers = Get-ADComputer -Filter {(OperatingSystem -Like "Windows Server*")-and (enabled -eq "true")} -Property SamAccountName | Select -expand Name  
$Global:ReportPath = "C:\temp\Shares.txt"  
  
$scriptblock = {  
       param($server)  
    $pingResult = Test-Connection -count 1 -ErrorAction SilentlyContinue $server | select IPV4Address 
       $Shares = Get-WmiObject Win32_Share -ComputerName $Server | select name 
       $values = @()  
       if($Error){  
            if( $Error -like "*Access is denied*"){  
                return ($server+",AccessDenied")  
            }  
            $Error.Clear()  
            return ($server+",")  
       }  
     
     foreach ($Share in $shares) {            
  
         $values += ($Server + "," + $Share) 
             }  
       return $values  
}  
  
function getdata{  
    $jobs = Get-Job | ? { $_.State -eq "Completed" }  
     foreach( $job in $jobs){  
        $results = Receive-Job $job  
       Add-Content $ReportPath $results  
        Remove-Job $job  
     }     
}  
  
  
Add-Content $ReportPath "Server,share"  
foreach($server in $Servers){  
          
     while( (Get-Job).count -ge 50 ){ 
            sleep -Seconds 1  
            getdata  
     } 
  
     Start-Job -ScriptBlock $scriptblock -ArgumentList $server 
}  
  
while( (get-job).count -ne 0 ){  
      sleep -Seconds 1
            getdata  
              
 }  
   
 

Saturday, August 23, 2014

Powershell - get all host files on domain.


Purpose: This script will search AD for Window computers and attempted to connect to each one. Then it will read the contents of the host file and write them to a csv file.

Note: This will take a while to run unless someone wants to make it multithreaded.
I just wrote this so there may need to be some bug fixes but in general it seemed to work.

#Read all host files and write to CSV file


Import-Module ActiveDirectory

$PATH = "c:\temp\hostfiles.csv"


   $myCol = @()
   
$AllComputers = Get-ADComputer -Filter {OperatingSystem -Like "Windows*"} -Property * | Select -Expand Name

foreach ($Computer in $AllComputers){
$i++

Write-Progress -activity "Scanning Machine $Computer " -status "Scanned: $i of $($AllComputers.Count)" -percentComplete (($i / $AllComputers.Count)  * 100)
 Get-Content -Path "\\$Computer\c$\windows\system32\drivers\etc\hosts" |             
 where {!$_.StartsWith("#")} |            
 foreach {            
  if ($_ -ne ""){            
  $data = $_ -split " ",2            
  $Hosts = New-Object -TypeName PSObject -Property @{            
     Host = $Computer
  IPAddress = $data[0].Trim()   
  Node = $data[1].Trim()            
              
   }            
  } 
  $myCol += $Hosts
 }    
 $myCol |Select Host,Node,IPAddress| Export-Csv -Path $PATH -NoTypeInformation
}




Tuesday, August 5, 2014

Powershell: Get list of all services accounts used on Windows servers in domain.


Purpose: This script will search AD for Windows Servers that are enabled and attempted to connect to each server and get a listing of all services and the accounts used to run them.
Note: This will take a while to run unless someone wants to make it multithreaded.
I just wrote this so there may need to be some bug fixes but in general it seemed to work.
Requirements: RSAT tools WMI



Import-Module activedirectory
cls

$ServicesReport = @()

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

$i = 0
foreach($Server in $AllServers) {
$i++
Write-Host "Working on Server: $Server " $i " of " $AllServers.Count 

try
{
if (Test-Connection -ComputerName $Server -Quiet) {
$Services = Get-WmiObject win32_service -ComputerName $Server | select Name,
  @{N="StartupType";E={$_.StartMode}},
  @{N="ServiceAccount";E={$_.StartName}},
  @{N="SystemName";E={$_.Systemname}}
    foreach ($Service in $Services) {
       $Detail = New-Object PSObject 
    $Detail | Add-Member Noteproperty ServiceName $($Service.Name)
    $Detail | Add-Member Noteproperty StartupType $Service.StartupType
    $Detail | Add-Member Noteproperty ServiceAccount $Service.ServiceAccount
    $Detail | Add-Member Noteproperty SystemName $Service.Systemname
       $ServicesReport += $Detail
    }
 }
}
Catch
{
$Detail = New-Object PSObject 
    $Detail | Add-Member Noteproperty ServiceName "NA"
    $Detail | Add-Member Noteproperty StartupType "NA"
    $Detail | Add-Member Noteproperty ServiceAccount "Error"
    $Detail | Add-Member Noteproperty SystemName $Server
       $ServicesReport += $Detail
  
 }
  
  } 
  
$ServicesReport | Export-Csv -Path c:\temp\test.csv -NoTypeInformation


Powershell-DellBatchWarrentylookup


Purpose: This script will read serial numbers from a text file then search dells site for warranty information. The get-dellassetinfo function i found from some forum but don't remember where.


###################################
$ComputerSerials = gc "c:\temp\SerialNumbers.txt"
###################################
Function Get-DellAssetInfo([string]$ServiceTag){

 $Asset=New-WebServiceProxy -Uri 'http://xserv.dell.com/services/AssetService.asmx?WSDL' -UseDefaultCredential
 $Asset.GetAssetInformation([Guid]::NewGuid(),'AssetService',$ServiceTag);
}

$myCol = @()
foreach ($ComputerSerial in $ComputerSerials) {
 $results=Get-DellAssetInfo $ComputerSerial
 $SystemType = $results.AssetHeaderData.SystemType
 $ServiceLevelDescription = $results.Entitlements.ServiceLevelDescription
 $SystemModel = $results.AssetHeaderData.SystemModel
 $Region = $results.AssetHeaderData.Region         
 $StartDate = $results.Entitlements.StartDate.Date | Select -ExpandProperty DateTime 
 $EndDate = $results.Entitlements.EndDate.Date | Select -ExpandProperty DateTime  
 Write-Host "Writing $ComputerName info" 
 $x = 0
   foreach ($Sdate in $StartDate) {
    $Detail = New-Object PSObject 
    $Detail | Add-Member Noteproperty ComputerName $ComputerName
    $Detail | Add-Member Noteproperty Serial $ComputerSerial
    $Detail | Add-Member Noteproperty Manufacturer $ComputerManufacturer
    $Detail | Add-Member Noteproperty SystemType $SystemType
    $Detail | Add-Member Noteproperty SystemModel $SystemModel
    $Detail | Add-Member Noteproperty Region $Region
    $Detail | Add-Member Noteproperty ServiceLevelDescription $ServiceLevelDescription.get_Item($x)
    $Detail | Add-Member Noteproperty StartDate $Sdate
    $Detail | Add-Member Noteproperty EndDate $EndDate.get_Item($x)
    $x++
    $myCol += $Detail
   }
  

}

$myCol | Export-Csv -Path c:\temp\AD_WarrentyComputerSerialNumbers.csv -notype

Thursday, February 13, 2014

Powershell: Get All AD Group Members


Purpose: This script requires the RSAT tools to work. It connects to AD and gets all groups and users within each group and outputs to a csv file. It can also get single groups and display/exports the results.


###################################
#Tony Unger - Get Group members
#12/12/2013
#1.0
###################################

Import-Module activedirectory

do {
  cls
$response = "N"
$ExportPath = "c:\temp\AD_GroupMemberofQuery.csv"
$myCol = @()

[int]$xMenuChoiceA = 0
while ( $xMenuChoiceA -lt 1 -or $xMenuChoiceA -gt 4 ){
Write-host "Active Directory Group Member Reporting" -foregroundcolor "magenta"
Write-host "1. Specifiy a Group"
Write-host "2. All Groups"
Write-host "3. Quit and exit"
[Int]$xMenuChoiceA = read-host "Please enter an option 1 to 3..." }

Switch( $xMenuChoiceA ){
  1{$ADGroups = read-host "Please enter the AD group name:"}
  2{$ADGroups = Get-ADGroup -filter {GroupCategory -eq "Security" -and GroupScope -eq "Global"} | Select -expand SamAccountName}
  3{exit}
default{exit}
}

$i = 0
foreach ($ADGroup in $ADGroups){
  

 $i++
 Write-Progress -Activity "Gathering members" -status "Currently on group $ADGroup" -percentComplete ($i / $ADGroups.count*100)
 $Members = get-adgroupmember $ADGroup -recursive

 
 foreach ($MemberofGroup in $Members){
 
  $Detail = New-Object PSObject 
  $Detail | Add-Member Noteproperty GroupName $ADGroup
  $Detail | Add-Member Noteproperty User $MemberofGroup.Name
  $Detail | Add-Member Noteproperty Account_Name $MemberofGroup.SamAccountName
  $myCol += $Detail
 }

}



$myCol | Export-Csv -Path $ExportPath -notype
Write-Host "File exported to: $ExportPath"


[int]$xMenuChoiceB = 0
while ( $xMenuChoiceB -lt 1 -or $xMenuChoiceA -gt 4 ){
cls
Write-host "Active Directory Group Member Reporting" -foregroundcolor "magenta"
Write-host "1. Display current results"
Write-host "2. Query another group"
Write-host "3. Quit and exit"
[Int]$xMenuChoiceB = read-host "Please enter an option 1 to 3..." }

Switch( $xMenuChoiceB ){
  1{$myCol}
  2{$response = "Y"}
  3{exit}
default{exit}
}

}
while ($response -eq "Y")


Thursday, May 9, 2013

Powershell: Read servers from AD and search for shares and return ACL permissions


Purpose:
Connects to active directory and pulls a list of all computer objects that are servers and check ACL permissions

  
Import-Module ActiveDirectory
#Most of the information to do this was from this site.
#http://blogs.technet.com/b/heyscriptingguy/archive/2009/09/14/hey-scripting-guy-september-14-2009.aspx

Function Get-ACLPermissions($Share){

    $acl = Get-Acl -Path $Share

return $ACL

}


function Get-MyShares

{
#Function by
#http://www.peetersonline.nl/2008/11/finding-shares-with-powershell/

     param([string]$Server)
     $Shares = Get-WmiObject -Class Win32_Share -ComputerName $Server
     $output = @()
         ForEach ($Share in $Shares)
         {
              $fullpath = “\\{0}\{1}” -f $server, $share.name
              Add-Member -MemberType NoteProperty -InputObject $Share -Name FullPath -Value $fullpath
              $output += $Share
         }
         Return $output
}

#Path to where the CSV file is written to
$PathtoCSV = "C:\temp\AuditACL.csv"

#Create Header in CSV
"Server;Share;Username;FileSystemRights;AccessControlType;IsInherited;InheritanceFlags" > $PathtoCSV 
#Get all computers that are servers from AD
$Servers = Get-ADComputer -Filter {OperatingSystem -Like "Windows Server*"} -Property * | Select -Expand Name
$i = 0
foreach ($Server in $Servers)
# update counter and write progress
{
   $i++
   Write-Progress -activity "Scanning Machine $Server" -status "Scanned: $i of $($Servers.Count)" -percentComplete (($i / $Servers.Count)  * 100)
   
# Get all Shares on server
    $Shares = Get-MyShares $Server | Select -ExpandProperty Name 
        foreach ($Share_Current in $Shares){
        #Process all Shares on Server
            $fullpath = "\\$Server\$Share_Current"
            $ShareACL = Get-ACLPermissions $fullpath
            $o = 0
            $ShareACL.Access | ForEach-Object {
            $FileSystemRights = $ShareACL.Access[$o] | Select -ExpandProperty FileSystemRights #Example ReadAndExecute
            $AccessControlType = $ShareACL.Access[$o] | Select -ExpandProperty AccessControlType #Example Allow/Deny
            $IdentityReference = $ShareACL.Access[$o] | Select -ExpandProperty IdentityReference #Example Everyone,Username
            $IsInherited = $ShareACL.Access[$o] | Select -ExpandProperty IsInherited #Are Permissions inherited
            $InheritanceFlags = $ShareACL.Access[$o] | Select -ExpandProperty InheritanceFlags #Type of Inheritance ContainerInherit
            $PropagationFlags = $ShareACL.Access[$o] | Select -ExpandProperty PropagationFlags #PropagationFlags
            $o++

            switch -wildcard ($FileSystemRights) 
            { #Should be a better way to do this via function
                "268435456*" {$FileSystemRights = "FullControl"} 
                "-536805376*" {$FileSystemRights = "Modify, Synchronize"} 
                "-1610612736*" {$FileSystemRights = "ReadAndExecute, Synchronize"} 
            }
            $Combine = $Server,$fullpath,$IdentityReference,$FileSystemRights,$AccessControlType,$IsInherited,$InheritanceFlags
            Write-Host "$Combine to $PathtoCSV"
            $Combine -join ";" >> $PathtoCSV
        } 
}
}





Powershell: Microsoft Graph to add new roles to application registration

PowerShell Script Bulk add new roles to application registration in azure. Update $roles with ,Us...