Windows 2012 – CLI

Activating Windows 2012 with powershell:

(or use sconfig)

slmgr.vbs –ipk <productkey>
slmgr.vbs –ato

 

Rename the sever:
  • Determine the current name of the server with the hostname or ipconfig command.
  • In Windows PowerShell, run Rename-Computer.
  • Restart the computer.

 

Installing GUI with powershell:

(or use sconfig)

Install-WindowsFeature Server-Gui-Shell, Server-Gui-Mgmt-Infra

An other option is to use dism

Dism /online /enable-feature /featurename:ServerCore-FullServer /featurename:Server-Gui-Shell /featurename:Server-Gui-Mgmt

If this fail, you need to mount the files.

1. Create a folder to mount WIM (mkdir c:\mountdir)

2. Check the index number needed for a server with GUI image (where d is the DVD drive)

dism /get-wiminfo /Wimfile: d:\sources\install.wim

We want to install the SERVERSTANDARD so the index number will be 2

3. Mount the WIM for Server Standard:

dism /mount-wim /wimfile: d:\sources\install.wim /Index:2 /mountdir:c:\mountdir /readonly

4. Start powershell and execute:

Install-WindowsFeature Server-Gui-Mgmt-Infra, Server-Gui-Shell –restart –source c:\mountdir\windows\winsxs

5. Restart the server

 

 

Remove the GUI with powershell:
Uninstall-WindowsFeature Server-Gui-Shell, Server-Gui-Mgmt-Infra

 

SCONFIG

Use SCONFIG to configure a lot of options (domain/Computername/updates/nic/…)

 

For other options to remove/install the GUI look at http://www.howtogeek.com/111967/how-to-turn-the-gui-off-and-on-in-windows-server-2012/

Configure a Server Core Server: http://technet.microsoft.com/en-us/library/jj592692.aspx#BKMK_1_5

Script – Get HP Serial Numbers

To get a list of HP Serial numers run the following Powershell script. Place the servernames/ipaddresses you want to check in the serverlist parameter.

 

#
# Get HP Serial Numbers from server text file
#
# Written by Bastiaan van Leeuwen
#
# Change $serverlist parameter to the right text file

$serverlist = "d:\script\servers.txt"
$username = Get-Credential domain\user

foreach($server in get-content $serverlist)
{
gwmi win32_systemenclosure -computer "$server" -credential $username –ErrorAction SilentlyContinue | 
select __SERVER,serialnumber
}

 

SCRIPT – Computer Inventory

The Computer Inventory Script enumerates Hardware, OS, System, Processor, Memory, Disk, and Network information and neatly organizes it in an Excel file. I’ve provided Version 2 of the script that allows you to choose a number of computer resources; all computers in the domain, all servers in the domain, computers from a list maintained in a text file, and the ability manually pick a computer. Version 2 of the PowerShell script also allows you to send credential information should you wish to logon the remote computer with an alternative user account. This is helpful for DMZ servers as well as stand alone servers that are not members of your domain.

source: http://www.powershellpro.com/why-i-no-longer-hate-writing-documentation/614/

 

[wpdm_file id=78]

Backup en restore windows FSRM Quotas

To get a list of quota’s in a text file: dirquota q l > all_quotas.txt

To backup the complete quota database first stop the FSRM services, copy the SRM directory and restart the FSRM services. To be able to copy the SRM directory you need rights on the System Volume Information directory.

 

1. Stop the FSRM services

net stop srmSvc
net stop srmReports
net stop quota
net stop Datascrn

2. Copy SRM for the disk you want to a backup folder, or restore them from a backup folder

3. Start the FSRM services

net start Datascrn
net start quota
net start srmReports
net start srmSvc

 

 

 

IBM Storage replace Disk

If you replace a disk in an IBM Storage, such as a DS4700 and the disk is not rebuilding and is instead a new disk. You can set the disk as a replacement disk with the following command:

replace drive [85,12] replacementDrive=85,12;

 

To put the hot spare which was in use back to a hot spare, use the following command:

set drive [0,1] hotSpare=TRUE

 

This can be done in the Main storage manager view. Highlight the system, right mouse click and choose “Execute Script …”. Put in the commands and select “Tools” –> “Verify and Execute”.

Your initial lun will rebuild and your hot spare will fall back to the hot spare.

 

Get Server Uptime Using WMI

Retrieve Server Uptime

Uses the WMI to pull system uptime with WMI timeouts, it will useful when remote WMI not responding.

