Difference between revisions of "Powershell"

From TheBestLinux.com
Jump to navigation Jump to search
 
(35 intermediate revisions by the same user not shown)
Line 4: Line 4:
 
<br /><br />
 
<br /><br />
  
 +
== Running PowerShell Commands as Administrator - Needed for System/Server/User Administration ==
 +
Many, if not most, administrative PowerShell commands require being run as the Administrator user or what is referred to as elevated privileges. Depending on if you are wanting to open a window from a CMD/Command prompt, or if you are opening it from a PowerShell command prompt, the process is very similar.
 +
<br /><br />
 +
 +
From PowerShell, here is the command to open an elevated PowerShell window to then run administrative command from:
 +
<pre style="color:blue">
 +
PS C:\Users\jamie.DAWGLAND> Start-Process powershell -verb runas
 +
</pre>
 +
<br />
 +
 +
This will open up a new PowerShell window with administrative privileges.
 +
<br /><br />
 +
 +
If you are in a CMD/DOS/Command Prompt, first type "powershell" to start PowerShell, and then just follow the above commands to open an elevated PowerShell window in which you can then run administrative commands to manage your system.
 +
<br /><br /><br />
 +
 +
== '''Setup Windows Command-line(CMD) Aliases Similar to Alias in Linux/UNIX''' ==
 +
I find the ability to creating and using custom "shortcut" commands, commonly referred to "Aliases".
 +
<br />
 +
Traditionally, the Windows/DOS command "DOSKEY" is used to create complex command "alias" commands, to make administration of Windows/DOS based computers much easier and quicker. 
 +
<br />
 +
As I am obviously a Linux guy, I always prefer the "Linux/UNIX" way of doing things.  That's why one of the first things I do on any new Windows computer is to install the command-line "GIT" tools, which include many of the most common Linux command-line tools and configures the Windows command-line terminal to look and function like Linux terminals.
 +
<br />
 +
Instead of using DOSKEY, I find the solution at this URL to be best for my needs:
 +
https://superuser.com/questions/183475/how-to-alias-commands-on-windows-command-prompt
 +
<br /><br />
 +
 +
== '''REAL Aliases with Powershell''' ==
 +
Powershell actually has full support for "Real" aliases! It contains many built-in aliases, and has the ability to create any type of custom alias you can imagine!
 +
<br /><br />
 +
To list the basic commands used to manage aliases using Powershell, use this command from a Powershell prompt:
 +
<pre style="color:blue">
 +
PS C:\Users\jamie> Get-Command -Noun Alias 
 +
</pre>
 +
<br /><br />
 +
 +
The output of the command should look like this:
 +
<pre style="color:blue">
 +
CommandType    Name                                              Version    Source
 +
-----------    ----                                              -------    ------
 +
Cmdlet          Export-Alias                                      3.1.0.0    Microsoft.PowerShell.Utility
 +
Cmdlet          Get-Alias                                          3.1.0.0    Microsoft.PowerShell.Utility
 +
Cmdlet          Import-Alias                                      3.1.0.0    Microsoft.PowerShell.Utility
 +
Cmdlet          New-Alias                                          3.1.0.0    Microsoft.PowerShell.Utility
 +
Cmdlet          Set-Alias                                          3.1.0.0    Microsoft.PowerShell.Utility
 +
 +
 +
PS C:\Users\jamie>
 +
</pre>
 +
<br /><br />
 +
 +
Use the Get-Alias commandlet to list the aliases available in the current environment:
 +
<pre style="color:blue">
 +
PS C:\Users\jamie> Get-Alias -Definition Get-ChildItem
 +
 +
CommandType    Name                                              Version    Source
 +
-----------    ----                                              -------    ------
 +
Alias          dir -> Get-ChildItem
 +
Alias          gci -> Get-ChildItem
 +
Alias          ls -> Get-ChildItem
 +
 +
PS C:\Users\jamie>
 +
</pre>
 +
<br /><br />
 +
 +
To see the definition of a single alias, use the "Name" parameter:
 +
<pre style="color:blue">
 +
PS C:\Users\jamie> Get-Alias -Name gci
 +
 +
CommandType    Name                                              Version    Source
 +
-----------    ----                                              -------    ------
 +
Alias          gci -> Get-ChildItem
 +
 +
PS C:\Users\jamie>
 +
</pre>
 +
<br /><br />
 +
 +
Use the Set-Alias command to create a new custom alias:
 +
<pre style="color:blue">
 +
PS C:\Users\jamie> Set-Alias -Name chkadm -Value "(New-Object Security.Principal.WindowsPrincipal([Security.Principal.WindowsIdentity]::GetCurrent())).IsInRole([Security.Principal.WindowsBuiltInRole]::Administrator)"
 +
 +
</pre>
 +
<br /><br />
 +
 +
 +
 +
Here is a URl at Microsoft listing all Powershell built-in aliases, as well as information on how to create your own custom alias for use with Powershell.
 +
<br />
 +
https://learn.microsoft.com/en-us/powershell/scripting/learn/shell/using-aliases?view=powershell-7.4
 +
<br /><br />
 +
 +
== DOS/CMD - Miscellaneous Command Line Commands ==
 +
This command shows how long a Windows computer has been powered on since the last time it was shut down or rebooted, which can be helpful when diagnosing issues with a sluggish, slow-responding system.  this is also known as a system's "Uptime".  This is the command along with its output.  Note the line starting with "Statistics since", which shows the actual date and time the system was last powered on.
 +
<pre style="color:blue">
 +
C:\Users\Administrator.DAWGLAND>net stats workstation
 +
Workstation Statistics for \\WIN22VM01
 +
 +
 +
Statistics since 2/6/2023 10:22:32 AM
 +
 +
 +
  Bytes received                              502580
 +
  Server Message Blocks (SMBs) received        2
 +
  Bytes transmitted                            952389
 +
  Server Message Blocks (SMBs) transmitted    0
 +
  Read operations                              366
 +
  Write operations                            0
 +
  Raw reads denied                            0
 +
  Raw writes denied                            0
 +
 +
  Network errors                              0
 +
  Connections made                            0
 +
  Reconnections made                          0
 +
  Server disconnects                          0
 +
 +
  Sessions started                            0
 +
  Hung sessions                                0
 +
  Failed sessions                              0
 +
  Failed operations                            0
 +
  Use count                                    109
 +
  Failed use count                            0
 +
 +
The command completed successfully.
 +
</pre>
 +
<br /><br />
 +
You can trim/filter out most of the output, so that you only get the actual info you are looking for, in this case, the two-word phrase "Statistics since".  This is how you would do it, "piping" the output of the previous command into the "findstr" command to find the line(s) containg the phrase "Statics since", case sensitive:
 +
<pre syle="color:blue">
 +
PS C:\Users\Administrator.DAWGLAND> net stats workstation | findstr /C:"Statistics since"
 +
Statistics since 2/6/2023 10:22:32 AM
 +
</pre>
 +
<br /><br />
 +
You can shorten the command even further if you instead of searching for the two-word phrase "Statistics since", you can just search for/find the one word "since", as it's the only line in the entire output of the "net stats workstation" command that contains that one word.  Here's an example:
 +
<pre style="color:blue">
 +
PS C:\Users\Administrator.DAWGLAND> net stats workstation | findstr since
 +
Statistics since 2/6/2023 10:22:32 AM
 +
</pre>
 +
<br /><br />
 +
 +
== Enabling & Configuring OpenSSH Server on Windows Using PowerShell ==
 +
First, confirm the current state of the OpenSSH Server and OpenSSH Clients, whether either are installed, enabled, and configured.
 +
 +
Type this command to check the current status of both the server and client:
 +
<pre style="color:blue">
 +
PS C:\Users\Administrator.DAWGLAND> Get-WindowsCapability -Online | ? Name -like 'OpenSSH*'
 +
 +
 +
Name  : OpenSSH.Client~~~~0.0.1.0
 +
State : Installed
 +
 +
Name  : OpenSSH.Server~~~~0.0.1.0
 +
State : NotPresent
 +
 +
</pre>
 +
<br /><br />
 +
 +
As you can see from output of the above command, OpenSSH Client is installed on the server, but OpenSSH Server is "NotPresent", meaning it's not been installed/enabled on the server yet.  Will fix that next so that users can log into the Windows server using SSH, the Secure Shell to remotely connect annd manage the server.
 +
<br /><br />
 +
Use this PowerShell command to install/enable the OpenSSH Server:
 +
<pre style="color:blue">
 +
PS C:\Users\Administrator.DAWGLAND> Add-WindowsCapability -Online -Name OpenSSH.Server~~~~0.0.1.0
 +
 +
 +
Path          :
 +
Online        : True
 +
RestartNeeded : False
 +
 +
</pre>
 +
<br /><br />
 +
 +
Run the previous "Get-WindowsCapability -Online | ? Name -like 'OpenSSH*'" command and confirm that OpenSSH Server is now installed.
 +
