A N

August 31, 2016

Manage Windows Services with Powershell

Filed under: Tips — donrsh @ 9:58 am

Manage Windows Services with Powershell. With this script you can connect to a server(s) and change logon account or just show the services.

#REQUIRES -Version 4.0
<#
	.NOTES
	===========================================================================
	 Created on:   	2016-08-30
	 Created by:   	Arash Nabi - arash@nabi.nu
	 Created for:	-
	===========================================================================
 
	.SYNOPSIS
		Manage service accounts
	
	
	.EXAMPLE
        
        PS C:\WINDOWS> Set-Service -Servers Server001,Server002,Server003 -ServiceName fake* -UpdateServices
        WARNING: No Service with name fake* found in Server003 


        Name         DisplayName        ServerName PathName               StartMode    State  
        ----         -----------        ---------- --------               ---------    -----  
        Fake         Fake Service       Server001  C:\windows\notepad.exe DC\SysScript Stopped
        Fake         Fake Service       Server002  C:\windows\notepad.exe DC\SysScript Stopped
        
     
    .EXAMPLE
             
        PS C:\WINDOWS> Set-Service -Servers Server001,Server002,Server003 -ServiceName fake* -ShowServices

        WARNING: No Service with name fake* found in Server003 

        DisplayName        State   StartName    SystemName
        -----------        -----   ---------    ----------
        Fake Service       Stopped DC\SysScript Server001   
        Fake Service       Stopped DC\SysScript Server002 
#>

function Set-Service
{
	[CmdletBinding()]
	param
	(
		[Parameter(Mandatory = $true)]
		$Servers,
		[Parameter(Mandatory = $true)]
		[string]$ServiceName,
		[switch]$ShowServices,
		[switch]$UpdateServices
	)
	
	Function Change-Service()
	{
		$cred = Get-Credential -Credential Domain\UserName
		$ServiceObj = @()
		foreach ($Server in $Servers)
		{
			# CIM stuff
			$objOption = New-CimSessionOption -Protocol Dcom
			$objSession = New-CimSession -ComputerName $server -SessionOption $objOption
			if ($objSession)
			{
				$params = @{
					'ServerName' = $Server
				}
				$getServices = Get-CimInstance win32_service -CimSession $objSession | Where-Object { $_.Name -like $ServiceName }
				if ($getServices)
				{
					foreach ($Service in $getServices)
					{
						$X = $Service | Invoke-CimMethod -Name Change -Arguments @{ StartName = "$($cred.UserName)"; StartPassword = "$($cred.Password)" }
						$ListService = Get-CimInstance win32_service -CimSession $objSession | Where-Object { $_.Name -like $ServiceName }
						$params.Add("DisplayName", "$($ListService.DisplayName)")
						$params.Add("StartMode", "$($ListService.StartName)")
						$params.Add("Name", "$($ListService.Name)")
						$params.Add("State", "$($ListService.State)")
						$params.Add("PathName", "$($ListService.PathName)")
					}
					$ServiceObj += New-Object psObject -Property $params
				}
				else
				{
					Write-Warning -Message "No Service with name $serviceName found in $server"
				}
				
			}
			else
			{
				Write-Warning -Message "ohh nooo! No Session established to $server"
			}
		}
		
		$ServiceObj | Select-Object -Property Name, DisplayName, ServerName, PathName, StartMode, State | Format-Table -AutoSize
	}
	
	if ($UpdateServices)
	{
		Change-Service
	}
	
	
	
	if ($ShowServices)
	{
		foreach ($Server in $servers)
		{
			$objOption = New-CimSessionOption -Protocol Dcom
			$objSession = New-CimSession -ComputerName $server -SessionOption $objOption
			if ($objSession)
			{
				$ListServices = Get-CimInstance win32_service -CimSession $objSession | Where-Object { $_.Name -like $ServiceName } |
				Select-Object -Property DisplayName, State, StartName, SystemName
				if ($ListServices)
				{
					$ListServices
				}
				else
				{
					Write-Warning -Message "No Service with name $serviceName found in $server `n"
				}
			}
			else
			{
				Write-Warning -Message "ohh nooo! No Session established to $server"
			}
			
		}
	}
}