I have used it for a few hundred servers and it works fine. The initial test-connection uses only 1 ping, so that it can go through a large list of servers very easily.

If you found any bug then report to [email protected]

# Writer = Ritesh Parab; fb.com\parab.ritesh   
# File Name = Get-uptime 1.2 
# WMI Query time function added {Thanks to Technet forum} 

cls                                              
$erroractionpreference = "SilentlyContinue" 
# Helper Function - convert WMI date to TimeDate object 
function WMIDateStringToDate($Bootup) { 
 [System.Management.ManagementDateTimeconverter]::ToDateTime($Bootup) 
} 

# Main script 
$Computer = Get-Content "c:\Servers.txt" 

foreach ($system in $Computer) { 
$rtn = Test-Connection -ComputerName $system -Count 1 -BufferSize 16 -Quiet 
         IF($rtn -match 'True') { 
        $NameSpace = "Root\CIMV2" 
        $wmi = [WMISearcher]"" 
         $wmi.options.timeout = '0:0:15' #set timeout to 10 seconds 
         $query = 'Select * from Win32_OperatingSystem' 
         $wmi.scope.path = "\\$system\$NameSpace" 
         $wmi.query = $query 
          Try{ 
          $wmiresult = $wmi.Get() 
          #    $wmiresult 
            foreach ($wmioutput in $wmiresult){ 
               $Bootup = $wmioutput.LastBootUpTime 
               $LastBootUpTime = WMIDateStringToDate($Bootup) 
               $now = Get-Date 
               $Uptime = $now - $lastBootUpTime 
               $d = $Uptime.Days 
               $h = $Uptime.Hours 
               $m = $uptime.Minutes 
               $ms= $uptime.Milliseconds 
               $a = "$System Up for: {0} days, {1} hours, {2}.{3} minutes" -f $d,$h,$m,$ms 
               Write-Host "$a" -ForegroundColor Green 
                 } 
              } 
        Catch { 
                  Write-host "WMI not available on : $System" -ForegroundColor Red 
                Write-Output "WMI failed on $system because : $_" | Out-File "d:\failed.txt" -Force -Append  
          } 
        } 
        else{ 
            write-host "$system Offline" -ForegroundColor DarkRed 
            Write-Output "$system Offline" | Out-File 'd:\wintech\Get-Uptime\failed.txt' -Force -Append  
        } 
    }

http://gallery.technet.microsoft.com/scriptcenter/Get-Server-Uptime-Using-WMI-15aaa8ac

Determine when each user in the domain last logged on.

Run the following powershell script to determine the last logon date from the AD users.

Output will be written to c:\users.txt

# PSLastLogon.ps1
# PowerShell script to determine when each user in the domain last
# logged on.
#
# ----------------------------------------------------------------------
# Copyright (c) 2011 Richard L. Mueller
# Hilltop Lab web site - http://www.rlmueller.net
# Version 1.0 - March 16, 2011
#
# This program queries every Domain Controller in the domain to find the
# largest (latest) value of the lastLogon attribute for each user. The
# last logon dates for each user are converted into local time. The
# times are adjusted for daylight savings time, as presently configured.
#
# You have a royalty-free right to use, modify, reproduce, and
# distribute this script file in any way you find useful, provided that
# you agree that the copyright owner above has no warranty, obligations,
# or liability for such use.

Trap {"Error: $_"; Break;}
$file = "c:\users.txt"
$D = [System.DirectoryServices.ActiveDirectory.Domain]::GetCurrentDomain()
$Domain = [ADSI]"LDAP://$D"
$Searcher = New-Object System.DirectoryServices.DirectorySearcher
$Searcher.PageSize = 200
$Searcher.SearchScope = "subtree"

$Searcher.Filter = "(&(objectCategory=person)(objectClass=user))"
$Searcher.PropertiesToLoad.Add("distinguishedName") > $Null
$Searcher.PropertiesToLoad.Add("lastLogon") > $Null

# Create hash table of users and their last logon dates.
$arrUsers = @{}

