Friday 10 January 2020

Useful PowerShell scripts -1

Here are the few very useful PowerShell short commands for basic checks:

Disk info:
Get-WmiObject Win32_volume -ComputerName .|Format-Table Name, Label,
@{Name="SizeGB";Expression={($_.capacity/1gb -as [int])}},
@{Name="FreeSpaceGB";Expression={([math]::Round($_.Freespace/1GB,0))}},
@{Name="UsedGB";Expression={($_.capacity/1gb -as [int])-([math]::Round($_.Freespace/1GB,0))}}


Disk block size format info:
Script-1:
Get-CimInstance -ClassName Win32_Volume | Select-Object Name, Label, BlockSize | Format-Table -AutoSize Script-2:
Get-WmiObject -Class Win32_Volume -ComputerName .| Select-Object Name,Label,BlockSize | Format-Table -AutoSize

Disk Lun ID\Physical location info:
Get-WmiObject Win32_DiskDrive | sort scsibus,scsilogicalunit | 
ft @{Label=”ScsiBus”;Expression={$_.scsibus}},@{Label=”LUN”;Expression={$_.scsilogicalunit}}, 
@{Label=”Disk Number”;Expression={$_.index}}, 
@{Label=”Size (GB)”;Expression={[Math]::Round($_.size / 1GB)}} -autosize


Disk partition style (GPT\MBR) info:

Get-Disk | Select-Object  DiskNumber,FriendlyName,SerialNumber,HealthStatus,OperationalStatus,
@{Name="SizeGB";Expression={($_.Size/1gb -as [int])}},PartitionStyle | Format-Table -AutoSize


Add User at server level remotely\locally :
Invoke-Command -ComputerName . 
-ScriptBlock {Add-LocalGroupMember -Group Administrators -Member "domain\account"}


Sample code to check if software is installed, do something & if not, do something else :
$software = "SQL Server*";
$installed = (Get-Service | Where-Object {$_.DisplayName -eq $software}) -like $null

If(-Not $installed)
{
    Write-Host "Copy '$software'..."

    Copy-Item -Path "Source_Path" -Destination "C:\dba\xxxx.msi"

    Get-Date

    Write-Host "Ready to install '$software'..."
    Read-Host -Prompt "Press Enter to continue"

    Invoke-Command -ComputerName . -ScriptBlock `
    {Start-Process msiexec.exe -Wait -ArgumentList '/I C:\dba\xxx.msi /quiet'}
    Write-Host "driver Installed!!"
}
else { Write-Host "'$software' is installed." }


No comments:

Post a Comment