Showing posts with label Powershell. Show all posts
Showing posts with label Powershell. Show all posts

Wednesday, April 30, 2014

Excel - Format Data Cell for kb/mb/gb

Have you ever exported a powershell script only to see values like 876755433?

Have you ever wanted an easy way to format that number auto-magically into a kb's mb's or gb's?

Use the following process:

In Excel
Select the column needed to format
Right click column header
Choose "Format Cells"
Choose the "Custom" option under the "Number" tab
Paste this value - [<1000]#,##0.00" KB ";[<1000000]#,##0.00," MB";#,##0.00,," GB"
And click OK


MAGIC!

Monday, April 21, 2014

Remote DNS Check

In moving our data center the request was made to identify all servers with static IP's that had DNS entries of servers that we were being decommissioned.
This is what I used -
param( 
  [parameter(ValueFromPipeline=$TRUE)] 
    [String[]] $ComputerName=$Env:COMPUTERNAME, 
    [System.Management.Automation.PSCredential] $Credential 
) 
 
begin { 
  $PipelineInput = (-not $PSBOUNDPARAMETERS.ContainsKey("ComputerName")) -and (-not $ComputerName) 
 
  # Outputs the computer name, IP address, and DNS and WINS settings for 
  # every IP-enabled adapter on the specified computer that's configured with 
  # an IPv4 address. 
  function Get-IPInfo($computerName) { 
    $params = @{ 
      "Class" = "Win32_NetworkAdapterConfiguration" 
      "ComputerName" = $computerName 
      "Filter" = "IPEnabled=True" 
    } 
    if ( $Credential ) { $params.Add("Credential", $Credential) } 
    get-wmiobject @params | foreach-object { 
      foreach ( $adapterAddress in $_.IPAddress ) { 
        if ( $adapterAddress -match '(\d{1,3}\.){3}\d{1,3}' ) { 
          foreach ( $dnsServerAddress in $_.DNSServerSearchOrder ) { 
            new-object PSObject -property @{ 
              "ComputerName" = $_.__SERVER 
              "IPAddress" = $adapterAddress 
              "DNSServer" = $dnsServerAddress 
            } | select-object ComputerName,IPAddress,DNSServer 
          } 
        } 
      } 
    } 
  } 
} 
 
process { 
  if ( $PipelineInput ) { 
    Get-IPInfo $_ 
  } 
  else { 
    $ComputerName | foreach-object { 
      Get-IPInfo $_ 
    } 
  } 
}

Gather all 5 FSMO Roles with Powershell

<#
This simple script will pole your domain for the 5 FSMO roles
#>
import-module activedirectory
$fqdn = Read-Host 'Domain Name'
$forest = get-adforest $fqdn | Format-Table SchemaMaster,DomainNamingMaster
$domain = get-addomain $fqdn | Format-Table PDCEmulator,RIDMaster,InfrastructureMaster
$info = $forest,$domain
$info

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


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