# Enumerate all Domain Controllers.
ForEach ($DC In $D.DomainControllers)
{
    $Server = $DC.Name
    $Searcher.SearchRoot = "LDAP://$Server/" + $Domain.distinguishedName
    $Results = $Searcher.FindAll()
    ForEach ($Result In $Results)
    {
        $DN = $Result.Properties.Item("distinguishedName")
        $LL = $Result.Properties.Item("lastLogon")
        If ($LL.Count -eq 0)
        {
            $Last = [DateTime]0
        }
        Else
        {
            $Last = [DateTime]$LL.Item(0)
        }
        If ($Last -eq 0)
        {
            $LastLogon = $Last.AddYears(1600)
        }
        Else
        {
            $LastLogon = $Last.AddYears(1600).ToLocalTime()
        }
        If ($arrUsers.ContainsKey("$DN"))
        {
            If ($LastLogon -gt $arrUsers["$DN"])
            {
                $arrUsers["$DN"] = $LastLogon
            }
        }
        Else
        {
            $arrUsers.Add("$DN", $LastLogon)
        }
    }
}

# Output latest last logon date for each user.
$Users = $arrUsers.Keys
ForEach ($DN In $Users)
{
    $Date = $arrUsers["$DN"]
    "$DN;$Date" | Out-File $file -Append
}

Original script (without export to file) from: http://www.rlmueller.net/PowerShell/PSLastLogon.txt

Sample PowerShell Scripts with OMSA

