Monday, February 3, 2014

Poor Man's Hardware Inventory - Powershell through logon script

We are in the middle of migrating a domain to ours and I was working on a plan to move all of the PC's over. I wanted to make sure that I was able to capture all of the existing hardware/OS configs without staying up till 2am and grab them manually... if they were online:)
I came up with this powershell script that will run on logon and write back to a specified location. Then I could gather them as people logged on/connected.
$name = (Get-Item env:\Computername).Value
$filepath = "\\SERVER\DIRECTORY"

function inventory {
# MotherBoard: Win32_BaseBoard
$manuf = Get-WmiObject Win32_ComputerSystem -ComputerName $name
# Hard-Disk
$hd = Get-WmiObject win32_diskDrive -ComputerName $name | ForEach-Object {[math]::round($_.size / 1GB)}
# Memory
$mem = Get-WmiObject Win32_ComputerSystem -ComputerName $name | ForEach-Object {[math]::round($_.TotalPhysicalMemory / 1GB)}
# Processor 
$cpu = Get-WmiObject Win32_Processor -ComputerName $name
#OS Architecture
$OS = Get-WmiObject Win32_OperatingSystem -ComputerName $name
## System enclosure 
$enc = Get-WmiObject Win32_SystemEnclosure -ComputerName $name
$type = $enc.chassistypes
$chassis = Switch ($type)
    {
        "1" {"Other"}
        "2" {"Virtual Machine"}
        "3" {"Desktop"}
        "4" {"Low Profile Desktop"}
        "5" {"Pizza Box"}
        "6" {"Mini Tower"}
        "7" {"Tower"}
        "8" {"Portable"}
        "9" {"Laptop"}
        "10" {"Notebook"}
        "11" {"Handheld"}
        "12" {"Docking Station"}
        "13" {"All-in-One"}
        "14" {"Sub-Notebook"}
        "15" {"Space Saving"}
        "16" {"Lunch Box"}
        "17" {"Main System Chassis"}
        "18" {"Expansion Chassis"}
        "19" {"Sub-Chassis"}
        "20" {"Bus Expansion Chassis"}
        "21" {"Peripheral Chassis"}
        "22" {"Storage Chassis"}
        "23" {"Rack Mount Chassis"}
        "24" {"Sealed-Case PC"}
        Default {"Unknown"}
     }

##Excract Object Data
$obj = New-Object psobject
$obj | Add-Member noteproperty Manufacturer $manuf.Manufacturer
$obj | Add-Member noteproperty Model $manuf.Model
$obj | Add-Member noteproperty CPU $cpu.Name
$obj | add-member noteproperty RAM $mem
$obj | add-member noteproperty HD $hd
$obj | Add-Member noteproperty Type $chassis
$obj | Add-Member noteproperty OS $OS.Caption
$obj | Add-Member noteproperty Arch $OS.OSArchitecture
Write-Output $obj
}

##Run function and export to csv
inventory | format-table
inventory | Export-Csv -NoTypeInformation $filepath\$name.csv

Tuesday, March 19, 2013

Simple Server Setup Automation - Powershell

I know this kind of goes against the theme of this blog (SCCM) but we don't use OSD for deploying Servers because we don't do it that often.

I wanted another reason to write some more powershell though so I wrote the following to automate some of the simple tasks that we do when setting up new servers.  It doesn't save us much time but it ensures that our Servers are all setup with the same set of "standard" options.


#Set Variables
 #License Key
 $Productkey = "xxxxx-xxxxx-xxxxx-xxxxx-xxxxx"
 #IE ESC Keys
 $AdminKey = "HKLM:\SOFTWARE\Microsoft\Active Setup\Installed Components\{A509B1A7-37EF-4b3f-8CFC-4F3A74704073}"
 $UserKey = "HKLM:\SOFTWARE\Microsoft\Active Setup\Installed Components\{A509B1A8-37EF-4b3f-8CFC-4F3A74704073}"

# Disable Windows Firewall
set-service -name "SharedAccess" -ComputerName - Status stopped -startuptype disabled

# Enable RDC
(Get-WmiObject Win32_TerminalServiceSetting -Namespace root\cimv2\TerminalServices).SetAllowTsConnections(1,1) | Out-Null
(Get-WmiObject -Class "Win32_TSGeneralSetting" -Namespace root\cimv2\TerminalServices -Filter "TerminalName='RDP-tcp'").SetUserAuthenticationRequired(0) | Out-Null