June 10, 2016

Convert RoboCopy log details to Powershell Object

Filed under: Tips — donrsh @ 11:53 am
<#	
	 Created on:   	2016-06-08 
	 Created by:   	Arash Nabi
	 Email: 	arash@nabi.nu 
#>
$TimeDay = get-date -Format "yyyyMMdd"
$xResults = @()
$xErr = @()
foreach ($x in (get-childitem -path "C:\temp\log\$TimeDay"))
{
  

$LogFile = Get-Content -Path $x.FullName

foreach ($Lines in $LogFile)
{
	
	$Lines | Foreach {
        if ($_ -match 'ERROR :')
            { $xError = $_.SubString(8)
              $xTime  = $x.CreationTime  
                $P = [ordered]@{
				Error = $xError
                Time  = $xTime
                }
                $xErr += New-Object -TypeName PSObject -Property $P
            }
        
        if ($_ -match '   Source : ') { $Source = $_.Substring(12, $_.Length - 12) }
		if ($_ -match '     Dest : ') { $Destination = $_.Substring(12, $_.Length - 12) }
		if ($_ -match '    Dirs :')
		{
			$DirTotal = [Long]$_.Substring(12, 10).Trim()
			$DirCopied = [Long]$_.Substring(22, 10).Trim()
			$DirFailed = [Long]$_.Substring(52, 10).Trim()
		}
		if ($_ -match '   Files : ' -and $_.Length -gt 60)
		{
			$FileTotal = [Long]$_.Substring(12, 10).Trim()
			$FileCopied = [Long]$_.Substring(22, 10).Trim()
			$FileFailed = [Long]$_.Substring(52, 10).Trim()
		}
		if ($_ -match '   Times :') { $Duration = [TimeSpan]$_.Substring(12, 10).Trim() }
		if ($_ -match '   Ended : ')
		{
			$Ended = $_.Substring(11, $_.Length - 11).Trim()
			$Properties = [ordered]@{
				Source = $Source
				Destination = $Destination
				DirTotal = $DirTotal
				NewDirCopied = $DirCopied
				DirFailed = $DirFailed
				FileTotal = $FileTotal
				NewFileCopied = $FileCopied
				FileFailed = $FileFailed
				Ended = $Ended
                }
			$xResults += New-Object -TypeName PSObject -Property $Properties
		}
	}


}
}
$xResults | Format-Table -AutoSize

RoboCopy Powershell Object Results

RoboCopy – Copy files from source to destination with x days old

Filed under: Tips — donrsh @ 11:47 am
<#	
	.NOTES
	===========================================================================
	 Created on:   	2016-06-08 
	 Created by:   	Arash Nabi
	 Email: 	arash@nabi.nu 

	===========================================================================
	.DESCRIPTION
     # /SEC           - Copies files with security
     # /R:1           - Specifies the number of retries on failed copies.
     # /W:1           - Specifies the wait time between retries, in seconds.
     # /NP            - Specifies that the progress of the copying operation (the number of files or directories copied so far) will not be displayed.
     # /FP            - Includes the full path names of the files in the output.
     # /V             - Produces verbose output, and shows all skipped files.
     # /MOVE          - Moves files and directories, and deletes them from the source after they are copied.
     # /maxage:<N>    - Specifies the maximum file age (to exclude files older than N days or date).
     # /log:<LogFile> - Writes the status output to the log file (overwrites the existing log file).
     # /minage:<N>    - Specifies the minimum file age (exclude files newer than N days or date).
     # /L             - Specifies that files are to be listed only (and not copied, deleted, or time stamped).	
     # /S             - Copies subdirectories. Note that this option excludes empty directories.
     # /FP            - Includes the full path names of the files in the output.
     # /NC            - Specifies that file classes are not to be logged.
     # /TS            - Includes source file time stamps in the output.
	 	