<br /><br />
 +
Next, manually start the OpenSSH service, like this:
 +
<pre style="color:blue">
 +
PS C:\Users\Administrator.DAWGLAND> Start-Service sshd
 +
WARNING: Waiting for service 'OpenSSH SSH Server (sshd)' to start...
 +
</pre>
 +
<br /><br />
 +
You can use this command to confirm the SSH server service has been started and is now running:
 +
<pre style="color:blue">
 +
PS C:\Users\Administrator.DAWGLAND> Get-Service | findstr -i sshd
 +
Running  sshd              OpenSSH SSH Server
 +
 +
</pre>
 +
<br /><br />
 +
Use this command to check on the startup type, referring to the setting to have the OpenSSH Server startup automatically on each computer reboot or power on.
 +
<pre style="color:blue">
 +
PS C:\Users\jamie.DAWGLAND> Get-Service -Name sshd | Select -property name,starttype
 +
 +
Name StartType
 +
---- ---------
 +
sshd    Manual
 +
 +
</pre>
 +
As you can see from the output of the above command, the "StartType" for "sshd"(sshd stands for "SecureSHell Daemon".  Daemon is another word for "Server".
 +
<br /><br />
 +
As we want to always be able to securly log into the server remotely to perform routine maintenance and configuration, we want to configure the SSHD(OpenSSH Server) to automatically start up every time the computer is started up or rebooted.  Here's how:
 +
<pre style="color:blue">
 +
PS C:\Users\jamie\Downloads> Set-Service -Name sshd -StartupType 'Automatic'
 +
</pre>
 +
<br /><br />
 +
Now, confirm it's set to start up automatically:
 +
<pre style="color:blue">
 +
PS C:\Users\jamie\Downloads> Get-Service -Name sshd | Select -property name,star
 +
ttype
 +
 +
Name StartType
 +
---- ---------
 +
sshd Automatic
  
=== Miscellaneous PowerShell Commands ===
+
</pre>
 +
<br /><br />
 +
Confirm firewall rule has been created for the SSH service:
 +
<pre style="color:blue">
 +
PS C:\Users\jamie.DAWGLAND> Get-NetFirewallRule -Name *ssh*
 +
 
 +
 
 +
Name                          : OpenSSH-Server-In-TCP
 +
DisplayName                  : OpenSSH SSH Server (sshd)
 +
Description                  : Inbound rule for OpenSSH SSH Server (sshd)     
 +
DisplayGroup                  : OpenSSH Server
 +
Group                        : OpenSSH Server
 +
Enabled                      : True
 +
Profile                      : Any
 +
Platform                      : {}
 +
Direction                    : Inbound
 +
Action                        : Allow
 +
EdgeTraversalPolicy          : Block
 +
LooseSourceMapping            : False
 +
LocalOnlyMapping              : False
 +
Owner                        :
 +
PrimaryStatus                : OK
 +
Status                        : The rule was parsed successfully from the     
 +
                                store. (65536)
 +
EnforcementStatus            : NotApplicable
 +
PolicyStoreSource            : PersistentStore
 +
PolicyStoreSourceType        : Local
 +
RemoteDynamicKeywordAddresses : {}
 +
 
 +
</pre>
 +
<br /><br />
 +
Finally, last, but not least, configure PowerShell to be the default environment when logging into the Windows server using SSH protocol.  Here's the command:
 +
<pre style="color:blue">
 +
PS C:\Users\jamie.DAWGLAND> New-ItemProperty -Path "HKLM:\SOFTWARE\OpenSSH" -Name DefaultShell -Value "C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe" -PropertyType String -Force
 +
 
 +
 
 +
DefaultShell : C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe       
 +
PSPath      : Microsoft.PowerShell.Core\Registry::HKEY_LOCAL_MACHINE\SOFTWARE\
 +
              OpenSSH
 +
PSParentPath : Microsoft.PowerShell.Core\Registry::HKEY_LOCAL_MACHINE\SOFTWARE 
 +
PSChildName  : OpenSSH
 +
PSDrive      : HKLM
 +
PSProvider  : Microsoft.PowerShell.Core\Registry
 +
 
 +
</pre>
 +
<br /><br />
 +
 
 +
== AD-DS - Active Directory - Domain Services ==
 +
Here is the DOS/CMD command to show the current state of each of the 5 FSMO roles configured for MS AD-DS using the "netdom query fsmo" command:
 +
<pre style="color:blue">
 +
C:\Users\Administrator.DAWGLAND>netdom query fsmo
 +
Schema master              win19vm10.dawgland.com
 +
Domain naming master        win19vm10.dawgland.com
 +
PDC                        win19vm10.dawgland.com
 +
RID pool manager            win19vm10.dawgland.com
 +
Infrastructure master      win19vm10.dawgland.com
 +
The command completed successfully.
 +
</pre>
 +
<br /><br />
 +
As you can see from the output of the "netdom query fsmo" command, all 5 roles are hosted on the same Windows Server 2019 machine/VM.  This is required information when it comes time to migrate AD-DS from an older server to a newwer server with a newer version of MS Windows Server.
 +
<br /><br />
 +
 
 +
== Miscellaneous PowerShell Commands ==
 
Here are some of the PowerShell commands I use regularily to to manage Windows machines:
 
Here are some of the PowerShell commands I use regularily to to manage Windows machines:
 
<pre style="color:blue">
 
<pre style="color:blue">
 
 
Create NEW Active Directory Domain Controller/AD DS:
 
Create NEW Active Directory Domain Controller/AD DS:
 
Install-WindowsFeature -Name AD-Domain-Services -IncludeManagementTools
 
Install-WindowsFeature -Name AD-Domain-Services -IncludeManagementTools
Line 39: Line 308:
 
Get-ADDomain dawgland.com | Format-Table PDCEmulator,RIDMaster,InfrastructureMaster
 
Get-ADDomain dawgland.com | Format-Table PDCEmulator,RIDMaster,InfrastructureMaster
 
Get-ADForest dawgland.com | Format-Table SchemaMaster,DomainNamingMaster
 
Get-ADForest dawgland.com | Format-Table SchemaMaster,DomainNamingMaster
 
 
Get-DnsServerResourceRecord -ZoneName dawgland.com
 
Get-DnsServerResourceRecord -ZoneName dawgland.com
 
Get-NetConnectionProfile
 
Get-NetConnectionProfile
Line 49: Line 317:
 
Add-WindowsCapability -Online -Name OpenSSH.Server~~~~0.0.1.0
 
Add-WindowsCapability -Online -Name OpenSSH.Server~~~~0.0.1.0
 
Import-Module GroupPolicy -verbose
 
Import-Module GroupPolicy -verbose
 +
 +
</pre>
 +
 
<br /><br />
 
<br /><br />
 +
== Hardware Related PowerShell Commands ==
 +
Display Hard Drive Information:
 +
<pre style="color:blue">
 +
S C:\Users\Administrator> Get-Disk
 +
 +
Number Friendly Name                Serial Number                    HealthStatus        OperationalStatus      Total Size Partition
 +
                                                                                                                            Style   
 +
------ -------------                -------------                    ------------        -----------------      ---------- ----------
 +
0      VMware Virtual disk          6000c29e5f1b1b3e5150ace9c505b4a3 Healthy              Online                      25 GB GPT
 
</pre>
 
</pre>
 +
<br /><br />
 +
 +
Display Disk Drive Volumes:
 +
<pre style="color:blue">
 +
PS C:\Users\Administrator> Get-Volume
 +
 +
DriveLetter FriendlyName FileSystemType DriveType HealthStatus OperationalStatus SizeRemaining    Size
 +
----------- ------------ -------------- --------- ------------ ----------------- -------------    ----
 +
                        NTFS          Fixed    Healthy      OK                    83.41 MB  523 MB
 +
                        FAT32          Fixed    Healthy      OK                    68.17 MB    96 MB
 +
C                        NTFS          Fixed    Healthy      OK                    13.53 GB 24.37 GB
 +
D                        Unknown        CD-ROM    Healthy      Unknown                    0 B      0 B
 +
</pre>
 +
<br /><br />
 +
 +
== More PowerShell Commands with Some Examples ==
 +
Here are some more commands I use when working on headless Windows Server hardware and virual machines, such as
 +
 +
Windows Server Core:
 +
<pre style="color:blue">
 +
 +
Open a Windows command prompt as Administrator:
 +
runas /user:administrator CMD.exe
 +
 +
List Installed Apps:
 +
Get-ItemProperty HKLM:\Software\Wow6432Node\Microsoft\Windows\CurrentVersion\Uninstall\* | Select-Object DisplayName, DisplayVersion, Publisher, InstallDate | Format-Table –AutoSize
 +
 +
Install Failover Cluster Tools:
 +
Install-WindowsFeature -Name Failover-Clustering –IncludeManagementTools
 +
Include command line management tools:
 +
Install-WindowsFeature RSAT-Clustering-CmdInterface
 +
 +
Find out if package is installed.  This example uses GIT:
 +
PS C:\Users\Administrator> Get-Package | Select-Object Name | findstr -i git
 +
Git
 +
 +
Find out if package is installed.  This exampled uses WAC(Windows Admin Center):
 +
PS C:\Users\Administrator> get-package | select-object Name | findstr -i Admin
 +
Windows Admin Center
 +
 +
Another way to do same as above, but more “Precise”.  Can USE WILD-CARDS!!!:
 +
PS C:\Users\Administrator> get-package | Where-Object {$_.Name -like "*Windows Admin Center*"}
 +
 +
Name                          Version          Source                          ProviderName
 +
----                          -------          ------                          ------------
 +
Windows Admin Center          1.3.53858.0      C:\Program Files\Windows Admi... msi
 +
 +
 +
Display ALL services installed and their status:
 +
Get-Service | Select-Object Name,Status,DisplayName
 +
 +
Check Status of Windows Admin Center(IF Installed – Otherwise will not find it!
 +
Get-Service | Select-Object Name,Status,DisplayName | findstr Admin
 +
FINDS:
 +
“ServerManagementGateway”, the ACTUAL name of WAC!
 +
ServerManagementGateway                  Running Windows Admin Center Service
 +
ServerManagementGatewayAccount          Stopped Windows Admin Center Account Service
 +
 +
Configure DNS Servers:
 +
Set-DnsClientServerAddress -InterfaceIndex 3 -ServerAddresses ("192.168.200.103","192.168.200.121","75.75.76.76")
 +
 +
Disable ALL Firewall Zones:
 +
Set-NetFirewallProfile -Profile Domain,Public,Private -Enabled False
 +
 +
Enable a port through firewall:
 +
netsh advfirewall firewall add rule name="WinRM-HTTP" dir=in localport=5985 protocol=TCP action=allow
 +
 +
Check if Windows Admin Center has been installed:
 +
Get-WmiObject -Class win32_service | Where-Object {$_.name -like "WinRM"}
 +
 +
Download a file using PowerShell:
 +
$WebClient = New-Object System.Net.WebClient
 +
$WebClient.DownloadFile("http://192.168.200.125/WindowsAdminCenter2110.2.msi","C:\Users\Administrator\WindowsAdminCenter2110.2.msi")
 +
 +
Check EvenLogs for logins, failures, apps, etc:
 +
get-eventlog -list
 +
get-eventlog Application -after (get-date).addhours(-1)
 +
get-eventlog Application -after (get-date).addhours(-8)
 +
 +
USE Security log for checking logins:
 +
get-eventlog Security -after (get-date).addhours(-1)
 +
 +
FORMATTING Example of explicit log index number:
 +
Get-EventLog Security | where index -eq 3704 | format-list *
 +
 +
DOWNLOAD & Install MS SQL Server:
 +
$wc=new-object system.net.webclient
 +
$wc.downloadfile("https://go.microsoft.com/fwlink/?linkid=866662","SQL2019-SSEI-Dev.exe")
 +
 +
GIT Download:
 +
$wc.downloadfile("https://github.com/git-for-windows/git/releases/download/v2.36.0.windows.1/Git-2.36.0-64-bit.exe","Git-2.36.0-64-bit.exe")
 +
 +
Get-Service -Name vds
 +
get-service | Where-Object {$_.status -eq "stopped"}
 +
get-service -name wisvc
 +
 +
PS C:\Users\Administrator> get-service | grep -i admin
 +
Stopped  sacsvr            Special Administration Console Helper
 +
Running  ServerManagemen... Windows Admin Center Service
 +
Stopped  ServerManagemen... Windows Admin Center Account Service
 +
PS C:\Users\Administrator>
 +
 +
Get-Item WSMan:\localhost\Client\TrustedHosts
 +
 +
Get-CimInstance -Class CIM_LogicalDisk
 +
 +
DeviceID DriveType ProviderName VolumeName Size        FreeSpace
 +
-------- --------- ------------ ---------- ----        ---------
 +
C:      3                                53109321728 44553736192
 +
D:      5
 +
 +
 +
Get-NetTCPConnection
 +
 +
LocalAddress                        LocalPort RemoteAddress                      RemotePort State      AppliedSetting
 +
------------                        --------- -------------                      ---------- -----      --------------
 +
::                                  56357    ::                                  0          Bound
 +
::                                  56268    ::                                  0          Bound
 +
::                                  54693    ::                                  0          Bound
 +
::                                  54690    ::                                  0          Bound
 +
::                                  54689    ::                                  0          Bound
 +
::                                  54688    ::                                  0          Bound
 +
::                                  54687    ::                                  0          Bound
 +
::                                  54671    ::                                  0          Bound
 +
::                                  54667    ::                                  0          Bound
 +
::                                  54665    ::                                  0          Bound
 +
::                                  54663    ::                                  0          Bound
 +
::                                  49712    ::                                  0          Bound
 +
::                                  49706    ::                                  0          Bound
 +
::                                  49695    ::                                  0          Bound
 +
::                                  49680    ::                                  0          Bound
 +
::                                  49679    ::                                  0          Bound
 +
::1                                56357    ::1                                49666      Established Datacenter
 +
fe80::b586:d0e3:8c2b:2229%5        56268    fe80::b586:d0e3:8c2b:2229%5        49666      Established Datacenter
 +
fe80::b586:d0e3:8c2b:2229%5        54815    fe80::b586:d0e3:8c2b:2229%5        135        TimeWait
 +
fe80::b586:d0e3:8c2b:2229%5        54671    fe80::b586:d0e3:8c2b:2229%5        389        Established Datacenter
 +
fe80::b586:d0e3:8c2b:2229%5        54667    fe80::b586:d0e3:8c2b:2229%5        389        Established Datacenter
 +
::1                                54665    ::1                                389        Established Datacenter
 +
fe80::b586:d0e3:8c2b:2229%5        54663    fe80::b586:d0e3:8c2b:2229%5        389        Established Datacenter
 +
::                                  49715    ::                                  0          Listen
 +
fe80::b586:d0e3:8c2b:2229%5        49712    fe80::b586:d0e3:8c2b:2229%5        49666      Established Datacenter
 +
fe80::b586:d0e3:8c2b:2229%5        49695    fe80::b586:d0e3:8c2b:2229%5        49666      Established Datacenter
 +
::                                  49692    ::                                  0          Listen
 +
::                                  49686    ::                                  0          Listen
 +
::1                                49680    ::1                                389        Established Internet
 +
::1                                49679    ::1                                389        Established Datacenter
 +
::                                  49676    ::                                  0          Listen
 +
::                                  49675    ::                                  0          Listen
 +
::                                  49668    ::                                  0          Listen
 +
fe80::b586:d0e3:8c2b:2229%5        49666    fe80::b586:d0e3:8c2b:2229%5        56268      Established Datacenter
 +
fe80::b586:d0e3:8c2b:2229%5        49666    fe80::b586:d0e3:8c2b:2229%5        49712      Established Datacenter
 +
fe80::b586:d0e3:8c2b:2229%5        49666    fe80::b586:d0e3:8c2b:2229%5        49695      Established Datacenter
 +
::1                                49666    ::1                                56357      Established Datacenter
 +
::                                  49666    ::                                  0          Listen
 +
::                                  49665    ::                                  0          Listen
 +
::                                  49664    ::                                  0          Listen
 +
::                                  47001    ::                                  0          Listen
 +
::                                  9389      ::                                  0          Listen
 +
::                                  5985      ::                                  0          Listen
 +
::                                  3389      ::                                  0          Listen
 +
::                                  3269      ::                                  0          Listen
 +
::                                  3268      ::                                  0          Listen
 +
::                                  636      ::                                  0          Listen
 +
::                                  593      ::                                  0          Listen
 +
::                                  464      ::                                  0          Listen
 +
::                                  445      ::                                  0          Listen
 +
fe80::b586:d0e3:8c2b:2229%5        389      fe80::b586:d0e3:8c2b:2229%5        54671      Established Datacenter
 +
fe80::b586:d0e3:8c2b:2229%5        389      fe80::b586:d0e3:8c2b:2229%5        54667      Established Datacenter
 +
fe80::b586:d0e3:8c2b:2229%5        389      fe80::b586:d0e3:8c2b:2229%5        54663      Established Datacenter
 +
::1                                389      ::1                                54665      Established Datacenter
 +
::1                                389      ::1                                49680      Established Datacenter
 +
::1                                389      ::1                                49679      Established Datacenter
 +
::                                  389      ::                                  0          Listen
 +
::                                  135      ::                                  0          Listen
 +
::                                  88        ::                                  0          Listen
 +
fe80::b586:d0e3:8c2b:2229%5        53        ::                                  0          Listen
 +
::1                                53        ::                                  0          Listen
 +
0.0.0.0                            49715    0.0.0.0                            0          Listen
 +
0.0.0.0                            49692    0.0.0.0                            0          Listen
 +
0.0.0.0                            49686    0.0.0.0                            0          Listen
 +
0.0.0.0                            49676    0.0.0.0                            0          Listen
 +
0.0.0.0                            49675    0.0.0.0                            0          Listen
 +
0.0.0.0                            49668    0.0.0.0                            0          Listen
 +
192.168.200.129                    49666    192.168.200.216                    60179      Established Datacenter
 +
0.0.0.0                            49666    0.0.0.0                            0          Listen
 +
0.0.0.0                            49665    0.0.0.0                            0          Listen
 +
0.0.0.0                            49664    0.0.0.0                            0          Listen
 +
0.0.0.0                            9389      0.0.0.0                            0          Listen
 +
192.168.200.121                    3389      192.168.200.223                    64821      Established Datacenter
 +
0.0.0.0                            3389      0.0.0.0                            0          Listen
 +
0.0.0.0                            3269      0.0.0.0                            0          Listen
 +
0.0.0.0                            3268      0.0.0.0                            0          Listen
 +
0.0.0.0                            636      0.0.0.0                            0          Listen
 +
0.0.0.0                            593      0.0.0.0                            0          Listen
 +
0.0.0.0                            389      0.0.0.0                            0          Listen
 +
192.168.200.121                    139      0.0.0.0                            0          Listen
 +
0.0.0.0                            135      0.0.0.0                            0          Listen
 +
192.168.200.129                    53        0.0.0.0                            0          Listen
 +
192.168.200.121                    53        0.0.0.0                            0          Listen
 +
127.0.0.1                          53        0.0.0.0                            0          Listen
 +
 +
 +
Get-NetConnectionProfile:
 +
Name            : Unidentified network
 +
InterfaceAlias  : Ethernet
 +
InterfaceIndex  : 5
 +
NetworkCategory  : Public
 +
IPv4Connectivity : NoTraffic
 +
IPv6Connectivity : NoTraffic
 +
 +
 +
Get-DnsServerResourceRecord -ZoneName dawgland.com
 +
 +
HostName                  RecordType Type      Timestamp            TimeToLive      RecordData
 +
--------                  ---------- ----      ---------            ----------      ----------
 +
@                        A          1          2/21/2022 4:00:00 PM 00:10:00        192.168.200.129
 +
@                        A          1          2/21/2022 4:00:00 PM 00:10:00        192.168.200.121
 +
@                        NS        2          0                    01:00:00        win19vm10.dawgland.com.
 +
@                        SOA        6          0                    01:00:00        [33][win19vm10.dawgland.com.][h...
 +
_msdcs                    NS        2          0                    01:00:00        win19vm10.dawgland.com.
 +
_gc._tcp.Default-First... SRV        33        2/21/2022 4:00:00 PM 00:10:00        [0][100][3268][win19vm10.dawgla...
 +
_kerberos._tcp.Default... SRV        33        2/21/2022 4:00:00 PM 00:10:00        [0][100][88][win19vm10.dawgland...
 +
_ldap._tcp.Default-Fir... SRV        33        2/21/2022 4:00:00 PM 00:10:00        [0][100][389][win19vm10.dawglan...
 +
_gc._tcp                  SRV        33        2/21/2022 4:00:00 PM 00:10:00        [0][100][3268][win19vm10.dawgla...
 +
_kerberos._tcp            SRV        33        2/21/2022 4:00:00 PM 00:10:00        [0][100][88][win19vm10.dawgland...
 +
_kpasswd._tcp            SRV        33        2/21/2022 4:00:00 PM 00:10:00        [0][100][464][win19vm10.dawglan...
 +
_ldap._tcp                SRV        33        2/21/2022 4:00:00 PM 00:10:00        [0][100][389][win19vm10.dawglan...
 +
_kerberos._udp            SRV        33        2/21/2022 4:00:00 PM 00:10:00        [0][100][88][win19vm10.dawgland...
 +
_kpasswd._udp            SRV        33        2/21/2022 4:00:00 PM 00:10:00        [0][100][464][win19vm10.dawglan...
 +
DomainDnsZones            A          1          2/21/2022 4:00:00 PM 00:10:00        192.168.200.121
 +
DomainDnsZones            A          1          2/21/2022 4:00:00 PM 00:10:00        192.168.200.129
 +
_ldap._tcp.Default-Fir... SRV        33        2/21/2022 4:00:00 PM 00:10:00        [0][100][389][win19vm10.dawglan...
 +
_ldap._tcp.DomainDnsZones SRV        33        2/21/2022 4:00:00 PM 00:10:00        [0][100][389][win19vm10.dawglan...
 +
ForestDnsZones            A          1          2/21/2022 4:00:00 PM 00:10:00        192.168.200.121
 +
ForestDnsZones            A          1          2/21/2022 4:00:00 PM 00:10:00        192.168.200.129
 +
_ldap._tcp.Default-Fir... SRV        33        2/21/2022 4:00:00 PM 00:10:00        [0][100][389][win19vm10.dawglan...
 +
_ldap._tcp.ForestDnsZones SRV        33        2/21/2022 4:00:00 PM 00:10:00        [0][100][389][win19vm10.dawglan...
 +
win10vm8                  A          1          2/21/2022 9:00:00 PM 00:20:00        192.168.200.216
 +
win19vm10                A          1          0                    01:00:00        192.168.200.121
 +
win19vm10                A          1          0                    01:00:00        192.168.200.129
 +
 +
</pre>
 +
<br /><br />
 +
 +
== '''User Accounts and Groups''' ==
 +
List all local user and system accounts - NOT Part of AD(Active Directory)
 +
<pre style="color:blue">
 +
PS C:\Users\Jamie Rubinstein> Get-WmiObject -Class Win32_UserAccount
 +
 +
 +
AccountType : 512
 +
Caption    : DESKTOP-6462IKR\Administrator
 +
Domain      : DESKTOP-6462IKR
 +
SID        : S-1-5-21-3179005527-2571859427-2268210045-500
 +
FullName    :
 +
Name        : Administrator
 +
 +
AccountType : 512
 +
Caption    : DESKTOP-6462IKR\DefaultAccount
 +
Domain      : DESKTOP-6462IKR
 +
SID        : S-1-5-21-3179005527-2571859427-2268210045-503
 +
FullName    :
 +
Name        : DefaultAccount
 +
 +
AccountType : 512
 +
Caption    : DESKTOP-6462IKR\Guest
 +
Domain      : DESKTOP-6462IKR
 +
SID        : S-1-5-21-3179005527-2571859427-2268210045-501
 +
FullName    :
 +
Name        : Guest
 +
 +
AccountType : 512
 +
Caption    : DESKTOP-6462IKR\Jamie Rubinstein
 +
Domain      : DESKTOP-6462IKR
 +
SID        : S-1-5-21-3179005527-2571859427-2268210045-1001
 +
FullName    :
 +
Name        : Jamie Rubinstein
 +
 +
AccountType : 512
 +
Caption    : DESKTOP-6462IKR\WDAGUtilityAccount
 +
Domain      : DESKTOP-6462IKR
 +
SID        : S-1-5-21-3179005527-2571859427-2268210045-504
 +
FullName    :
 +
Name        : WDAGUtilityAccount
 +
 +
</pre>
 +
<br /><br />
 +
 +
You can now use the Get-LocalGroupMember, Get-LocalGroup, Get-LocalUser etc. from the Microsoft.PowerShell.LocalAccounts module to get and map users and groups, available in PowerShell 5.1 and above.
 +
 +
<br /><br />
 +
 +
Lists All Local Groups
 +
<pre style="color:blue">
 +
PS C:\Users\Jamie Rubinstein> Get-LocalGroup | Select-Object Name
 +
 +
Name
 +
----
 +
Access Control Assistance Operators
 +
Administrators
 +
Backup Operators
 +
Cryptographic Operators
 +
Device Owners
 +
Distributed COM Users
 +
Event Log Readers
 +
Guests
 +
Hyper-V Administrators
 +
IIS_IUSRS
 +
Network Configuration Operators
 +
Performance Log Users
 +
Performance Monitor Users
 +
Power Users
 +
Remote Desktop Users
 +
Remote Management Users
 +
Replicator
 +
System Managed Accounts Group
 +
Users
 +
</pre>
 +
<br /><br />
 +
 +
== '''More Useful Commands''' ==
 +
Create List of All Local Groups Along with All of the User Accounts in Each of the Groups
 +
<pre style="color:blue">
 +
Get-LocalGroup | %{ $groups = "$(Get-LocalGroupMember -Group $_.Name | %{ $_.Name } | Out-String)"; Write-Output "$($_.Name)>`r`n$($groups)`r`n" }
 +
Access Control Assistance Operators>
 +
 +
 +
Administrators>
 +
DESKTOP-6462IKR\Administrator
 +
DESKTOP-6462IKR\Jamie Rubinstein
 +
 +
 +
Backup Operators>
 +
 +
 +
Cryptographic Operators>
 +
 +
 +
Device Owners>
 +
 +
 +
Distributed COM Users>
 +
 +
 +
Event Log Readers>
 +
 +
 +
Guests>
 +
DESKTOP-6462IKR\Guest
 +
 +
 +
Hyper-V Administrators>
 +
 +
 +
IIS_IUSRS>
 +
NT AUTHORITY\IUSR
 +
 +
 +
Network Configuration Operators>
 +
 +
 +
Performance Log Users>
 +
 +
 +
Performance Monitor Users>
 +
 +
 +
Power Users>
 +
 +
 +
Remote Desktop Users>
 +
 +
 +
Remote Management Users>
 +
 +
 +
Replicator>
 +
 +
 +
System Managed Accounts Group>
 +
DESKTOP-6462IKR\DefaultAccount
 +
 +
 +
Users>
 +
NT AUTHORITY\Authenticated Users
 +
NT AUTHORITY\INTERACTIVE
 +
</pre>
 +
<br /><br />
 +
 +
Rename Computer Using PowerShell - '''MUST BE DONE FROM ADMINISTRATOR ELEVATED SHELL, OR THE COMMAND WILL FAIL!!!
 +
<br />
 +
First, open up an elevated shell sos you are the "Administrator", as follows:
 +
<pre style="color:blue">
 +
PS C:\Users\Jamie Rubinstein> Start-Process powershell -verb runas
 +
 +
</pre>
 +
<br />
 +
It will prompt you to allow it to make changes - Click on "YES"!
 +
<br />
 +
It will then open up a new PowerShell window, most likely with a blue background to remind you to be careful with anything you type since you are not in
 +
<br />
 +
Adminstrator mode, which can be very dangerous if you are not sure about what commands to type!
 +
<br /><br />
 +
In the new Adminstrator shell window, type the following command to rename your computer to what you want it to be:
 +
<pre style="color:blue">
 +
PS C:\WindowPS C:\Users\Jamie Rubinstein> Rename-Computer -NewName "win11tinyvm02"
 +
 +
</pre>
 +
<br /><br />
 +
 +
It will display this notice:
 +
<pre style="color:blue">
 +
WARNING: The changes will take effect after you restart the computer DESKTOP-6462IKR.
 +
PS C:\Windows\system32>
 +
</pre>
 +
<br /><br />
 +
 +
You can reboot the system immediately from the PowerShell command window, by typing this command:
 +
<pre style="color:blue">
 +
PS C:\Users\Jamie Rubinstein> shutdown /r /t 0
 +
</pre>
 +
<br /><br />
 +
If you'd rather just shut the system down for now, instead of rebooting, change the /r in the above command to /s, like this:
 +
<pre style="color:blue">
 +
PS C:\Users\Jamie Rubinstein> shutdown /s /t 0
 +
</pre>
 +
<br /><br />
 +
Changing lock sceen time-out using the command line:
 +
<br />
 +
Open a new command-prompt window as Administrator, and use this command, substituting the last number "300" to what you want, without the quotes.  "300" equals 5 minutes.  "0" equals "NEVER".
 +
<pre style="color:blue">
 +
powercfg.exe /SETACVALUEINDEX SCHEME_CURRENT SUB_VIDEO VIDEOCONLOCK 300
 +
</pre>
 +
<br /><br />

Latest revision as of 19:57, 13 November 2024

Windows PowerShell Information

Enabling PowerShell Script Execution

Running PowerShell Commands as Administrator - Needed for System/Server/User Administration

Many, if not most, administrative PowerShell commands require being run as the Administrator user or what is referred to as elevated privileges. Depending on if you are wanting to open a window from a CMD/Command prompt, or if you are opening it from a PowerShell command prompt, the process is very similar.

From PowerShell, here is the command to open an elevated PowerShell window to then run administrative command from:

PS C:\Users\jamie.DAWGLAND> Start-Process powershell -verb runas


This will open up a new PowerShell window with administrative privileges.

If you are in a CMD/DOS/Command Prompt, first type "powershell" to start PowerShell, and then just follow the above commands to open an elevated PowerShell window in which you can then run administrative commands to manage your system.


Setup Windows Command-line(CMD) Aliases Similar to Alias in Linux/UNIX

I find the ability to creating and using custom "shortcut" commands, commonly referred to "Aliases".
Traditionally, the Windows/DOS command "DOSKEY" is used to create complex command "alias" commands, to make administration of Windows/DOS based computers much easier and quicker.
As I am obviously a Linux guy, I always prefer the "Linux/UNIX" way of doing things. That's why one of the first things I do on any new Windows computer is to install the command-line "GIT" tools, which include many of the most common Linux command-line tools and configures the Windows command-line terminal to look and function like Linux terminals.
Instead of using DOSKEY, I find the solution at this URL to be best for my needs: https://superuser.com/questions/183475/how-to-alias-commands-on-windows-command-prompt

REAL Aliases with Powershell

Powershell actually has full support for "Real" aliases! It contains many built-in aliases, and has the ability to create any type of custom alias you can imagine!

To list the basic commands used to manage aliases using Powershell, use this command from a Powershell prompt:

PS C:\Users\jamie> Get-Command -Noun Alias 



The output of the command should look like this:

CommandType     Name                                               Version    Source
-----------     ----                                               -------    ------
Cmdlet          Export-Alias                                       3.1.0.0    Microsoft.PowerShell.Utility
Cmdlet          Get-Alias                                          3.1.0.0    Microsoft.PowerShell.Utility
Cmdlet          Import-Alias                                       3.1.0.0    Microsoft.PowerShell.Utility
Cmdlet          New-Alias                                          3.1.0.0    Microsoft.PowerShell.Utility
Cmdlet          Set-Alias                                          3.1.0.0    Microsoft.PowerShell.Utility


PS C:\Users\jamie>



Use the Get-Alias commandlet to list the aliases available in the current environment:

PS C:\Users\jamie> Get-Alias -Definition Get-ChildItem

CommandType     Name                                               Version    Source
-----------     ----                                               -------    ------
Alias           dir -> Get-ChildItem
Alias           gci -> Get-ChildItem
Alias           ls -> Get-ChildItem

PS C:\Users\jamie>



To see the definition of a single alias, use the "Name" parameter:

PS C:\Users\jamie> Get-Alias -Name gci

CommandType     Name                                               Version    Source
-----------     ----                                               -------    ------
Alias           gci -> Get-ChildItem

PS C:\Users\jamie>



Use the Set-Alias command to create a new custom alias:

PS C:\Users\jamie> Set-Alias -Name chkadm -Value "(New-Object Security.Principal.WindowsPrincipal([Security.Principal.WindowsIdentity]::GetCurrent())).IsInRole([Security.Principal.WindowsBuiltInRole]::Administrator)"




Here is a URl at Microsoft listing all Powershell built-in aliases, as well as information on how to create your own custom alias for use with Powershell.
https://learn.microsoft.com/en-us/powershell/scripting/learn/shell/using-aliases?view=powershell-7.4

DOS/CMD - Miscellaneous Command Line Commands

This command shows how long a Windows computer has been powered on since the last time it was shut down or rebooted, which can be helpful when diagnosing issues with a sluggish, slow-responding system. this is also known as a system's "Uptime". This is the command along with its output. Note the line starting with "Statistics since", which shows the actual date and time the system was last powered on.

C:\Users\Administrator.DAWGLAND>net stats workstation
Workstation Statistics for \\WIN22VM01


Statistics since 2/6/2023 10:22:32 AM


  Bytes received                               502580
  Server Message Blocks (SMBs) received        2
  Bytes transmitted                            952389
  Server Message Blocks (SMBs) transmitted     0
  Read operations                              366
  Write operations                             0
  Raw reads denied                             0
  Raw writes denied                            0

  Network errors                               0
  Connections made                             0
  Reconnections made                           0
  Server disconnects                           0

  Sessions started                             0
  Hung sessions                                0
  Failed sessions                              0
  Failed operations                            0
  Use count                                    109
  Failed use count                             0

The command completed successfully.



You can trim/filter out most of the output, so that you only get the actual info you are looking for, in this case, the two-word phrase "Statistics since". This is how you would do it, "piping" the output of the previous command into the "findstr" command to find the line(s) containg the phrase "Statics since", case sensitive:

PS C:\Users\Administrator.DAWGLAND> net stats workstation | findstr /C:"Statistics since"
Statistics since 2/6/2023 10:22:32 AM



You can shorten the command even further if you instead of searching for the two-word phrase "Statistics since", you can just search for/find the one word "since", as it's the only line in the entire output of the "net stats workstation" command that contains that one word. Here's an example:

PS C:\Users\Administrator.DAWGLAND> net stats workstation | findstr since
Statistics since 2/6/2023 10:22:32 AM



Enabling & Configuring OpenSSH Server on Windows Using PowerShell

First, confirm the current state of the OpenSSH Server and OpenSSH Clients, whether either are installed, enabled, and configured.

Type this command to check the current status of both the server and client:

PS C:\Users\Administrator.DAWGLAND> Get-WindowsCapability -Online | ? Name -like 'OpenSSH*'


Name  : OpenSSH.Client~~~~0.0.1.0
State : Installed

Name  : OpenSSH.Server~~~~0.0.1.0
State : NotPresent



As you can see from output of the above command, OpenSSH Client is installed on the server, but OpenSSH Server is "NotPresent", meaning it's not been installed/enabled on the server yet. Will fix that next so that users can log into the Windows server using SSH, the Secure Shell to remotely connect annd manage the server.

Use this PowerShell command to install/enable the OpenSSH Server:

PS C:\Users\Administrator.DAWGLAND> Add-WindowsCapability -Online -Name OpenSSH.Server~~~~0.0.1.0


Path          :
Online        : True
RestartNeeded : False



Run the previous "Get-WindowsCapability -Online | ? Name -like 'OpenSSH*'" command and confirm that OpenSSH Server is now installed.

Next, manually start the OpenSSH service, like this:

PS C:\Users\Administrator.DAWGLAND> Start-Service sshd
WARNING: Waiting for service 'OpenSSH SSH Server (sshd)' to start...



You can use this command to confirm the SSH server service has been started and is now running:

PS C:\Users\Administrator.DAWGLAND> Get-Service | findstr -i sshd
Running  sshd               OpenSSH SSH Server



Use this command to check on the startup type, referring to the setting to have the OpenSSH Server startup automatically on each computer reboot or power on.

PS C:\Users\jamie.DAWGLAND> Get-Service -Name sshd | Select -property name,starttype

Name StartType
---- ---------
sshd    Manual

As you can see from the output of the above command, the "StartType" for "sshd"(sshd stands for "SecureSHell Daemon". Daemon is another word for "Server".

As we want to always be able to securly log into the server remotely to perform routine maintenance and configuration, we want to configure the SSHD(OpenSSH Server) to automatically start up every time the computer is started up or rebooted. Here's how:

PS C:\Users\jamie\Downloads> Set-Service -Name sshd -StartupType 'Automatic'



Now, confirm it's set to start up automatically:

PS C:\Users\jamie\Downloads> Get-Service -Name sshd | Select -property name,star
ttype

Name StartType
---- ---------
sshd Automatic



Confirm firewall rule has been created for the SSH service:

PS C:\Users\jamie.DAWGLAND> Get-NetFirewallRule -Name *ssh*


Name                          : OpenSSH-Server-In-TCP
DisplayName                   : OpenSSH SSH Server (sshd)
Description                   : Inbound rule for OpenSSH SSH Server (sshd)      
DisplayGroup                  : OpenSSH Server
Group                         : OpenSSH Server
Enabled                       : True
Profile                       : Any
Platform                      : {}
Direction                     : Inbound
Action                        : Allow
EdgeTraversalPolicy           : Block
LooseSourceMapping            : False
LocalOnlyMapping              : False
Owner                         :
PrimaryStatus                 : OK
Status                        : The rule was parsed successfully from the       
                                store. (65536)
EnforcementStatus             : NotApplicable
PolicyStoreSource             : PersistentStore
PolicyStoreSourceType         : Local
RemoteDynamicKeywordAddresses : {}



Finally, last, but not least, configure PowerShell to be the default environment when logging into the Windows server using SSH protocol. Here's the command:

PS C:\Users\jamie.DAWGLAND> New-ItemProperty -Path "HKLM:\SOFTWARE\OpenSSH" -Name DefaultShell -Value "C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe" -PropertyType String -Force


DefaultShell : C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe        
PSPath       : Microsoft.PowerShell.Core\Registry::HKEY_LOCAL_MACHINE\SOFTWARE\ 
               OpenSSH
PSParentPath : Microsoft.PowerShell.Core\Registry::HKEY_LOCAL_MACHINE\SOFTWARE  
PSChildName  : OpenSSH
PSDrive      : HKLM
PSProvider   : Microsoft.PowerShell.Core\Registry



AD-DS - Active Directory - Domain Services

Here is the DOS/CMD command to show the current state of each of the 5 FSMO roles configured for MS AD-DS using the "netdom query fsmo" command:

C:\Users\Administrator.DAWGLAND>netdom query fsmo
Schema master               win19vm10.dawgland.com
Domain naming master        win19vm10.dawgland.com
PDC                         win19vm10.dawgland.com
RID pool manager            win19vm10.dawgland.com
Infrastructure master       win19vm10.dawgland.com
The command completed successfully.



As you can see from the output of the "netdom query fsmo" command, all 5 roles are hosted on the same Windows Server 2019 machine/VM. This is required information when it comes time to migrate AD-DS from an older server to a newwer server with a newer version of MS Windows Server.

Miscellaneous PowerShell Commands

Here are some of the PowerShell commands I use regularily to to manage Windows machines:

Create NEW Active Directory Domain Controller/AD DS:
Install-WindowsFeature -Name AD-Domain-Services -IncludeManagementTools
Install-ADDSForest -DomainName thebestlinux.net -DomainNetbiosName THEBESTLINUX -InstallDNS
OTHER COMMANDS:
Disable IPv6 on ALL NIC’s:
Disable-NetAdapterBinding -Name Ethernet* -ComponentID ms_tcpip6
Get-NetTCPConnection
Get-NetConnectionProfile
Get-NetAdapter
Set-DnsClientServerAddress -InterfaceIndex 3 -ServerAddresses ("192.168.200.103","192.168.200.121","75.75.76.76")
Install-Module PSWindowsUpdate
Set-PSRepository
Add-WUServiceManager -MicrosoftUpdate
Get-WindowsUpdate
Get-Service | findstr Admin
sc queryex type=service state=all
Get-ItemProperty HKLM:\Software\Wow6432Node\Microsoft\Windows\CurrentVersion\Uninstall\* | Select-Object DisplayName, DisplayVersion, Publisher, InstallDate | Format-Table -AutoSize
Get-WindowsFeature
Get-package | Select-Object Name,Version
Get-WindowsUpdate -v
Get-ItemProperty HKLM:\Software\Wow6432Node\Microsoft\Windows\CurrentVersion\Uninstall\* | Select-Object DisplayName, DisplayVersion, Publisher, InstallDate | Format-Table -AutoSize
New-ADUser /?
get-localuser
get-roles
Get-DnsServerResourceRecord dawgland.com
Get-DnsServerQueryResolutionPolicy
dcdiag /a
CONFIRM ALL 5 Roles of Active Directory Servers are up and running!!!:
Get-ADDomain dawgland.com | Format-Table PDCEmulator,RIDMaster,InfrastructureMaster
Get-ADForest dawgland.com | Format-Table SchemaMaster,DomainNamingMaster
Get-DnsServerResourceRecord -ZoneName dawgland.com
Get-NetConnectionProfile
Get-NetTCPConnection
Get-CimInstance -Class CIM_LogicalDisk
Get-DiskFreeSpace
Get-GPRegistryValue -Key HKEY_LOCAL_MACHINE
Get-GPRegistryValue -Guid 31b2f340-016d-11d2-945f-00c04fb984f9 -Key HKEY_LOCAL_MACHINE
Add-WindowsCapability -Online -Name OpenSSH.Server~~~~0.0.1.0
Import-Module GroupPolicy -verbose



Hardware Related PowerShell Commands

Display Hard Drive Information:

S C:\Users\Administrator> Get-Disk

Number Friendly Name                Serial Number                    HealthStatus         OperationalStatus      Total Size Partition 
                                                                                                                            Style     
------ -------------                -------------                    ------------         -----------------      ---------- ----------
0      VMware Virtual disk          6000c29e5f1b1b3e5150ace9c505b4a3 Healthy              Online                      25 GB GPT 



Display Disk Drive Volumes:

PS C:\Users\Administrator> Get-Volume

DriveLetter FriendlyName FileSystemType DriveType HealthStatus OperationalStatus SizeRemaining     Size
----------- ------------ -------------- --------- ------------ ----------------- -------------     ----
                         NTFS           Fixed     Healthy      OK                     83.41 MB   523 MB
                         FAT32          Fixed     Healthy      OK                     68.17 MB    96 MB
C                        NTFS           Fixed     Healthy      OK                     13.53 GB 24.37 GB
D                        Unknown        CD-ROM    Healthy      Unknown                     0 B      0 B



More PowerShell Commands with Some Examples

Here are some more commands I use when working on headless Windows Server hardware and virual machines, such as

Windows Server Core:


Open a Windows command prompt as Administrator:
runas /user:administrator CMD.exe

List Installed Apps:
Get-ItemProperty HKLM:\Software\Wow6432Node\Microsoft\Windows\CurrentVersion\Uninstall\* | Select-Object DisplayName, DisplayVersion, Publisher, InstallDate | Format-Table –AutoSize

Install Failover Cluster Tools:
Install-WindowsFeature -Name Failover-Clustering –IncludeManagementTools
Include command line management tools:
Install-WindowsFeature RSAT-Clustering-CmdInterface

Find out if package is installed.  This example uses GIT:
PS C:\Users\Administrator> Get-Package | Select-Object Name | findstr -i git
Git

Find out if package is installed.  This exampled uses WAC(Windows Admin Center):
PS C:\Users\Administrator> get-package | select-object Name | findstr -i Admin
Windows Admin Center

Another way to do same as above, but more “Precise”.  Can USE WILD-CARDS!!!:
PS C:\Users\Administrator> get-package | Where-Object {$_.Name -like "*Windows Admin Center*"}

Name                           Version          Source                           ProviderName
----                           -------          ------                           ------------
Windows Admin Center           1.3.53858.0      C:\Program Files\Windows Admi... msi


Display ALL services installed and their status:
Get-Service | Select-Object Name,Status,DisplayName

Check Status of Windows Admin Center(IF Installed – Otherwise will not find it!
Get-Service | Select-Object Name,Status,DisplayName | findstr Admin
FINDS: 
“ServerManagementGateway”, the ACTUAL name of WAC!
ServerManagementGateway                  Running Windows Admin Center Service
ServerManagementGatewayAccount           Stopped Windows Admin Center Account Service

Configure DNS Servers:
Set-DnsClientServerAddress -InterfaceIndex 3 -ServerAddresses ("192.168.200.103","192.168.200.121","75.75.76.76")

Disable ALL Firewall Zones:
Set-NetFirewallProfile -Profile Domain,Public,Private -Enabled False

Enable a port through firewall:
netsh advfirewall firewall add rule name="WinRM-HTTP" dir=in localport=5985 protocol=TCP action=allow

Check if Windows Admin Center has been installed:
Get-WmiObject -Class win32_service | Where-Object {$_.name -like "WinRM"}

Download a file using PowerShell:
$WebClient = New-Object System.Net.WebClient
$WebClient.DownloadFile("http://192.168.200.125/WindowsAdminCenter2110.2.msi","C:\Users\Administrator\WindowsAdminCenter2110.2.msi")

Check EvenLogs for logins, failures, apps, etc:
get-eventlog -list
get-eventlog Application -after (get-date).addhours(-1)
get-eventlog Application -after (get-date).addhours(-8)

USE Security log for checking logins:
get-eventlog Security -after (get-date).addhours(-1)

FORMATTING Example of explicit log index number:
Get-EventLog Security | where index -eq 3704 | format-list *

DOWNLOAD & Install MS SQL Server:
$wc=new-object system.net.webclient
$wc.downloadfile("https://go.microsoft.com/fwlink/?linkid=866662","SQL2019-SSEI-Dev.exe")

GIT Download:
$wc.downloadfile("https://github.com/git-for-windows/git/releases/download/v2.36.0.windows.1/Git-2.36.0-64-bit.exe","Git-2.36.0-64-bit.exe")

Get-Service -Name vds
get-service | Where-Object {$_.status -eq "stopped"}
get-service -name wisvc

PS C:\Users\Administrator> get-service | grep -i admin
Stopped  sacsvr             Special Administration Console Helper
Running  ServerManagemen... Windows Admin Center Service
Stopped  ServerManagemen... Windows Admin Center Account Service
PS C:\Users\Administrator>

Get-Item WSMan:\localhost\Client\TrustedHosts

Get-CimInstance -Class CIM_LogicalDisk

DeviceID DriveType ProviderName VolumeName Size        FreeSpace
-------- --------- ------------ ---------- ----        ---------
C:       3                                 53109321728 44553736192
D:       5


Get-NetTCPConnection

LocalAddress                        LocalPort RemoteAddress                       RemotePort State       AppliedSetting
------------                        --------- -------------                       ---------- -----       --------------
::                                  56357     ::                                  0          Bound
::                                  56268     ::                                  0          Bound
::                                  54693     ::                                  0          Bound
::                                  54690     ::                                  0          Bound
::                                  54689     ::                                  0          Bound
::                                  54688     ::                                  0          Bound
::                                  54687     ::                                  0          Bound
::                                  54671     ::                                  0          Bound
::                                  54667     ::                                  0          Bound
::                                  54665     ::                                  0          Bound
::                                  54663     ::                                  0          Bound
::                                  49712     ::                                  0          Bound
::                                  49706     ::                                  0          Bound
::                                  49695     ::                                  0          Bound
::                                  49680     ::                                  0          Bound
::                                  49679     ::                                  0          Bound
::1                                 56357     ::1                                 49666      Established Datacenter
fe80::b586:d0e3:8c2b:2229%5         56268     fe80::b586:d0e3:8c2b:2229%5         49666      Established Datacenter
fe80::b586:d0e3:8c2b:2229%5         54815     fe80::b586:d0e3:8c2b:2229%5         135        TimeWait
fe80::b586:d0e3:8c2b:2229%5         54671     fe80::b586:d0e3:8c2b:2229%5         389        Established Datacenter
fe80::b586:d0e3:8c2b:2229%5         54667     fe80::b586:d0e3:8c2b:2229%5         389        Established Datacenter
::1                                 54665     ::1                                 389        Established Datacenter
fe80::b586:d0e3:8c2b:2229%5         54663     fe80::b586:d0e3:8c2b:2229%5         389        Established Datacenter
::                                  49715     ::                                  0          Listen
fe80::b586:d0e3:8c2b:2229%5         49712     fe80::b586:d0e3:8c2b:2229%5         49666      Established Datacenter
fe80::b586:d0e3:8c2b:2229%5         49695     fe80::b586:d0e3:8c2b:2229%5         49666      Established Datacenter
::                                  49692     ::                                  0          Listen
::                                  49686     ::                                  0          Listen
::1                                 49680     ::1                                 389        Established Internet
::1                                 49679     ::1                                 389        Established Datacenter
::                                  49676     ::                                  0          Listen
::                                  49675     ::                                  0          Listen
::                                  49668     ::                                  0          Listen
fe80::b586:d0e3:8c2b:2229%5         49666     fe80::b586:d0e3:8c2b:2229%5         56268      Established Datacenter
fe80::b586:d0e3:8c2b:2229%5         49666     fe80::b586:d0e3:8c2b:2229%5         49712      Established Datacenter
fe80::b586:d0e3:8c2b:2229%5         49666     fe80::b586:d0e3:8c2b:2229%5         49695      Established Datacenter
::1                                 49666     ::1                                 56357      Established Datacenter
::                                  49666     ::                                  0          Listen
::                                  49665     ::                                  0          Listen
::                                  49664     ::                                  0          Listen
::                                  47001     ::                                  0          Listen
::                                  9389      ::                                  0          Listen
::                                  5985      ::                                  0          Listen
::                                  3389      ::                                  0          Listen
::                                  3269      ::                                  0          Listen
::                                  3268      ::                                  0          Listen
::                                  636       ::                                  0          Listen
::                                  593       ::                                  0          Listen
::                                  464       ::                                  0          Listen
::                                  445       ::                                  0          Listen
fe80::b586:d0e3:8c2b:2229%5         389       fe80::b586:d0e3:8c2b:2229%5         54671      Established Datacenter
fe80::b586:d0e3:8c2b:2229%5         389       fe80::b586:d0e3:8c2b:2229%5         54667      Established Datacenter
fe80::b586:d0e3:8c2b:2229%5         389       fe80::b586:d0e3:8c2b:2229%5         54663      Established Datacenter
::1                                 389       ::1                                 54665      Established Datacenter
::1                                 389       ::1                                 49680      Established Datacenter
::1                                 389       ::1                                 49679      Established Datacenter
::                                  389       ::                                  0          Listen
::                                  135       ::                                  0          Listen
::                                  88        ::                                  0          Listen
fe80::b586:d0e3:8c2b:2229%5         53        ::                                  0          Listen
::1                                 53        ::                                  0          Listen
0.0.0.0                             49715     0.0.0.0                             0          Listen
0.0.0.0                             49692     0.0.0.0                             0          Listen
0.0.0.0                             49686     0.0.0.0                             0          Listen
0.0.0.0                             49676     0.0.0.0                             0          Listen
0.0.0.0                             49675     0.0.0.0                             0          Listen
0.0.0.0                             49668     0.0.0.0                             0          Listen
192.168.200.129                     49666     192.168.200.216                     60179      Established Datacenter
0.0.0.0                             49666     0.0.0.0                             0          Listen
0.0.0.0                             49665     0.0.0.0                             0          Listen
0.0.0.0                             49664     0.0.0.0                             0          Listen
0.0.0.0                             9389      0.0.0.0                             0          Listen
192.168.200.121                     3389      192.168.200.223                     64821      Established Datacenter
0.0.0.0                             3389      0.0.0.0                             0          Listen
0.0.0.0                             3269      0.0.0.0                             0          Listen
0.0.0.0                             3268      0.0.0.0                             0          Listen
0.0.0.0                             636       0.0.0.0                             0          Listen
0.0.0.0                             593       0.0.0.0                             0          Listen
0.0.0.0                             389       0.0.0.0                             0          Listen
192.168.200.121                     139       0.0.0.0                             0          Listen
0.0.0.0                             135       0.0.0.0                             0          Listen
192.168.200.129                     53        0.0.0.0                             0          Listen
192.168.200.121                     53        0.0.0.0                             0          Listen
127.0.0.1                           53        0.0.0.0                             0          Listen


Get-NetConnectionProfile:
Name             : Unidentified network
InterfaceAlias   : Ethernet
InterfaceIndex   : 5
NetworkCategory  : Public
IPv4Connectivity : NoTraffic
IPv6Connectivity : NoTraffic


Get-DnsServerResourceRecord -ZoneName dawgland.com

HostName                  RecordType Type       Timestamp            TimeToLive      RecordData
--------                  ---------- ----       ---------            ----------      ----------
@                         A          1          2/21/2022 4:00:00 PM 00:10:00        192.168.200.129
@                         A          1          2/21/2022 4:00:00 PM 00:10:00        192.168.200.121
@                         NS         2          0                    01:00:00        win19vm10.dawgland.com.
@                         SOA        6          0                    01:00:00        [33][win19vm10.dawgland.com.][h...
_msdcs                    NS         2          0                    01:00:00        win19vm10.dawgland.com.
_gc._tcp.Default-First... SRV        33         2/21/2022 4:00:00 PM 00:10:00        [0][100][3268][win19vm10.dawgla...
_kerberos._tcp.Default... SRV        33         2/21/2022 4:00:00 PM 00:10:00        [0][100][88][win19vm10.dawgland...
_ldap._tcp.Default-Fir... SRV        33         2/21/2022 4:00:00 PM 00:10:00        [0][100][389][win19vm10.dawglan...
_gc._tcp                  SRV        33         2/21/2022 4:00:00 PM 00:10:00        [0][100][3268][win19vm10.dawgla...
_kerberos._tcp            SRV        33         2/21/2022 4:00:00 PM 00:10:00        [0][100][88][win19vm10.dawgland...
_kpasswd._tcp             SRV        33         2/21/2022 4:00:00 PM 00:10:00        [0][100][464][win19vm10.dawglan...
_ldap._tcp                SRV        33         2/21/2022 4:00:00 PM 00:10:00        [0][100][389][win19vm10.dawglan...
_kerberos._udp            SRV        33         2/21/2022 4:00:00 PM 00:10:00        [0][100][88][win19vm10.dawgland...
_kpasswd._udp             SRV        33         2/21/2022 4:00:00 PM 00:10:00        [0][100][464][win19vm10.dawglan...
DomainDnsZones            A          1          2/21/2022 4:00:00 PM 00:10:00        192.168.200.121
DomainDnsZones            A          1          2/21/2022 4:00:00 PM 00:10:00        192.168.200.129
_ldap._tcp.Default-Fir... SRV        33         2/21/2022 4:00:00 PM 00:10:00        [0][100][389][win19vm10.dawglan...
_ldap._tcp.DomainDnsZones SRV        33         2/21/2022 4:00:00 PM 00:10:00        [0][100][389][win19vm10.dawglan...
ForestDnsZones            A          1          2/21/2022 4:00:00 PM 00:10:00        192.168.200.121
ForestDnsZones            A          1          2/21/2022 4:00:00 PM 00:10:00        192.168.200.129
_ldap._tcp.Default-Fir... SRV        33         2/21/2022 4:00:00 PM 00:10:00        [0][100][389][win19vm10.dawglan...
_ldap._tcp.ForestDnsZones SRV        33         2/21/2022 4:00:00 PM 00:10:00        [0][100][389][win19vm10.dawglan...
win10vm8                  A          1          2/21/2022 9:00:00 PM 00:20:00        192.168.200.216
win19vm10                 A          1          0                    01:00:00        192.168.200.121
win19vm10                 A          1          0                    01:00:00        192.168.200.129



User Accounts and Groups

List all local user and system accounts - NOT Part of AD(Active Directory)

PS C:\Users\Jamie Rubinstein> Get-WmiObject -Class Win32_UserAccount


AccountType : 512
Caption     : DESKTOP-6462IKR\Administrator
Domain      : DESKTOP-6462IKR
SID         : S-1-5-21-3179005527-2571859427-2268210045-500
FullName    :
Name        : Administrator

AccountType : 512
Caption     : DESKTOP-6462IKR\DefaultAccount
Domain      : DESKTOP-6462IKR
SID         : S-1-5-21-3179005527-2571859427-2268210045-503
FullName    :
Name        : DefaultAccount

AccountType : 512
Caption     : DESKTOP-6462IKR\Guest
Domain      : DESKTOP-6462IKR
SID         : S-1-5-21-3179005527-2571859427-2268210045-501
FullName    :
Name        : Guest

AccountType : 512
Caption     : DESKTOP-6462IKR\Jamie Rubinstein
Domain      : DESKTOP-6462IKR
SID         : S-1-5-21-3179005527-2571859427-2268210045-1001
FullName    :
Name        : Jamie Rubinstein

AccountType : 512
Caption     : DESKTOP-6462IKR\WDAGUtilityAccount
Domain      : DESKTOP-6462IKR
SID         : S-1-5-21-3179005527-2571859427-2268210045-504
FullName    :
Name        : WDAGUtilityAccount



You can now use the Get-LocalGroupMember, Get-LocalGroup, Get-LocalUser etc. from the Microsoft.PowerShell.LocalAccounts module to get and map users and groups, available in PowerShell 5.1 and above.



Lists All Local Groups

PS C:\Users\Jamie Rubinstein> Get-LocalGroup | Select-Object Name

Name
----
Access Control Assistance Operators
Administrators
Backup Operators
Cryptographic Operators
Device Owners
Distributed COM Users
Event Log Readers
Guests
Hyper-V Administrators
IIS_IUSRS
Network Configuration Operators
Performance Log Users
Performance Monitor Users
Power Users
Remote Desktop Users
Remote Management Users
Replicator
System Managed Accounts Group
Users



More Useful Commands

Create List of All Local Groups Along with All of the User Accounts in Each of the Groups

Get-LocalGroup | %{ $groups = "$(Get-LocalGroupMember -Group $_.Name | %{ $_.Name } | Out-String)"; Write-Output "$($_.Name)>`r`n$($groups)`r`n" }
Access Control Assistance Operators>


Administrators>
DESKTOP-6462IKR\Administrator
DESKTOP-6462IKR\Jamie Rubinstein


Backup Operators>


Cryptographic Operators>


Device Owners>


Distributed COM Users>


Event Log Readers>


Guests>
DESKTOP-6462IKR\Guest


Hyper-V Administrators>


IIS_IUSRS>
NT AUTHORITY\IUSR


Network Configuration Operators>


Performance Log Users>


Performance Monitor Users>


Power Users>


Remote Desktop Users>


Remote Management Users>


Replicator>


System Managed Accounts Group>
DESKTOP-6462IKR\DefaultAccount


Users>
NT AUTHORITY\Authenticated Users
NT AUTHORITY\INTERACTIVE



Rename Computer Using PowerShell - MUST BE DONE FROM ADMINISTRATOR ELEVATED SHELL, OR THE COMMAND WILL FAIL!!!
First, open up an elevated shell sos you are the "Administrator", as follows:

PS C:\Users\Jamie Rubinstein> Start-Process powershell -verb runas


It will prompt you to allow it to make changes - Click on "YES"!
It will then open up a new PowerShell window, most likely with a blue background to remind you to be careful with anything you type since you are not in
Adminstrator mode, which can be very dangerous if you are not sure about what commands to type!

In the new Adminstrator shell window, type the following command to rename your computer to what you want it to be:

PS C:\WindowPS C:\Users\Jamie Rubinstein> Rename-Computer -NewName "win11tinyvm02"



It will display this notice:

WARNING: The changes will take effect after you restart the computer DESKTOP-6462IKR.
PS C:\Windows\system32>



You can reboot the system immediately from the PowerShell command window, by typing this command:

PS C:\Users\Jamie Rubinstein> shutdown /r /t 0



If you'd rather just shut the system down for now, instead of rebooting, change the /r in the above command to /s, like this:

PS C:\Users\Jamie Rubinstein> shutdown /s /t 0



Changing lock sceen time-out using the command line:
Open a new command-prompt window as Administrator, and use this command, substituting the last number "300" to what you want, without the quotes. "300" equals 5 minutes. "0" equals "NEVER".

powercfg.exe /SETACVALUEINDEX SCHEME_CURRENT SUB_VIDEO VIDEOCONLOCK 300