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

Monday, March 2, 2015

Powershell: SkipAsSource Flag

Finally ran into an issue where the removal of the primary ip address after Server 2003 caused an issue. Since if you have a multihomed nic the routing table will be set to use the closest IP address to the gateway as the source interface. Here is a fix from  James Kehr to run on your server to set an ip address to be the "Primary" ie Source. I did edit his script by putting a menu and removing the need to put a interface alias. This should only work with 2012 and above with powershell 3.0 and above. For other OS check the heyscriptingguy link.

http://blogs.technet.com/b/heyscriptingguy/archive/2013/01/24/use-powershell-to-change-ip-behavior-with-skipassource.aspx
KB969029

Thank you James Kehr
# set some constants
clear
Import-Module NetTCPIP

Get-NetIPAddress | Where {$_.PrefixOrigin -eq "Manual"} | select IPaddress,InterfaceAlias,SkipasSource | format-table

$primaryIP = Read-Host "Which ip address should be set as primary?"
$Alias = Get-NetIPAddress $primaryIP -EA stop | select -expand InterfaceAlias

Write-Host "Setting $Alias primary IP to $primaryIP"

# get all the IP addresses on the interface, filtered by IPv4 and excluding

# the $primaryIP

[array]$IPs = Get-NetIPAddress -InterfaceAlias $Alias | Where-Object {$_.AddressFamily -eq "IPv4" -and $_.IPAddress -ne $primaryIP}

 

# set primary IP SkipAsSource to false

Set-NetIPAddress -IPAddress $primaryIP -InterfaceAlias $Alias -SkipAsSource $false

 

# set other IP addresses with SkipAsSource equal to true

Set-NetIPAddress -IPAddress $IPs.IPAddress -InterfaceAlias $Alias -SkipAsSource $true
Write-Host "Please review the output False under SkipasSource means the ip can be a source"
Get-NetIPAddress | Where {$_.PrefixOrigin -eq "Manual"} | select IPaddress,InterfaceAlias,SkipasSource | format-table

Sunday, January 25, 2015

Bring back the windows 10 start menu.


Just follow the steps below:
  1. ​Right click on the Start Button and select "Run"
  2. Type "regedit"
  3. Navigate to HKEY_CURRENT_USER>Software>Microsoft>Windows>CurrentVersion>Explorer>Advance
  4. Create a new DWORD (32-bit) value, call it "EnableXamlStartMenu"
  5. Restart Explorer​
Found from 
http://www.winbeta.org/news/how-bring-back-old-resizable-start-menu-running-windows-10-build-9926

Friday, November 21, 2014

SQL - If you don't have permission to logon fix

Purpose: If you don't want to put a SQL db into single user mode, you can try the following to give yourself permission to a SQL instance. The following will open a command prompt as the built in security principal "System" using PSExec. psexec -i -s -d cmd From there open SQL management studio from within that command prompt. ie: c:\Program Files (x86)\Microsoft SQL Server\100\Tools\Binn\VSShell\Common7\IDE\Ssms.exe" I came up with this independently, but a simple google search will show you others have figured it out as well. Should be able to now give yourself permissions to log on now depending on how the SQL was initially configured. If this doesn't work you will have to Start the instance of SQL Server in single-user mode by using either the -m or -f options. Any member of the computer's local Administrators group can then connect to the instance of SQL Server as a member of the sysadmin fixed server role.

http://msdn.microsoft.com/en-us/library/dd207004.aspx

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  
              
 }  
   
 

Friday, September 12, 2014

Powershell: get free disk space from computers listed in text file. using Job


Purpose: This script will search a list of computers and report their c drives total and free space into a text file that can be imported into excel.

This is my first time using jobs to speed up the process of gathering the info so there could be a better way of doing this but this seems to work just fine.

cls
#Get free disk space code from here.
#http://www.codeproject.com/Articles/757946/Retrieve-Disk-Space-of-Remote-Computers-using-Powe




$Global:Servers = Get-Content "C:\temp\computers.txt"
$Global:ReportPath = "C:\temp\freediskspace.txt"

$scriptblock = {
       param($server)
    $ConvertToGB = (1024 * 1024 * 1024)
       $pingResult = Test-Connection -count 1 -ErrorAction SilentlyContinue $server | select IPV4Address
       $disk = Get-WmiObject Win32_LogicalDisk -ComputerName $Server -Filter "DeviceID='C:'" | Select-Object Size,FreeSpace
       $values = @()
       if($Error){
            if( $Error -like "*Access is denied*"){
                return ($server+",,AccessDenied")
            }
            $Error.Clear()
            return ($server+",,")
       }
        
                
       $values += ($Server + "," + ($disk.Size / $ConvertToGB) + "," + ($disk.FreeSpace / $ConvertToGB) )
             
       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,Total,Free"
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
            
 }
 

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