Skip to main content

Posts

Showing posts with the label PowerShell

PowerShell check Windows OS version home or professional

Windows OS version also comes in different editions or releases. The edition that has always been a part of Windows OSes releases are Home or Professional version. Home version is good for personal use, as it name suggested that its a Home version. Pro or Professional version is ideal if the laptop or device is used in a company or corporate environment. Professional version has the ability to join a domain or the device can be enrolled to an Active Directory. Windows 11 also comes with SE version, which is aim for low-end devices sold in the education market. There are other editions or releases such as enterprise, workstation and others. To get or check the Windows OS version via PowerShell, run the following PowerShell code snippet. Example: (Get-WmiObject -Class Win32_OperatingSystem).Caption Sample output: Microsoft Windows 11 Home gwmi -class Win32_OperatingSystem | select caption Sample output: caption ------- Microsoft Windows 11 Home Look forward what is bey...

PowerShell Get OS Install Date

PowerShell One-Liner to get OS/Operating System Install Date. Example: [System.Management.ManagementDateTimeConverter]::ToDateTime((Get-WmiObject -Class Win32_OperatingSystem).InstallDate) Without the DateTimeConverter this will just show the raw output of the date and time. (Get-WmiObject -Class Win32_OperatingSystem).InstallDate Feeling overwhelmed with life's tribulations, sufferings and anxieties. You need to surrender all to Jesus, have a faith of mustard seed and walk in the path of righteousness. Matt. 11 Verses 28 to 30 Take my yoke upon you, and learn from me; for I am gentle and lowly in heart, and you will find rest for your souls. For my yoke is easy, and my burden is light.

PowerShell execute multiple task on different servers

If you find yourself feeling overwhelmed by the maintenance of hundreds or multiple servers, there is no need for concern; PowerShell can assist you, provided that you have a clear understanding of the required actions. Below is a PowerShell code snippet that can shut down a server, restart a server, restart a service, or stop a service. It is advisable not to attempt this in a production environment unless the necessary actions are permissible and the task has been approve. An example image illustrating the output of the PowerShell script is included below. Ensure to modify the server name or service name as appropriate. And most importantly, used an elevated PowerShell with Admin credentials. Here's the PowerShell code: $servers = @("Admin_server", "DB_Server", "Redis_Server", "Docker_server") $action = @("Shutdown_server", "Restart_server", "Service_restart", "Service_stop") $ix = 0 ...

PowerShell: Displaying Local Administrator Accounts

The PowerShell command provided below will enumerate all local accounts that belong to the Administrator group or possess administrative privileges on the system. Here is the PowerShell code to execute: Get-CimInstance Win32_GroupUser | Where-Object {$_.GroupComponent.Name -eq "Administrators"} | Select-Object -ExpandProperty PartComponent | Select-Object -Property Name Example Output: There are other ways to list user accounts with administrator privileges on a Windows System. On a server OS or other OS that supports Microsoft Management Console command will also show the list of users with admin rights, press "windows key + r" and when run box appears type: "lusrmgr.msc" or simply open a command prompt and type the command: "lusrmgr.msc", if the command is supported it will show a window where you can check the list of users with admin access. The MMC is beneficial because it features a graphical interface, but using scripts proves...

PowerShell to Verify BIOS Information

The BIOS Properties contain a wealth of information, with BIOS standing for Basic Input Output System. In technical point of view, a computer cannot start without the BIOS. While the computer may power on, it will only show a blank screen, and the operating system will not load or function or there will be no display. Here’s a straightforward PowerShell script to check details such as the BIOS release date, computer serial number, BIOS version, and additional information. PowerShell script to get BIOS information or data. $biosProperties = Get-WmiObject Win32_BIOS Write-Host "BIOS Name:" $biosProperties.Name Write-Host "BIOS Serial Num:" $biosProperties.serialnumber Write-Host "PrimaryBIOS:" $biosProperties.PrimaryBIOS Write-Host "BIOS ReleaseDate:" $biosProperties.ReleaseDate Write-Host "BIOS Version:" $biosProperties.BIOSVersion Write-Host "BIOS Caption:" $biosProperties.Caption Write-Host "BIOS Language...

PowerShell Get ComputerName