#>



$Time = (get-date -Format T).Replace(':','.')
$TimeDay = get-date -Format "yyyyMMdd"
$DateMonth = get-date -Format "yyyyMM" 
$Y = New-Item -Path "c:\temp\log\" -ItemType Directory -Name $TimeDay -Force
$Log = "C:\temp\log\$TimeDay\LogTime-$Time.txt" 
$MinAgeDate = (get-date).AddDays(-2) | get-date -Format "yyyyMMdd" 
$Dir = 'C:\temp\Archive\'
$Destination = 'C:\temp\Archive2'
$RoboCopyList = Invoke-Expression -Command  "Robocopy $Dir $Destination\$DateMonth /S /COPYALL /MINAGE:$MinageDate /MOV /R:10 /W:5 /TS /NFL /ETA /LOG+:$log"

April 7, 2016

Create ODBC Connection with Powershell

Filed under: Tips — donrsh @ 8:55 am

Create ODBC Connection with Powershell.


<#
	 Created on:   	2016-04-07 
	 Created by:   	Arash Nabi
	 Email: 	    arash@nabi.nu 

#>


<#
	
    .SYNOPSIS
		Create ODBC Connection
	
	.DESCRIPTION
		Create ODBC Connection
	
	.PARAMETER SQLserver
		Provide a SQLserver with instance name. Ex SQLserver\InstanceName
	
	.PARAMETER Databases
		A description of the Databases parameter.
	
	.PARAMETER DsnType
		Data Source Name type
	
	.PARAMETER Platform
		X86 or X64 platform
	
	.PARAMETER DriverName
		An ODBC driver allows ODBC-enabled programs to get information from ODBC data sources.
	
	.PARAMETER Name
		A description of the Name parameter.
	
	.EXAMPLE
		PS C:\>  Create-ODBC -SQLserver SQLserver\InstanceName -Databases DBname -DsnType System -Platform 64-bit -Verbose
	
	.NOTES
		Additional information about the function.
#>
function Create-ODBC
{
	[CmdletBinding()]
	param
	(
		$SQLserver,
		$Databases,
		[ValidateSet('System', 'User')]
		$DsnType,
		[ValidateSet('64-bit', '32-bit')]
		$Platform
	)
	
	try
	{
		foreach ($Database in $Databases)
		{
			Add-OdbcDsn -Name $Database -DriverName "SQL Server Native Client 11.0" -DsnType $DsnType -Platform $Platform -SetPropertyValue @("Server=$SQLserver", "Trusted_Connection=Yes", "Database=$Database") -ErrorAction SilentlyContinue -PassThru
		}
	}
	catch [System.IO.IOException] {
		$_.Exception.Message
	}
	
	finally
	{
		Write-Verbose -Message "End of script"
	}
}



March 7, 2016

SCOM – Show and Start MaintenanceMode

Filed under: Tips — donrsh @ 2:49 pm
#REQUIRES -Version 4.0
<# .NOTES
	===========================================================================
	Created on:   	2016-03-07
	Created by:   	Arash Nabi - arash@nabi.nu
	===========================================================================
#>