(http://en.community.dell.com/techcenter/systems-management/w/wiki/sample-powershell-scripts-with-omsa.aspx)

sample Function to launch DRAC, based on computer name

Below are sample PowerShell scripts for querying data from OMSA – download the attached .txt file for all the examples.

get-wmiobject -namespace root\cimv2\dell -computer Server1 -list | sort-object name Displays all classes int he root\cimv2\dell namespace on Server1
$a = get-wmiobject dell_chassis -namespace root\cimv2\dell -computer Server1
$a | select-object AmpStatus, EsmLogStatus, FanRedStatus, FanStatus, MemStatus, Model, ProcStatus, PsRedStatus, PsStatus, SecurityBreach, SerialNumber, Status, SystemClass, TempStatus, VoltStatus, VrmStatus
Displayoverall hardware status based on info from Dell_Chassis
$a = get-wmiobject Dell_baseboard -namespace root\cimv2\dell -computer Server1
$a.PartNumber, $a.BaseBoardTypeDescString
Display the part number of the motherboard
$a = get-wmiobject cim_PhysicalMemory -namespace root\cimv2\dell -computer Server1
$a | select-object capacity, datawidth, formfactor, memorytype, name, speedasstring, status, tag, totalwidth | format-table
Displays Physical Memory information (speed, type, etc)
$a = get-wmiobject cim_temperaturesensor -namespace root\cimv2\dell -computer Server1
$a | select-object baseunits, CurrentReading, LowerThresholdCritical, LowerThresholdNonCritical, name, status, unitmodifier, upperthresholdcritical,upperthresholdnoncritical
Show Current Temperature sensor information (CurrentReading in Celsius)
get-wmiobject cim_tachometer -namespace root\cimv2\dell -computer Server1 | select-object Name, CurrentReading Displays Current Fan Speed
get-wmiobject cim_fru -namespace root\cimv2\dell -computer Server1 | select-object DeviceID, FRUManufacturerName, FRUPartNumberName, FRUSerialNumberName Displays “Field Replaceable Units” (FRU) information for specific components
get-wmiobject cim_powersupply -namespace root\cimv2\dell -computer Server1 | select-object name, DeviceID, Status, TotalOutputPower Displays the total output power of the supply – in milliwatts
get-wmiobject cim_processor -namespace root\cimv2\dell -computer Server1 | select-object CoreCount, CoreEnabledCount, CPUStatus, CurrentClockSpeed, DeviceID, MaxClockSpeed, Name | ft -autosize Displays processor information
get-wmiobject dell_networkport -namespace root\cimv2\dell -computer Server1 | select-object OSAdapterDescription, IsTOEEnable Displays if TCP Offload Engine (TOE) is enabled
$a = get-wmiobject DELL_PowerConsumptionData -namespace root\cimv2\dell -computer Server1
$a | select-object Name, CumulativePowerReading, maxPowerConsumption, minPowerConsumption, parStartTime, parTime, peakAmpReading, peakHeadRoom, peakWattReading, powerCap, powerCapCapabilities, pwrStartTime, pwrTime, Status
Displays valuable power consumption information – shows “CumulativePowerReading based from pwrStartTime, as well as min/max power consumption, and peak amps, watts, etc.
get-wmiobject CIM_BIOSElement -namespace root\cimv2\dell -computer Server1 | select-object InstallDate, Name, Version Displays BIOS Version, and installation date
get-wmiobject CIM_BIOSElement -namespace root\cimv2\dell -computer Server1 | % {$_.ConvertToDateTime($_.InstallDate), $_.Name, $_.Version} Convert BIOS Install Date time to a friendly date/time
get-wmiobject DELL_Firmware -namespace root\cimv2\dell -computer Server1 | select-object Name, Version Displays DRAC Version information
get-wmiobject Dell_SoftwareFeature -namespace root\cimv2\dell -computer Server1 | select-object Description, OmsaURL, Version Displays the OMSAURL used to connect to DRAC
function LaunchDrac($strComputerName)
{
$a = get-wmiobject Dell_SoftwareFeature -namespace root\cimv2\dell -computer $strComputerName | select-object Description, OmsaURL, Version
$ie = new-object -comobject InternetExplorer.Application
$ie.visible = $true
$ie.navigate(($a.omsaurl.split(‘,’))[0])
}
sample Function to launch DRAC, based on computer name

Check FSMO Roles

Run the following vbs script to show you the location off the FSMO roles:

 

Set objRootDSE = GetObject("LDAP://rootDSE")

Set objSchema = GetObject _
    ("LDAP://" & objRootDSE.Get("schemaNamingContext"))
strSchemaMaster = objSchema.Get("fSMORoleOwner")
Set objNtds = GetObject("LDAP://" & strSchemaMaster)
Set objComputer = GetObject(objNtds.Parent)
WScript.Echo "Forest-wide Schema Master FSMO: " & objComputer.Name

Set objNtds = Nothing
Set objComputer = Nothing

Set objPartitions = GetObject("LDAP://CN=Partitions," & _
    objRootDSE.Get("configurationNamingContext"))
strDomainNamingMaster = objPartitions.Get("fSMORoleOwner")
Set objNtds = GetObject("LDAP://" & strDomainNamingMaster)
Set objComputer = GetObject(objNtds.Parent)
WScript.Echo "Forest-wide Domain Naming Master FSMO: " & objComputer.Name

Set objDomain = GetObject _
    ("LDAP://" & objRootDSE.Get("defaultNamingContext"))
strPdcEmulator = objDomain.Get("fSMORoleOwner")
Set objNtds = GetObject("LDAP://" & strPdcEmulator)
Set objComputer = GetObject(objNtds.Parent)
WScript.Echo "Domain's PDC Emulator FSMO: " & objComputer.Name

Set objRidManager = GetObject("LDAP://CN=RID Manager$,CN=System," & _
    objRootDSE.Get("defaultNamingContext"))
strRidMaster = objRidManager.Get("fSMORoleOwner")
Set objNtds = GetObject("LDAP://" & strRidMaster)
Set objComputer = GetObject(objNtds.Parent)
WScript.Echo "Domain's RID Master FSMO: " & objComputer.Name

Set objInfrastructure = GetObject("LDAP://CN=Infrastructure," & _
    objRootDSE.Get("defaultNamingContext"))
strInfrastructureMaster = objInfrastructure.Get("fSMORoleOwner")
Set objNtds = GetObject("LDAP://" & strInfrastructureMaster)
Set objComputer = GetObject(objNtds.Parent)
WScript.Echo "Domain's Infrastructure Master FSMO: " & objComputer.Name

 

download link: [wpdm_file id=49]

Delete files older then n days (VBS)

Here is a VBS script to delete all file older then 10 days in d:\backup.

Set the active constraint to “True” if you want to delete the files.

 

Const Active = False
Const sSource = "d:\backup"
Const MaxAge = 10 'days
Const Recursive = True

Checked = 0
Deleted = 0

Set oFSO = CreateObject("Scripting.FileSystemObject")
if active then verb = "Deleting """ Else verb = "Old file: """
CheckFolder oFSO.GetFolder(sSource)

WScript.echo
if Active then verb = " file(s) deleted" Else verb = " file(s) would be
deleted"
WScript.Echo Checked & " file(s) checked, " & Deleted & verb

Sub CheckFolder (oFldr)
For Each oFile In oFldr.Files
Checked = Checked + 1
If DateDiff("D", oFile.DateLastModified, Now()) > MaxAge Then
Deleted = Deleted + 1
WScript.Echo verb & oFile.Path & """"
If Active Then oFile.Delete
End If
Next

if not Recursive then Exit Sub
For Each oSubfolder In oFldr.Subfolders
CheckFolder(oSubfolder)
Next
End Sub