Getting computername in PowerShell is quite straight forward using environments variable. Example: $computerName = $env:ComputerName Write-Host "The computer name is: $computerName" With the right credentials and as long as WinRM or Windows Remote Management is enabled we can use the Environment ComputerName variable to shutdown a remote PC. This command runs or shutdown a remote pc, by invoking a local command to shutdown the PC. Invoke-Command -ComputerName remote_computer_name -ScriptBlock {Stop-Computer -ComputerName $env:ComputerName } The above invokes shutdown command locally, just like you were in front of the server or computer. Above is just a demonstration on how to use ComputerName environment variable. Shutting down a remote computer with a valid domain credentials, doesn't need the invoke-command instead command below can be used. Stop-Computer -ComputerName "RemotePC1", "Server2" -Force 1 Peter 5:6: "Humble y...

How to run a command after x minutes in Linux/Windows

In Linux command below will trigger an rm commands after 5 minutes. echo "sleep 5m && rm -f /var/www/html/products.html" | at now In Windows the command below will also trigger a copy command after 5 minutes. Start-Job -ScriptBlock { copy /html/update.html /shared/} -ArgumentList (New-TimeSpan -Minutes 5) Faith as big as a mustard seed will create a magnificient outcome in your life.

PowerShell Port Scanning one liner - check range of port

Netcat is one of the best tools to check if port is open or not, and Netcat does offer also a lot of features other than port scanning. However, if netcat is not available on the system or it's not allowed to be installed. In Windows environment PowerShell will come in handy. Example one-liner code below uses PowerShell to scan a specified Target IP and also a range of ports to be scanned. To test the code, change the target IP as desired and also the range of port to be tested.  1..65535 | % {Test-NetConnection  127.0.0.1-Port $_ } 442..443 | % {Test-NetConnection  8.8.8.8 -Port $_ } Sample Output of the above commands:  1..10 | % {Test-NetConnection  127.0.0.1-Port $_ } 442..443 | % {Test-NetConnection  8.8.8.8 -Port $_ } Cheers! Take care. Till next Time. Enjoy exploring the world of PowerShell and enjoy the journey of learning.. Stay safe! and Keep things up!  Do ASAP,  A lways  S ay  A   P rayer ... Practice O.T.G. =  O be...

PowerShell check device uptime since last reboot

Checking how long the machine or server is running since last reboot or maintenance is sometimes necessary. To measure the device performance or stability of the server or computer. In Windows, PowerShell is quite handy to to check the uptime of the server. Here's a simple code snippet to do check how long the server has been running since its last reboot. $Last_reboot_time = Get-WmiObject win32_operatingsystem | select csname, @{LABEL='LastBootUpTime';EXPRESSION={$_.ConverttoDateTime($_.lastbootuptime)}} $Today = Get-Date $uptime = NEW-TIMESPAN –Start $Last_reboot_time.LastBootUpTime –End $Today $xdays=$uptime.Days $xhours=$uptime.TotalHours $xhours=[math]::Round($xhours,2) write-output ("Computer is up since last reboot for: $xdays day/s and  $xhours  hours") Sample output of the code below: Computer is up since last reboot for: 1 day/s and  45.98  hours Cheers! Take care. Till next Time. Stay safe! and Keep things up!  Do ASAP,  A lways  S ay  ...

WMIC restart wireless network via command line in Windows

How to restart WiFi or Wireless using command line in Windows? If the wireless devices, laptops or computers are connected to a domain such as active directory, or a centralized control. The command below can be created using a batch file and deploy to all controlled devices or computers. The command below, has been tested on a Windows 11 laptop and works fine. If nothing goes wrong, the command executes very fast. Here's the command, must be executed on an elevated command prompt or administrator prompt. wmic service where caption="WLAN AutoConfig" call stopservice && timeout 3 && wmic service where caption="WLAN AutoConfig" call startservice Timeout command is used in between stop and start, as this would give the first command to stop the service and after 3 seconds, another command is executed to start the service. Without the timeout command, the second command might not run  properly, since the first is still executed on the background. Jus...

How to view windows folder in GB or MB or in human readable sizes