<#
	.SYNOPSIS
		Invoke a command to SCOM Server
	
	.DESCRIPTION
		The Invoke-SCOM function uses SCOM Module to connect to SCOM Server and Show if a server is in maintenance mode,
		put a server in maintenance mode, show if a Web Watcher is in maintenance mode or put a Web Watcher in maintenance mode.
	
	.PARAMETER ShowInMaintenanceModeServer
		Selecting this parameter will show you Maintenance mode of a server or servers.
	
	.PARAMETER StartMaintenanceModeServer
		Selecting this parameter will start Maintenance mode of a server or serves, if the server is in maintenance mode
		it will update it with the new entries you entered.
	
	.PARAMETER ComputerName
		ComputerName should be entered either with .hm.com or without. The script is smart enough to check and add domain
		prefix if doesn´t have.
	
	.PARAMETER Minutes
		Minutes should be entred as integer, minimum 10 minutes.
	
	.PARAMETER Reason
		The reason parameter is predefined values. Choose the one that fits.
	
	.PARAMETER Comment
		The comment parameter should be entered in quotation mark, otherwise you will get error.
	
	
	.EXAMPLE
		Invoke-SCOM -ShowInMaintenanceModeServer -ComputerName SERVER001,SERVER002
		
		Show if a server(s) is in Maintenance mode or not.
		
		HealthState     InMaintenanceMode  DisplayName
		-----------     -----------------  -----------
		Error                 False        SERVER001.DOMAIN.COM
		Success               False        SERVER002.DOMAIN.COM
	
	.EXAMPLE
		Invoke-SCOM -StartMaintenanceModeServer -ComputerName SERVER001,SERVER001 -Minutes 10 -Reason PlannedOther -Comment "Some text comments here..."
		Put a server(s) in Maintenance mode. If the server is in maintenance mode, the records will be updated.
		
		VERBOSE: SERVER001.DOMAIN.COM is not in maintenance mode. Starting maintenance mode...
		
		
		StartTime        : 2016-03-07 12:15:42
		ScheduledEndTime : 2016-03-07 12:25:32
		Reason           : PlannedOther
		Comments         : Some text comments here...
		User             : DOMAIN\USERNAME
		
		VERBOSE: SERVER002.DOMAIN.COM is not in maintenance mode. Starting maintenance mode...
		StartTime        : 2016-03-07 12:15:42
		ScheduledEndTime : 2016-03-07 12:25:32
		Reason           : PlannedOther
		Comments         : Some text comments here...
		User             : DOMAIN\USERNAME
	
	.NOTES
		Additional information about the function.