#Enter License Key and Activate
Function Register-Computer 
{  [CmdletBinding(SupportsShouldProcess=$True)] 
   param ([parameter()][ValidateScript({ $_ -match "^\S{5}-\S{5}-\S{5}-\S{5}-\S{5}$"})][String]$Productkey , 
          [String] $Server="."   )
 

    $objService = get-wmiObject -query "select * from SoftwareLicensingService" -computername $server 
    if ($ProductKey) { If ($psCmdlet.shouldProcess($Server , $lStr_RegistrationSetKey)) {
                           $objService.InstallProductKey($ProductKey) | out-null  
                           $objService.RefreshLicenseStatus()         | out-null  } 

    }   get-wmiObject -query  "SELECT * FROM SoftwareLicensingProduct WHERE PartialProductKey <> null
                                                                   AND ApplicationId='55c92734-d682-4d71-983e-d6ec3f16059f'
                                                                   AND LicenseIsAddon=False" -Computername $server |

      foreach-object { If ($psCmdlet.shouldProcess($_.name , "Activate product" )) 

                             { $_.Activate()                      | out-null 

                               $objService.RefreshLicenseStatus() | out-null

                               $_.get()
                               If     ($_.LicenseStatus -eq 1) {write-verbose "Product activated successfully."} 
                               Else   {write-error ("Activation failed, and the license state is '{0}'" ` 
                                                      -f $licenseStatus[[int]$_.LicenseStatus] ) }
                            If     (-not $_.LicenseIsAddon) { return } 

              }               
             else { write-Host ($lStr_RegistrationState -f $lStr_licenseStatus[[int]$_.LicenseStatus]) } 
    } 
}

#Disable IE ESC
    Set-ItemProperty -Path $AdminKey -Name "IsInstalled" -Value 0
    Set-ItemProperty -Path $UserKey -Name "IsInstalled" -Value 1
    Stop-Process -Name Explorer
#    Write-Host "IE Enhanced Security Configuration (ESC) has been disabled." -ForegroundColor Green

#Disable UAC
    Set-ItemProperty "HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\Policies\System" -Name "ConsentPromptBehaviorAdmin" -Value 00000000
 Set-ItemProperty -Path registry::HKEY_LOCAL_MACHINE\Software\Microsoft\Windows\CurrentVersion\Policies\System -Name EnableLUA -Value 0
#    Write-Host "User Access Control (UAC) has been disabled." -ForegroundColor Green

#Install Windows Server Backup (BareMetal)
Import-Module ServerManager 
Add-WindowsFeature Backup-Features -Include 
Add-PSSnapin Windows.ServerBackup


Tuesday, June 26, 2012

Hyper-V host - slow internet browsing

After setting up Hyper-V on Windows 8 I noticed that when my Domain Controller VM was turned on(hosting AD, DHCP and DNS) my host PC would take a long time to surf the internet.

I did a speed test and, after making the initial connection, saw that my download/upload speeds were normal I realized that it must be because I was hitting the DNS of my "Internal" DNS host on the VM.

Quick fix -
Open your network connections and hit the "alt" button.  Open Advanced - Advanced settings like so:



Then move your External Virtual Switch adapter connection to the top of the priority list like so:

This should restore your host Internet surfing abilities to normal.

Friday, June 22, 2012

Bitlocker recovery key didn't get uploaded to Active Directory

For some reason a laptop did not upload it's encryption key to Active Directory after bitlocker was enabled. I can only assume that it had lost network connectivity somehow.

So I needed to find a way to get the key into Active Directory manually after bitlocker was enabled and most of my google searches were of no help.

This is what I have come up with -
Start with a cmd prompt (ran as an administrator)
Enter the following command: manage-bde -protectors -adbackup C: -id {recoveryGUID}


You might be asking yourself what is the recoveryGUID???
The volume GUID can be found by executing the following:

  1. Right click the volume (ex. C: drive) that is bitlocker'ed and choose Manage BitLocker
  2. Choose save or print recovery key again
  3. Choose save to file
  4. We are looking for the "Full recovery key identification".  That is the GUID of the volume that you selected and is also the "id" used with the manage-bde command above.  Make sure you include the brackets with the ID
That should be it, double check in AD to make sure that the information for the recovery key has been populated in the computer object.


Tuesday, June 19, 2012

Accidentally deleted "All Systems" Collection

*somehow* the All Systems collection had gotten deleted.  I didn't really think anything of it until our HelpDesk system was unable to use it's Asset Inventory function because it was polling the SMS00001 collection.

With some help from Chris Nackers blog I found this vb script which restored the collection with the appropriate collection ID -


'###Begin Code

strSMSServer = "ENTER SERVERNAME HERE" 
strParentCollID = "COLLROOT" 
'This example creates the collection in the collection root. 
'Replace COLLROOT with the CollectionID of an existing collection to make the new collection a child.

strCollectionName = "All Systems" 
strCollectionComment = "This is the All Systems Collection." 
Set objLoc = CreateObject("WbemScripting.SWbemLocator") 
Set objSMS = objloc.ConnectServer(strSMSServer, "root\sms") 
Set Results = objSMS.ExecQuery ("SELECT * From SMS_ProviderLocation WHERE ProviderForLocalSite = true")

For each Loc in Results 
If Loc.ProviderForLocalSite = True Then 
  Set objSMS = objLoc.ConnectServer(Loc.Machine, "root\sms\site_" & Loc.SiteCode) 
End if 
Next

Set newCollection = objSMS.Get("SMS_Collection").SpawnInstance_()

'Create new "All Systems" collection 
newCollection.Name = "All Systems" 
newCollection.OwnedByThisSite = True 
newCollection.Comment = strCollectionComment 
newCollection.CollectionID = "SMS00001" 
path = newCollection.Put_

'Set the Relationship 
Set newCollectionRelation = objSMS.Get("SMS_CollectToSubCollect").SpawnInstance_() 
newCollectionRelation.parentCollectionID = strParentCollID 
newCollectionRelation.subCollectionID = ("SMS00001") 
newCollectionRelation.Put_

'###End Code

Then all I had to do was add my customized query, that removes discovered apple devices, into the collection and do an update/refresh and presto (You could remove the "where" part of the statement to get it back to original) -

select SMS_R_SYSTEM.ResourceID,SMS_R_SYSTEM.ResourceType,SMS_R_SYSTEM.Name,SMS_R_SYSTEM.SMSUniqueIdentifier,SMS_R_SYSTEM.ResourceDomainORWorkgroup,SMS_R_SYSTEM.Client
from SMS_R_System
where SMS_R_System.Name not like "%AD"
and  SMS_R_System.Name not like "%AL"

Saturday, May 26, 2012

Windows to Go for Windows 8 or Windows 8 Server (boot from USB)

I wanted to play around with Hyper-V on my laptop but didn't want to wipe Windows 7 to do it and I wasn't about to dual-boot.

Enter a cool new feature from the windows 8 family - "Windows to Go" .  Windows to Go allows you to install the Windows 8 family onto, that's right not from, a USB stick.

This process is the same for either Windows 8 (client) or Windows 8 Server

Tools used:

  • Most others say that you have to download Windows AIK (1.8gb) just to make use of imagex.exe but I have spoken about gimagex.exe before.  It's just a GUI wrapper for imagex and works well if you don't really like to memorize a bunch of command lines to image systems and it's FREE!
  • Either Windows 8 Consumer Edition ISO or Windows 8 Beta
  • A tool like WinRar to extract the files from the ISO
  • diskpart.exe


Hardware Required:

  • At least a 16Gb usb thumb drive.  You are going to want to purchase a usb 3.0 drive if you have the slots available as this is booting windows from the USB key.

Steps:

  1. Open command prompt and enter the following commands
    1. List Disk - This will show you a list of the physical disks that you have plugged into your computer.  Make note of the number that is your USB key
    2. Sel Disk 1 - where 1 is your USB stick
    3. Clean - wipes the drive out
    4. Create Partition Primary
    5. format fs=ntfs quick label=Win2Go
    6. active
    7. assign
    8. exit
  2. Extract the Windows 8 ISO to c:\extracted\win8 (or wherever you are comfortable with)
  3. Open gimagex.exe
  4. Select the Apply tab at the top
  5. Select the install.wim file from the extracted ISO - ie. c:\extracted\win8\sources\install.wim as the Source
  6. Select the drive letter of your freshly formatted USB key as the Destination
  7. Click Apply and wait :) 

  8. Once gimagex Apply reaches 100% open a command prompt and enter the following command:
    1. bcdboot f:\windows /s f:  - where f: is your usb key
That's it, your done!  Boot your computer off of your usb key and let setup complete.

Friday, May 11, 2012

Setting Local Admin account to not expire

So I was using this command - 
net user username password /expires:never /passwordchg:no /comment:"Desktop Support" /add
- to create the local administrator account during OSD but the password was still set to expire.

I guess I misunderstood the /expires:never switch.  This sets the account to never expire not the password.

So in addition to the aforementioned net user command I added a wmic command that sets the password to never expire:

wmic path Win32_UserAccount WHERE Name="username" set PasswordExpires=False

Remote Mailboxes - Hybrid Config - Missing

The Remote Mailbox exists on the On Prem Exchange server and linked to the Office 365 mailbox. Without one of these for each Office 365 mail...