With the era of WSL, Windows Subsystem for Linux is quite helpful. You can now run Linux commands on Windows with ease, or without installing any virtualization software. Of course, having VirtualBox installed with Linux is a different story, since you can have a pure Linux environment. Anyway, WSL provides an easy way to view size or capacity of Windows folder without any scripting using PowerShell or installing any Sysinternal tools. How to view folder sizes in human readable format in Windows using WSL? If WSL has been installed and working correctly, open Windows Terminal an awesome command-line shell application, in which you can run multiple Windows in one screen. And you can also position different windows terminal, either horizontally or vertically and Terminals can be resized the way you wan it. Grab windows terminal from Microsoft Store and for the prize of free. Once the Windows Terminal is open, just cd or browse to the directory where you need to check folder sizes. Just p...

PowerShell query event log last reboot or shutdown

Querying when was the last time the server  or computer is  essential in troubleshooting or auditing the server. Or in production system, computers or servers, must scheduled a downtime and let stakeholders know that at this specific date and time there will be a down time and services will not ne available at the said time and date. Even in development servers or computers, checking when was the last time the computer restarted or shutdown is quite essential. If the application is buggy,  or has some memory leak or other issues then it will cause the system to reboot, shutdown or crash. PowerShell comes in handy in querying event log; when was the last time the computer has shutdown or rebooted. Of course, event log can be checked manually. But scrolling through the 100 or thousands of event logs is quite tedious. So, PowerShell comes to a rescue  and avoid the tedious, manual finding of the event log. Here's a sample code snippet on how to query Windows event log w...

PowerShell Compare and Get Hash File

 Hash File comparison is a good thing to do, to make sure that file in transit, transferred, downloaded, or copied over is not corrupted or has been altered or modified. PowerShell has a built-in module to do this that makes life easier and an easy task to do. Here's an example code snippet to do this: #Path location of the file $file="C:\Users\User1\Downloads\Win10_22H2_EnglishInternational_x64.iso" # Get the file hash $hashSrc = Get-FileHash $file -Algorithm "SHA256" write-output $hashSrc #copy the Hash file  $Display_hash_only = $hashSrc | Select-Object -Property Hash | ft -HideTableHeaders Write-Output $Display_hash_only Output of the write-output $hashSrc command, will show the Algorithm used, the Hash of the file and path location of the file. Algorithm : SHA256  Hash: AC5522F9DB9F4F432A1AADE69FEF268C8C0B5FD3F22D3A6987719752F8A7108   Path : C:\Users\User1\Downloads\Win10_22H2_EnglishInternational_x64.iso  After getting the Hash File run this code...

Create an admin account on Azure VM to reset forgotten password

How to create an administrator account on Azure VM? On Azure environment, username and password of the authorized account is needed in order to login or connect via Remote Desktop. If the administrator password or the password to RDP has been forgotten, then logging in to the VM will be an issue. How to resolve this kind of issue? PowerShell is a friend for this kind of dilemma. Code snippet below will create a user account, and set the created account as a member of the administrator group. # Create a user account   $username = "azure_admin_22" $password = ConvertTo-SecureString "Dynamic_Admin_User_2022" -AsPlainText -Force New-LocalUser -Name "$username" -Password $password -FullName "$username" -Description "User Description"   # Add the user to "Administrators" groups Add-LocalGroupMember -Group "Administrators" -Member azure_admin_22 User account that will be created is: azure_admin_22 with the pass...

PowerShell add text or string to text file without opening the file

How to add or append a string or any contents to a text file without opening the text file? Reading and writing in PowerShell is quite fundamental but very important. A simple PowerShell snippet code below, that will add or append a string to the text file dynamically. This is quite useful like monitoring a service, or pinging a server and adding the status or the result to a text file that can be checked later. Text file can be easily tampered, so proper permissions should be set who can write and read. So the file can be a source of truth, if ever auditing has to be done. Here's a simple PowerShell snippet that append a string to a text file or dynamically adding a string to a file. $contents_to_add=Get-Date Add-Content   -Path  "c:\temp\xx.rtf" -Value $contents_to_add #This will append a string to the existing content $file_content = get-content -Path  "c:\temp\xx.rtf" Write-Output $file_content  #Read the content of the files Just a short code but does a won...

Set or create a task scheduler using PowerShell or via command prompt