#>
function Invoke-SCOM
{
	[CmdletBinding(DefaultParameterSetName = 'MaintenanceModeServer')]
	[OutputType([int])]
	param
	(
		[Parameter(ParameterSetName = 'ShowOnlyMaintenanceModeServers',
				   Mandatory = $true,
				   ValueFromPipeline = $true,
				   ValueFromPipelineByPropertyName = $true,
				   Position = 0)]
		[switch]$ShowInMaintenanceModeServer,
		[Parameter(ParameterSetName = 'MaintenanceModeServer',
				   Mandatory = $false,
				   Position = 0)]
		[switch]$StartMaintenanceModeServer,
		[Parameter(ParameterSetName = 'MaintenanceModeServer',
				   Mandatory = $true)]
		[Parameter(ParameterSetName = 'ShowOnlyMaintenanceModeServers',
				   Mandatory = $true)]
		$ComputerName,
		[Parameter(ParameterSetName = 'MaintenanceModeServer')]
		[int]$Minutes,
		[Parameter(ParameterSetName = 'MaintenanceModeServer')]
		[ValidateSet('ApplicationInstallation', 'ApplicationUnresponsive', 'ApplicationUnstable', 'LossOfNetworkConnectivity', 'PlannedApplicationMaintenance', 'PlannedHardwareInstallation', 'PlannedHardwareMaintenance', 'PlannedOperatingSystemReconfiguration', 'PlannedOther', 'SecurityIssue', 'UnplannedApplicationMaintenance', 'UnplannedHardwareInstallation', 'UnplannedHardwareMaintenance', 'UnplannedOperatingSystemReconfiguration', 'UnplannedOther')]
		[string]$Reason,
		[Parameter(ParameterSetName = 'MaintenanceModeServer',
				   Mandatory = $true)]
		[string]$Comment
	)
	
	Begin
	{
		$VerbosePreference = 'Continue'
		$SCOMServer = "ScomServer"
		$GetModule = Get-Module -Name 'OperationsManager'
		
		if (-not $GetModule)
		{
			$ScomModule = Get-Module -ListAvailable | Where-Object { $_.Name -like 'OperationsManager' }
			if ($ScomModule)
			{
				Write-Verbose -Message "OperationsManager exist in $env:COMPUTERNAME"
				Import-Module -Name 'OperationsManager' -Verbose
				New-SCOMManagementGroupConnection -ComputerName $SCOMServer -Verbose
			}
			else
			{
				[void][System.Windows.Forms.MessageBox]::Show("OperationsManager module does not exist", "Warning!")
				Break
			}
			
		}
		
		
	}
	Process
	{
		try
		{
			$end = ((get-date).AddMinutes($minutes))
			
			# Show All Servers Maintenance Mode
			if ($ShowInMaintenanceModeServer)
			{
				$instanceclass = Get-SCOMClass -Name 'Microsoft.Windows.Computer' -ErrorAction SilentlyContinue | Get-SCOMClassInstance
				foreach ($Computer in $ComputerName)
				{
					if (-not ($Computer -match ".domain.com"))
					{
						$computer = $($computer + ".domain.com")
					}
					$instance = $instanceclass | Where-Object { $_.DisplayName -match $Computer }
					$isMaint = $instance | Get-SCOMMaintenanceMode -ErrorAction SilentlyContinue | Select-Object -Property StartTime, ScheduledEndTime, Reason, Comments, User
					if ($isMaint)
					{
						Write-Host " "
						Write-Verbose -Message "$Computer"
						$isMaint
					}
					else
					{
						$instance
					}
					
				}
				
			}
			
			
			# Start Server Maintenance
			if ($StartMaintenanceModeServer)
			{
				$instanceclass = Get-SCOMClass -Name 'Microsoft.Windows.Computer' -ErrorAction SilentlyContinue | Get-SCOMClassInstance
				foreach ($Computer in $ComputerName)
				{
					if (-not ($Computer -match ".domain.com"))
					{
						$computer = $($computer + ".domain.com")
					}
					$instance = $instanceclass | Where-Object { $_.DisplayName -match $Computer }
					if ($instance.InMaintenanceMode -eq $false)
					{
						Write-Verbose -Message "$computer is not in maintenance mode. Starting maintenance mode..."
						Start-SCOMMaintenanceMode -Instance $instance -EndTime $end -Reason $Reason -Comment $Comment -ErrorAction SilentlyContinue
					}
					else
					{
						Write-Warning "$Computer is in maintenance mode. Updating with new entries you entered... "
						$instance | Get-SCOMMaintenanceMode -ErrorAction SilentlyContinue | Set-SCOMMaintenanceMode -EndTime $end -Reason $Reason -Comment $Comment -ErrorAction SilentlyContinue
						
					}
					$instance | Get-SCOMMaintenanceMode -ErrorAction SilentlyContinue | Select-Object -Property StartTime, ScheduledEndTime, Reason, Comments, User
				}
				
				
			}
			
			
			
		}
		
		catch [System.Net.WebException], [System.Exception]
		{
			$errorMessage = $_.Exception.Message
			Write-Warning  $errorMessage
		}
		finally
		{
			
		}
		
		
	}
	End
	{
	}
}


February 11, 2016

Get LastBootUpTime and Export to CSV

Filed under: Tips — donrsh @ 10:51 am
# Created by Arash Nabi / arash@nabi.nu
# Date: 2016-02-11

try
{
	$Source = "C:\temp\Serverlists\2.txt"
    $Export = "C:\temp\Serverlists\2.csv"
    $VerbosePreference = 'Continue'
    $xObj = @()
	$Servers = Get-Content -Path $Source
	
	foreach ($server in $servers)
	{		
		# CIM stuff
		$objOption = New-CimSessionOption -Protocol Dcom -ErrorAction SilentlyContinue
		$objSession = New-CimSession -ComputerName $server -SessionOption $objOption -ErrorAction SilentlyContinue
		if ($objSession)
		{
			$params = @{
			'ServerName' = $server
			}
			$LastReboot =  Get-CimInstance -CimSession $objSession -Namespace ROOT/cimv2 -ClassName Win32_OperatingSystem | select LastBootUpTime
			$params.Add('LastBootUptime',"$($LastReboot.LastBootUpTime)")
			# Create objects
			$objresult = New-Object psobject -Property $params
			# Add object to result
			$xObj += $objresult
			Write-Verbose -Message $server
		}
		else
		{
			Write-Warning "No CimSession connection to $server. Aborting"
		}
	}
	$xObj | Export-Csv -Path $Export -NoTypeInformation
}
catch [System.Net.WebException] #, [System.Exception]
{
	$errorMessage = $_.Exception
	Write-Warning -Message $errorMessage
}
finally
{
	Write-Verbose -Message 'End of Script'
}

February 4, 2016

Get content of larg files, replace and bulkimport into SQL

Filed under: Tips — donrsh @ 2:23 pm

I had a few and larg log files which was around 500 MB each and looked like this:

Login Succeeded	server38	admin	2013-07-11 16:10:35	1
..Logout Succeeded	server4438	admin1	2013-07-11 16:15:35	1
Login Succeeded	server4438	admin2	2013-07-11 16:18:14	1
..Logout Succeeded	server4438	admin	2013-07-11 16:24:05	1
Login Succeeded	server1106	admin1	2013-07-12 10:53:20	1
Login Succeeded	server1106	admin2	2013-07-12 11:34:29	1

[System.IO.File]::ReadAllLines Read More Here

$Files = Get-ChildItem  'C:\Files'
foreach ($File in $Files)
{
	$FullName = $File.FullName
	([System.IO.File]::ReadAllLines($FullName)) -replace ('..Logout Succeeded', 'Logout') -replace ('Login Succeeded', 'Login') |
	Out-File -FilePath 'C:\Files\Export.csv' -Append
}

The result is:

Login server38    admin   2013-07-11 16:10:35 1
Logout  server4438  admin1   2013-07-11 16:15:35 1
Login server4438  admin2   2013-07-11 16:18:14 1
Logout  server4438  admin   2013-07-11 16:24:05 1
Login server1106  admin1  2013-07-12 10:53:20 1
Login server1106  admin2  2013-07-12 11:34:29 1

Now lets bulk import it to SQL

-- 1
GO
CREATE TABLE CSVTest
(
            Event VARCHAR(40),
            CitrixServer VARCHAR(40),
            Username VARCHAR(40),
            "DateTime" VARCHAR(40),
            "status" VARCHAR(40)
)
GO

-- 2

BULK
INSERT CSVTest
FROM 'C:\Files\Export.csv'
WITH
(
FIELDTERMINATOR = '\t',
ROWTERMINATOR = '\n'
)
GO

--3

select [Event],[CitrixServer],[UserName],CONVERT(datetime,[DateTime]) [DateTime],[Status] into Logs from CSVTest

January 11, 2016

January-2016-scripting-games-puzzle | Get-UpTime

Filed under: Tips — donrsh @ 3:25 pm

My solution for January-2016-scripting-games-puzzle

Get-UpTime


<#	
	.NOTES
	===========================================================================
	 Created on:   	2016-01-11 08:28
	 Created by:   	Arash Nabi
	 Mail:          arash@nabi.nu 	
	===========================================================================
	.SYNOPSIS
		A brief description of the Get-UpTime function.
	
	.DESCRIPTION
		Get uptime of the remote server. This is 2016-January Scripting Games Puzzle
	    For more info please visist: http://powershell.org/wp/2016/01/02/january-2016-scripting-games-puzzle/
	.EXAMPLE
		PS C:\> Get-UpTime -ComputerName 
	    PS C:\> $value1 | Get-UpTime
#>