Task Scheduler in Windows or Cron in Linux is a life saver on the Sys Admin world. Why it is a life saver? You can set a scheduled task and forget about it. Of course, provided you have already carefully examined and test multiple times what will be the output when the Task is triggered. Yes, set and forget; once you are confident enough that everything will go smoothly. If there are task that needs to be run at midnight or early hours in the morning, Task Scheduler will come in handy. So, how do we set a Task Scheduler using PowerShell or Command Prompt? Why need to learn both? And not just PowerShell? Well, command prompt is always available on all Windows distribution. While PowerShell might be available on newer Windows system but then some restriction might be in place for security reasons. Therefore, it is good to be familiar with both PowerShell and Command Prompt executable files. PowerShell code snippet below shows how to set or create a Task Scheduler. PowerSh...

Parallel Processing example using PowerShell

PowerShell version 7 has option to run tasks in Parallel.  This would mean that task that can be run in Parallel mode and tasks can be done simultaneously and save time.  How to get started or making use of Parallel in PowerShell?  First, PowerShell has to be in version 7.  Version 7 of PowerShell can be downloaded from Microsoft via this link below.  PowerShell 7 download. Choose the version, whether its x86 or x64.  The CPU architecture in your system will determine whether x64 PowerShell can be used or not.  Check out this link to check CPU architecture in your system:  Check if 64 bit processor or 32 bit Sample code below, shows how Parallel processing in PowerShell can be done.    $HostsIPs = '127.0.0.1','8.8.8.8','8.8.4.4','1.1.1.1'    $HostsIPs | ForEach-Object -Parallel {      Test-Connection $_      } -ThrottleLimit 5   The screenshot image below, shows that the commands indee...

Get accounts in O365 with no ATP or Defender license assigned

Advance Threat Protection aka ATP which is now called Microsoft Defender in office 365, is one of the licenses offered by Microsoft. If there are hundred accounts in O365, tracking which account that doesn't have ATP or Microsoft Defender license is just troublesome. Of course, PowerShell will come into rescue for this kind of issue. One liner code below in PowerShell will check which Office 365 accounts does not have ATP or Microsoft Defender license assigned. Get-MsolUser -All | Where-Object {$_.licenses.AccountSkuId -notcontains 'contoso:ATP_ENTERPRISE'} | Select-Object userprincipalname,licenses | export-csv c:\temp\office_365\no_defender_license.csv Replace contoso with your domain. Or run this command to see which licenses are assigned or available in your tenant. Get-MsolAccountSku | select -ExpandProperty ServiceStatus The PowerShell command checks which accounts does not have ATP assigned; which means that if you have 100 of guests or client user...

PowerShell test/check if file exist

One liner code to check if file exists via PowerShell. Code below will check if Winrar.exe exist on the path specified. if (-not (test-path "$env:C:\Program Files\WinRAR\winrar.exe")) {write-host "File not found"; break;} {write-host "File Found" } Output will show "File Found" if winrar.exe exists on the path specified. The "break;" command on the code will cause the script to exit and not to continue to show "File Found" if the file doesn't exist. Or else it will be confusing to see the output. However, if the file can be found then the "File not Found" will not be shown. PowerShell will automatically bypass the first command on the { } curly braces and execute whatever is on the next line. Code below will check if output.txt exist on c:\temp. if (-not (test-path "$env:C:\temp\output.txt")) {write-host "File not found"; break;} {write-host "File Found" } Output ...

Close all open notepad instances or processes in one go

If you’re an admin and manually checking logs for details and opening each file one by one. Then opening multiple instances of notepad is quite an everyday task. Or you just love notepad in making notes, documentations or other endless reasons to use notepad. Then it will be a headache in closing all the notepad instances that were opened. However, PowerShell can be used to close all instances of notepad all at once. No sweat in clicking each file one by one. PowerShell can handle it in one click of a button if you open the file via PowerShell ISE. Here’s a simple PowerShell code snippet to close all files in one shot. #========== $x = ( Get-Process | Where-Object   { $_ . ProcessName -EQ 'Notepad' }) . count   1 .. $x | % {    stop-process -name notepad –force } #=========== Yes, 2 lines of code can save you a lot of time. The above code can be used also to close other processes that has multiple instances open on the system. If uns...