function Get-UpTime
{
	[CmdletBinding()]
	param
	(
		[Parameter(Mandatory = $false,
				   ValueFromPipeline = $true)]
		$ComputerName = $env:COMPUTERNAME
	)
	
	Process
	{
		try
		{
            $AllObj = @()
			foreach ($PC in $ComputerName)
			{
				$params = @{
					'ComputerName' = "$PC"
				}
                $PingComputer = Test-Connection -ComputerName $PC -ErrorAction SilentlyContinue
				if (-not ($PingComputer))
				{
					$params.Add("Status", "Offline")
					Write-Warning "$PC is Offline"
				}
				# 
				if ($PingComputer)
				{
					$objOption = New-CimSessionOption -Protocol Dcom -ErrorAction SilentlyContinue
					$objSession = New-CimSession -ComputerName $PC -SessionOption $objOption -ErrorAction SilentlyContinue
					if ($objSession)
					{
						$LastBootUpTime = Get-CimInstance -CimSession $objSession -Namespace ROOT/cimv2 -ClassName Win32_OperatingSystem | select LastBootUpTime
						if ($LastBootUpTime)
						{
							$upTime = New-TimeSpan -Start $($LastBootUpTime.LastBootUpTime) -End (get-date)
							$params.add("StartTime", "$($LastBootUpTime.LastBootUpTime)")
							$params.Add("Status", "OK")
							$params.Add("UpTime (Days)", "$($upTime.Days)")
						}
						
						if ($upTime -gt 30)
						{
							$params.add("MightNeedPatched", "Yes")
						}
						else
						{
							$params.add("MightNeedPatched", "No")
						}
					}
					else
					{
						$params.Add("Status", "Error")
					}
				}
				
				$objresult = New-Object psobject -Property $params
				$AllObj += $objresult
			}
			
		}
		
		catch [System.Net.WebException], [System.Exception]
		{
			$errorMessage = $_.Exception.Message
            Write-Warning -Message $errorMessage

		}
		finally
		{
			$AllObj | Select-Object ComputerName, StartTime, 'Uptime (Days)', Status, MightNeedPatched | Format-Table -AutoSize
		}
	}
	
}


	

December 11, 2015

Powershell – Get Disc Report

Filed under: Tips — donrsh @ 3:33 pm
<#	
	 Created on:   	2015-09-09 
	 Created by:   	Arash Nabi
	 Email: 	    arash@nabi.nu 
     
     Get disk report. Export the result to csv file for further tuning in Excel.
	
#>
try
{
	$VerbosePreference = 'Continue'
	$diskObj = @()
	$Servers = Get-Content -Path "C:\Servers.txt"
	
	foreach ($server in $servers)
	{		
		# CIM stuff
		$objOption = New-CimSessionOption -Protocol Dcom -ErrorAction SilentlyContinue
		$objSession = New-CimSession -ComputerName $server -SessionOption $objOption -ErrorAction SilentlyContinue
		if ($objSession)
		{
			$params = @{
			'ServerName' = $server
			}
			$allDisks = Get-CimInstance -CimSession $objSession -Namespace ROOT/cimv2 -ClassName Win32_Volume -ErrorAction SilentlyContinue | Where-Object { $_.Capacity -gt 1 } |
			select driveletter, capacity, freespace
			foreach ($disk in $alldisks)
			{
				$DisksizeGB = [math]::round($disk.capacity/1GB)
				$diskLetter = $disk.Driveletter.Replace(':', '')
				$DiskUsed = [math]::round(($disk.capacity - $disk.freespace) /1GB)
				$DiskFree = [math]::round(($disk.freespace /1GB))
				$percentFree = "{0:P1}" -f ($DiskFree/$DisksizeGB)
				$params.Add($("$diskLetter Drive"), $("($percentFree Free) Total $disksizeGB GB, Used $DiskUsed GB, Free $DiskFree GB"))
			}
			# Create objects
			$objresult = New-Object psobject -Property $params
			# Add object to result
			$diskObj += $objresult
			Write-Verbose -Message $server
		}
		else
		{
			Write-Warning "No CimSession connection to $server. Aborting"
		}
	}
	$diskObj | select Servername, 'C Drive', 'D Drive', 'F Drive', 'E Drive', 'G Drive' | Export-Csv -Path c:\export.csv -NoTypeInformation
}
catch [System.Net.WebException] #, [System.Exception]
{
	$errorMessage = $_.Exception
	Write-Warning -Message $errorMessage
}
finally
{
	Write-Verbose -Message 'End of Script'
}

October 8, 2015

Get server architecture with CimSession

Filed under: Tips — donrsh @ 12:26 pm
<#   
    .NOTES
    ===========================================================================
     Created on:    2015-10-08 
     Created by:    Arash Nabi
     Email:         arash@nabi.nu 
 
    ===========================================================================
    .DESCRIPTION 
        Get server architecture info through CimInstance.
        The function creates a new cimSession to a remote computer and collects
        server architecture information and then creats a powershell object of them.
    .Exampel
        PS C:\> Get-Architecture -Servers $value1
     
#>


function Get-Architecture
{
	[CmdletBinding()]
	[OutputType([int])]
	Param
	(
		[Parameter(Mandatory = $true,
				   ValueFromPipelineByPropertyName = $false,
				   Position = 0)]
		$Servers
		
		
	)
	
	Process
	{
		try
		{
			$serverarch_obj = @()
			
			foreach ($server in $servers)
			{
				
				# CIM stuff
				$objOption = New-CimSessionOption -Protocol Dcom -ErrorAction Stop
				$objSession = New-CimSession -ComputerName $server -SessionOption $objOption -ErrorAction Stop
				
				$WinOS = Get-CimInstance -CimSession $objSession -Namespace ROOT/cimv2 -ClassName Win32_OperatingSystem -ErrorAction Stop
				$Model = (Get-CimInstance -CimSession $objSession -Namespace ROOT/cimv2 -ClassName Win32_ComputerSystem -ErrorAction Stop ).Model
				$IP    = (Get-CimInstance -CimSession $objSession -Namespace ROOT/cimv2 -ClassName Win32_NetworkAdapterConfiguration -ErrorAction Stop | 
                    where { $_.ipaddress -like "1*" } | select -ExpandProperty ipaddress | select -First 1 -ErrorAction SilentlyContinue)
				$CPU   = Get-CimInstance -CimSession $objSession -Namespace ROOT/cimv2 -ClassName Win32_Processor -ErrorAction Stop
				
				
				$params = @{
					'ServerName'        = $server
					'Architecture'      = $WinOS.OSArchitecture
					'Operating System'  = $WinOS.Caption
					'Model'             = $Model
					'CPU'               = ($CPU.Name | Select-Object -First 1)
					'IP'                = $IP
					'RAM'               = ([math]::round($WinOS.TotalVisibleMemorySize/1MB)).ToString() + ' GB'
					'Cores'             = ($CPU.NumberOfCores).count
					'LogicalProcessors' = ($CPU.NumberOfLogicalProcessors).Count
					
					
				}
				
				$allDisks = Get-CimInstance -CimSession $objSession -Namespace ROOT/cimv2 -ClassName Win32_Volume -ErrorAction Stop |
                     select driveletter, capacity
				
				foreach ($disk in $alldisks)
				{
					$DisksizeGB = [math]::round($disk.capacity/1GB)
					$diskLetter = $disk.Driveletter.Replace(':', '')
					$params.Add($("$diskLetter Drive"), $("$disksizeGB GB"))
					
				}
				
				# Create objects
				$objresult = New-Object psobject -Property $params
				
				# Add object to result
				$serverarch_obj += $objresult
				
			}
			
		}
		catch [System.Net.WebException], [System.Exception]
		{
			$errorMessage = $_.Exception.Message
            Write-Warning -Message $errorMessage
		}
		finally
		{
			$serverarch_obj
		}
	}
	
}
Older Posts »

Blog at WordPress.com.