Install Microsoft OpenSSH.Server package from PowerShell and set SSHD service to Automatic

#Install Microsoft OpenSSH.Server package from PowerShell and set SSHD service to Automatic


#Just the code:

Add-WindowsCapability -Online -Name OpenSSH.Server~~~~0.0.1.0
Get-Service -Name sshd|Set-Service -StartupType 'Automatic'
Get-Service -Name sshd|Start-Service

#The long story…

#Add OpenSSH Server capability to Windows 10 and Windows Server 2019

#OpenSSH Server needs to be installed via Remote Desktop Protocol (RDP) or from a local PowerShell session to allow incoming SSH connections and tunnels.

#OpenSSH Client is now included with Microsoft Windows 10 and Microsoft Windows Servers. This package only needs to be installed on the remote side of a tunnel. OpenSSH Client is required on the computer initiating the connections or tunnels and is installed by default in the latest version of Windows 10, Windows Server 2019 and Windows Server 2022.

#Add-WindowsCapability does not work for the OpenSSH.Server package via Enter-PSSession for some reason.

Add-WindowsCapability -Online -Name OpenSSH.Server~~~~0.0.1.0

#Set the SSHD service to Automatic

Get-Service -Name sshd|Set-Service -StartupType 'Automatic'

#Start the SSHD service

Get-Service -Name sshd|Start-Service

#Use this command to verify that OpenSSH Client is installed

(Get-WindowsCapability -Online|? Name -like 'OpenSSH.Client*').State

#Verify the incoming Windows Firewall rules for OpenSSH Server were properly created

Get-NetFirewallRule -Name "OpenSSH-Server-In-TCP"

Use PowerShell to create an SSH tunnel for a Remote Desktop Connection (RDP) to another computer with OpenSSH-Server installed

#Use PowerShell to create an SSH tunnel for a Remote Desktop Connection (RDP) to another computer with OpenSSH-Server installed


#Just the code:

Start-Process ssh -ArgumentList "-N -L 127.0.0.3:13389:10.4.0.12:3389 10.4.0.12 -l sshuser" -Verb open
(Read-Host 'Press Enter to continue...')|Out-Null
&mstsc /V:127.0.0.3:13389 /prompt

#The Long Story…

#Remote Desktop Protocol (RDP) is great but it is not very secure. This is one way to make your RDP connections more secure using a Secure Shell (SSH) tunnel.

#Install SSH Server on Windows 10 or Windows 2019

http://winrollup.com/install-microsoft-openssh-server-package-from-powershell-and-set-sshd-service-to-automatic

#Use PowerShell to open SSH in a cmd.exe window that will control the SSH tunnel.

Start-Process ssh -ArgumentList "-N -L 127.0.0.3:13389:10.4.0.12:3389 10.4.0.12 -l sshuser" -Verb open

#The commands will pause while you login to the SSH tunnel session. In this example 127.0.0.3:13889 is the tunnel entrance. 10.4.0.12:3389 is the tunnel destination and will most likely be different for you. In my case it is a Microsoft Windows Server 2019 server that I connect to from a Windows 10 Professional client.

#10.4.0.12 is the address of the SSH server and sshuser is an account on the destination machine. The account used doesn’t need additional rights beyond User rights on Windows 10 to create the tunnel but you will need additional rights to connect via RDP.

#Login to SSH tunnel

#Type in the password for sshuser

#The first time you connect to a new SSH host computer you must accept the SSH key that is presented. Type yes if prompted with a message similar to the text below.

The authenticity of host 'servername (10.04.00.02)' can't be established.
ECDSA key fingerprint is SHA256:(<a large string>).
Are you sure you want to continue connecting (yes/no)?

ssh tunnel login screen

#Leave this window open. Minimize if you need to but it needs to stay running for the tunnel traffic to use.

#This will end with a window that looks like it hangs after you login. It is not hung. That window is where the tunnel runs through. Do not close it. Minimize the window and go back to your script. Press Enter to continue…

SSH tunnel active after a successful login win10 server2019

#Go back to the PowerShell window and press Enter to launch mstsc.exe and make a Remote Desktop Connection using the new SSH tunnel.

(Read-Host 'Press Enter to continue...')|Out-Null

setup ssh tunnel rdp powershell win10 server2019

#Launch mstsc.exe with the new loopback IP and made up port number

#Use the & call operator to force PowerShell to treat the string as a command to be executed and run mstsc.exe which is the Windows command to launch the Remote Desktop Services client also know as Microsoft Terminal Services client (mstsc).

&mstsc /V:127.0.0.3:13389 /prompt

rdp ssh tunnel active win10 powershell


#I used code and knowledge from the page linked below to create this but the code I use is modified to combine techniques and concepts shown there when using PowerShell. 

#This site has information on using Putty and Linux to create SSH tunnel connections as well.

https://www.saotn.org/tunnel-rdp-through-ssh/

 

 

 

Setup a New Microsoft Windows Server 2019 Core Installation to Accept Incoming PowerShell Connections in a Workgroup

#Setup a New Microsoft Windows Server 2019 Core Installation to Accept Incoming PowerShell Remoting connections in a Workgroup


#You will not need to do this if you perform your PowerShell tasks directly from a domain connected computer.  You need this if you have virtual machines or headless devices… or just plain lazy. Also not everyone has a domain controller and sometimes even a Hyper-V host computer will remain in a workgroup since it might host the domain controller and it is off topic… I work in PowerShell ISE for the most part and connect to where ever I need to.


#This is the first steps after a fresh clean install of Microsoft Windows Server 2019 Core to allow PowerShell Remoting and WSMan.

Initial Screen Ctrl, Alt,_Del_Server 2019 Core

#Press Ctrl-Alt-Delete to begin configuring Microsoft Windows Server 2019 Core

Change password before signing in Server 2019 Core

#Press Enter to select OK to change password

Set local administrator password Server 2019 Core

#Set password for .\administrator

Your password has been changed Server 2019 Core

#This initial password is for the local administrator account .\administrator is also a way to access this account. It is not part of active directory and therefore doesn’t fall under the Active Directory password policy. Do not make it something easy to guess. The standard policy require 8 characters minimum with upper and lower case letters, numbers and symbols. I suggest you follow that as this password will be passed to your initial domain administrator account, where it will fail to work, so it is just best to avoid issues.

Microsoft Windows Server 2019 Core command prompt Server 2019 Core

#This is cmd.exe start screen for Microsoft Windows Server 2019 Core. Type sconfig to bring up the cheater menu.

Run Powershell Server 2019 Core

#Type powershell and press enter to start a PowerShell session directly in Microsoft Windows Server 2019 Core cmd.exe prompt.

Enable-PSRemoting -Force Server 2019 Core

#Type Enable-PSRemoting -Force to enable PowerShell Remoting. You can use -SkipNetworkProfileCheck to allow management requests on a network Microsoft Windows has categorized as Public such as Hotspots and new unrecognized networks.

Enable-PSRemoting -SkipNetworkProfileCheck -Force

Get-Item WSMan clients trustedhosts Server 2019 Core

#This will show you what computers you “trust” to connect remotely via PowerShell Remote, no remote hosts are allowed by default.

Get-Item WSMan:\localhost\Client\TrustedHosts

Set-Item -Value IP addresses and computer names verify Server 2019 Core

#This creates a list of computers you “trust” so that you wish to make outgoing PowerShell Remote connections. It doesn’t need a value if you don’t plan to connect to other computers from this new server and/or just use a management PC. 

#This is not a list of computers that are allowed to use Enter-PSSession to connect to the new server and most likely you need to run this command on a Windows 10 management PC instead. You would include either the IP address of the new server, the computer name of the new server or ‘*’ if you want to be able to connect to anywhere.

Get-Item WSMan:\localhost\Client\TrustedHosts|Set-Item -Value '10.4.0.2,BEAKER'

#The code below will add entries to the TrustedHosts rather than overwrite them:

# Retrieve the current TrustedHosts value
$currentTrustedHosts = (Get-Item WSMan:\localhost\Client\TrustedHosts).Value

# Define the new entries you want to add
$newEntries = "KERMIT,10.10.10.20"

# Check if currentTrustedHosts is empty and append new entries
if ([string]::IsNullOrEmpty($currentTrustedHosts)) {
$updatedTrustedHosts = $newEntries
} else {
$updatedTrustedHosts = "$currentTrustedHosts,$newEntries"
}

# Set the updated TrustedHosts value
Set-Item WSMan:\localhost\Client\TrustedHosts -Value $updatedTrustedHosts

You can now connect via Eter-PSSession Server 2019 Core

#You can use either the server IP address or computer name if you need to perform this step.  I choose to use both so I avoid any issues when connecting. You need to type y and press Enter to confirm.  A value of ‘*’ allows the server to connect to any remote host.

#Now you can use Enter-PSSession to connect to your Microsoft Windows Sever 2019 Core install to configure it using PowerShell or RSAT tools.


#At this point you probably do not have Active Directory installed so you would use the command below to connect to the server. I use PowerShell ISE to open my list of common commands and just run them remotely from my desktop computer. After the -Cn is whatever IP address or computer name you added to WSMan:\localhost\Client\TrustedHosts

Enter-PSSession -Cn 10.4.0.2 -Credential administrator

#If you are running Microsoft Windows 2019 Core on Hyper-V then you can connect the way shown above from anywhere. You could connect the way below, from the Hyper-V host, if that isn’t also a core installation.  Be aware that connecting -VMName Vs. -ComputerName can cause some commands to behave differently or not at all.

Enter-PSSession -VMName Server2019 -Credential administrator

 

Installing and configuring PowerShell 7.2.1 on 64-bit Server 2019 and Windows 10

#Installing and configuring PowerShell 7.2.1 on 64-bit Server 2019 and Windows 10

#The installation commands shown here are for the latest stable release of PowerShell 7

#To be honest I don’t recommend upgrading if you plan to keep using all your existing scripts and commands without issue.  That most likely will not happen. PowerShell 7 doesn’t work well with Microsoft 365 and Microsoft Azure.  The login command fails, for example.  There might be a work around using the Microsoft Graph API but I haven’t managed to get that working.  The differences between PowerShell 5 and PowerShell 7 are discussed here.

 #I need to use the older Microsoft only releases of PowerShell for most of what I do.  PowerShell 7 does work on many non-Windows platforms but do not expect to use PowerShell 7 to manage your hard drives in Linux.  PowerShell 5.x and PowerShell 6.x only work on Microsoft Windows-based computers.

#It should also be mentioned that PowerShell 5 and PowerShell 7 run along side each other and is determined by which shell you choose to work in.  Another problem is that PowerShell ISE is not designed to work with PowerShell 7 and not included.


From Microsoft: 

#Is PowerShell ISE going away?

 
The PowerShell ISE is no longer in active feature development. As a shipping component of Windows, it continues to be officially supported for security and high-priority servicing fixes. … Users looking for replacement for the ISE should use Visual Studio Code with the PowerShell Extension.
 

 

PowerShell 7.2.1 can be downloaded for 64-bit Windows-based operating systems from the link below: 

https://github.com/PowerShell/PowerShell/releases/download/v7.2.1/PowerShell-7.2.1-win-x64.msi

Get more information about the latest version of Microsoft PowerShell 7.2 LTS from the link below:

https://docs.microsoft.com/en-us/powershell/scripting/install/installing-powershell-on-windows?view=powershell-7.2


#Open firewall to allow PowerShell access to and from other computers on your network:

Set-NetConnectionProfile -NetworkCategory Private
Enable-PSRemoting

 

Install AD-Domain-Services And Configure A New Domain On Windows Server 2016

#Install AD-Domain-Services And Configure A New Domain On Windows Server 2016

#This is to install and configure a new Active Directory domain called domain.win10server2016.lan with a short name of domain. You will be disconnected from Microsoft PowerShell at the end of the procedure if you are connected via WinRM or PowerShell Direct. You’ll need to restart the server and login with domain\username credentials when you reconnect. 

#Just the code:

Get-WindowsFeature -Name AD-Domain-Services|Install-WindowsFeature -Verbose|fl
Import-Module ADDSDeployment -PassThru|fl
Install-ADDSForest -DomainName domain.win10server2016.lan -DomainNetbiosName DOMAIN -DomainMode 7 -ForestMode 7 -InstallDNS -Verbose|fl

#The Longer Story…

#This is just to install a single domain on Windows Server 2016 using PowerShell commands.

#Install AD-Domain-Services feature in Windows Server 2016 using PowerShell Direct

Get-WindowsFeature -Name AD-Domain-Services|Install-WindowsFeature -Verbose|fl

#Import the ADDSDeployment module that contains Install-ADDSForest

Import-Module -Name ADDSDeployment -PassThru|fl

#Create domain and forest

#-DomainMode 7 and -ForestMode 7 are for Server 2016 domain and forest mode. These settings should be modified if compatibility for previous Active Directory domain and forest mode support is needed. I do not see these settings on the Microsoft help page for Install-ADDSDeployment but if you use the GUI wizard method then Server 2016 mode is the default used there and this will be added when they update the Install-ADDSDeployment TechNet page past Server 2012 R2.

#The -DomainNetbiosName is different from a Netbios Computer Name and is what is used when logging in so domain\administrator is as valid as logging into domain.win10server2016.lan\administrator.

Install-ADDSForest -DomainName domain.win10server2016.lan -DomainNetbiosName DOMAIN -DomainMode 7 -ForestMode 7 -InstallDNS -Verbose -NoRebootOnCompletion|fl

 

#Full Output of Install-ADDSForest:

The target server will be configured as a domain controller. The server needs to be restarted manually when this
operation is complete.
Do you want to continue with this operation?
[Y] Yes  [A] Yes to All  [N] No  [L] No to All  [S] Suspend  [?] Help (default is "Y"): y
VERBOSE: Active Directory Domain Services Setup
VERBOSE: Validating environment and parameters...
WARNING: Windows Server 2016 domain controllers have a default for the security setting named "Allow cryptography
algorithms compatible with Windows NT 4.0" that prevents weaker cryptography algorithms when establishing security
channel sessions.

For more information about this setting, see Knowledge Base article 942564
(http://go.microsoft.com/fwlink/?LinkId=104751).

WARNING: A delegation for this DNS server cannot be created because the authoritative parent zone cannot be found or it
 does not run Windows DNS server. If you are integrating with an existing DNS infrastructure, you should manually
create a delegation to this DNS server in the parent zone to ensure reliable name resolution from outside the domain
"domain.win10server2016.lan". Otherwise, no action is required.

VERBOSE: ----------------------------------------
VERBOSE: The following actions will be performed:
VERBOSE: Configure this server as the first Active Directory domain controller in a new forest.

The new domain name is "domain.win10server2016.lan". This is also the name of the new forest.

The NetBIOS name of the domain is "DOMAIN".

Forest Functional Level: Windows Server 2016

Domain Functional Level: Windows Server 2016

Site: Default-First-Site-Name

Additional Options:
  Read-only domain controller: "No"
  Global catalog: Yes
  DNS Server: Yes

Create DNS Delegation: No

Database folder: C:\Windows\NTDS
Log file folder: C:\Windows\NTDS
SYSVOL folder: C:\Windows\SYSVOL

The DNS Server service will be installed on this computer.
The DNS Server service will be configured on this computer.
This computer will be configured to use this DNS server as its preferred DNS server.

The password of the new domain Administrator will be the same as the password of the local Administrator of this
computer.
VERBOSE: ----------------------------------------
VERBOSE: Active Directory Domain Services Setup
VERBOSE: Validating environment and parameters...
WARNING: Windows Server 2016 domain controllers have a default for the security setting named "Allow cryptography
algorithms compatible with Windows NT 4.0" that prevents weaker cryptography algorithms when establishing security channel sessions.

For more information about this setting, see Knowledge Base article 942564
(http://go.microsoft.com/fwlink/?LinkId=104751).

WARNING: A delegation for this DNS server cannot be created because the authoritative parent zone cannot be found or it
 does not run Windows DNS server. If you are integrating with an existing DNS infrastructure, you should manually
create a delegation to this DNS server in the parent zone to ensure reliable name resolution from outside the domain
"domain.win10server2016.lan". Otherwise, no action is required.

VERBOSE: ----------------------------------------
VERBOSE: The following actions will be performed:
VERBOSE: Configure this server as the first Active Directory domain controller in a new forest.

The new domain name is "domain.win10server2016.lan". This is also the name of the new forest.

The NetBIOS name of the domain is "DOMAIN".

Forest Functional Level: Windows Server 2016

Domain Functional Level: Windows Server 2016

Site: Default-First-Site-Name

Additional Options:
  Read-only domain controller: "No"
  Global catalog: Yes
  DNS Server: Yes

Create DNS Delegation: No

Database folder: C:\Windows\NTDS
Log file folder: C:\Windows\NTDS
SYSVOL folder: C:\Windows\SYSVOL

The DNS Server service will be installed on this computer.
The DNS Server service will be configured on this computer.
This computer will be configured to use this DNS server as its preferred DNS server.

The password of the new domain Administrator will be the same as the password of the local Administrator of this
computer.
VERBOSE: ----------------------------------------
VERBOSE: Press CTRL-C to: Cancel
VERBOSE: Active Directory Domain Services is now installed on this computer for the domain
"domain.win10server2016.lan".

This Active Directory domain controller is assigned to the site "Default-First-Site-Name". You can manage sites with
the Active Directory Sites and Services administrative tool.


Message        : You must restart this computer to complete the operation.

Context        : DCPromo.General.4
RebootRequired : True
Status         : Success

#Restart the server.

Restart-Computer

#Reconnect to PowerShell Direct using the DOMAIN\administrator account after reboot from Install-ADDSForest is complete.

Enter-PSSession -VMName Server2016 -Credential domain\administrator

Manage Active Directory Users And Computers Using Windows 10 Creators Edition In PowerShell Direct Without CredSSP Or “Second-Hop” Issues

#Manage Active Directory Users And Computers Using Windows 10 Creators Edition Using PowerShell Direct Without CredSSP Or “Second-Hop” Issues

#If you connect to a virtual machine using PowerShell Remote then you need to enable CredSSP to avoid Second-Hop or “Multi-Hop” Issues when managing Active Directory objects. CredSSP is always needed when connecting to a physical machine since PowerShell Direct only works when connecting to a virtual machine directly from the host computer.

#PowerShell Direct doesn’t have the “Second-Hop” issue when managing Windows Server 2016 from a Windows 10 Creators Edition virtual machine running Hyper-V. I have enabled the Hyper-V role on Windows 10 Professional and my physical machine is not joined to a domain. The Windows 10 virtual machine will need to be joined to the Active  Directory domain you intend to manage without making further “workgroup” related configuration changes.

Enter-PSSession -VMName Win10 -Credential DOMAIN\administrator #Connect to a Windows 10 Creators Edition virtual machine using PowerShell Direct
New-ADOrganizationalUnit -Server KERMIT -Name Test -Description 'Administrator Rights' -DisplayName Test -PassThru -Verbose #Create a new OU called Test
Get-ADOrganizationalUnit -Server KERMIT -Identity 'OU=Test,DC=domain,DC=muppetlabs,DC=com'|Set-ADOrganizationalUnit –ProtectedFromAccidentalDeletion $false #Unprotect OU=Test for intentional deletion
Get-ADOrganizationalUnit -Server KERMIT -Identity 'OU=Test,DC=domain,DC=muppetlabs,DC=com'|Remove-ADOrganizationalUnit -Verbose #Delete OU=Test

#The Longer Story…

#Create a new Organizational Unit in PowerShell Remote using just the computer name

#Without CredSSP enabled this command fails in PowerShell Remote

Enter-PSSession -ComputerName KERMIT -Credential DOMAIN\administrator #Connect to a Windows 10 Creators Edition virtual machine using PowerShell Remote
New-ADOrganizationalUnit -Server KERMIT -Name Test -Description 'Administrator Rights' -DisplayName Test -PassThru -Verbose #Create a new OU called Test

#Create a new Organizational Unit in PowerShell Direct using just the computer name

#Just using OU=Test as an example to show how this command doesn’t fail in PowerShell Direct like it did in the previous example.

Enter-PSSession -VMName Win10 -Credential DOMAIN\administrator #Connect to a Windows 10 Creators Edition virtual machine using PowerShell Direct
New-ADOrganizationalUnit -Server KERMIT -Name Test -Description 'Administrator Rights' -DisplayName Test -PassThru -Verbose #Create a new OU called Test

#Set â€“ProtectedFromAccidentalDeletion to $false on OU=Test so it can be deleted

#This needs to be done to allow the OU to be deleted.

Get-ADOrganizationalUnit -Server KERMIT -Identity 'OU=Test,DC=domain,DC=muppetlabs,DC=com'|Set-ADOrganizationalUnit –ProtectedFromAccidentalDeletion $false #Unprotect OU=Test for intentional deletion

#Delete OU=Test from -Server KERMIT.

#KERMIT is the NetBIOS computer name of my domain controller and not the domain NetBIOS name. They are different things.

Get-ADOrganizationalUnit -Server KERMIT -Identity 'OU=Test,DC=domain,DC=muppetlabs,DC=com'|Remove-ADOrganizationalUnit -Verbose #Delete OU=Test

 

Join Windows 10 Professional To An Active Directory Domain Using PowerShell Direct

#Join Windows 10 Professional To An Active Directory Domain Using PowerShell Direct

#These are the commands to rename a Windows 10 client computer to GONZO and add that computer to a domain called domain.win10server2016.lan .

Rename-Computer -NewName GONZO -Verbose -PassThru #Rename computer before joining domain. Requires restart
Restart-Computer
Add-Computer -DomainName domain.win10server2016.lan -Credential domain\administrator -Passthru -Verbose #Join Active Directory Domain and add to Computer container. Requires restart
Restart-Computer

#The Longer Story…

#Your computer may not need to be renamed so skip that if needed. Also the Add-Computer command sends your newly added computers to the Computers container by default unless you specify an -OUPath when running Add-Computer.

#Rename computer before joining your domain if your computer name doesn’t comply with server standards. Restart required.

Rename-Computer -NewName GONZO -Verbose -PassThru #Rename computer before joining domain. Requires restart
Restart-Computer

 

#Join a domain called domain.muppetlabs.com. Restart required.

#You need to change the -DomainName from domain.win10server2016.lan to what you call your domain. Use -Restart at the end of the Add-Computer command to automatically restart.

Add-Computer -DomainName domain.win10server2016.lan -Credential domain\administrator -Passthru -Verbose #Join Active Directory Domain and add to Computer container. Requires restart
Restart-Computer

 


#A Bit More

#Specify a preconfigured Organizational Unit path when joining domain

#My domain is simple and this is not needed for me at this time. I don’t have multiple Organizational Units yet and I don’t need any Group Policies affecting this PC since I’m working with my Windows 10 Creators Edition management PC. I’m able to specify the -OUPath shown below, once I complete the step below to create an OU called ServerAdmins. This command adds the computer to OU=ServerAdmins.

#You are not able to specify another container besides the default Computers container, but there is a way to change the default container if you don’t specify an OU. I definitely don’t want my computers added to the default OU which is OU=Domain Controllers, so I don’t use this command switch unless I have created a new OU first. It has been suggested to create the OU and computer object prior to joining the domain, but I don’t need to do that at this point.

#The command below is used to specify an Organizational Unit when joining a domain, if needed.

Add-Computer -DomainName 'domain.win10server2016.lan' -OUPath 'OU=Producers,DC=domain,DC=win10server2016,DC=lan' -Credential 'DOMAIN\administrator' -Passthru -Verbose
Restart-Computer

#Create a new Organizational Unit on the server (Needs to be run on Windows Server 2016 with the Active Directory role installed and configured)

#If you preconfigure an alternative Organizational Unit on Windows Server 2016 then you can add your computers directly to that OU by specifying a -OUPath when running Add-Computer.

New-ADOrganizationalUnit -Name ServerAdmins -Description 'Administrator Rights' -DisplayName Producers -PassThru -Verbose

Using Set-Alias In PowerShell To Create Shortcuts To Functions In Windows 10

#Using Set-Alias In PowerShell To Create Shortcuts To Functions In Windows 10 Edition

#These commands also work in both PowerShell and PowerShell Direct. You can also do this in Microsoft Windows Server 2016.

#Just the code:

Function funk_cnkermit {Enter-PSSession -ComputerName KERMIT -Credential DOMAIN\administrator} #Set fucntion to enter a PowerShell Remote session
Set-Alias kermit funk_cnkermit #Create Alias using computer name
Function funk_vmserver2016 {Enter-PSSession -VMName Server2016 -Credential DOMAIN\administrator} #Set function to enter a PowerShell Direct session
Set-Alias server2016 funk_vmserver #Create Alias using virtual machine name

#The Longer Story…

#These are two basic functions, but the functions you control with Set-Alias can be much more complicated.  An Alias is just a shortcut to a command with a long name, but without any parameters. Parameters still need to be added to most commands when running an Alias. A function can contain commonly used parameters or even more complex command structures. You will also need to add permanent functions to your $Profile for PowerShell and PowerShell ISE separately since they are controlled by two different startup files.

#Using Set-Alias In PowerShell To Create Shortcuts To Functions

#As an example, I am going to create a function to run Enter-PSSession to connect using PowerShell Remote. I also create a similar function to connect using PowerShell Direct so I just type the value of either the -VMName or the -ComputerName to enter my password and connect.

#KERMIT is the computer name of my server. The name of the virtual machine is Server2016. These commands would need to be modified to fit your environment.

#List available Functions using Out-GridView in PowerShell ISE or not

#Note: Out-GridView does not work in a remote session or in PowerShell command prompt.

Get-ChildItem Function: #Take a look a the functions currently defined
Get-ChildItem Function:|Out-GridView #Use PowerShell ISE to provide a grid view of the output

#Check the pre-defined list of aliases using Out-GridView in PowerShell ISE or not

#See pre-defined Alias list

Get-ChildItem Alias: #Take a look at the currently defined alias list
Get-ChildItem Alias:|Out-GridView #Use PowerShell ISE to provide a grid view of the output

#Create Two New Functions To Connect To Server Using PowerShell Remote and PowerShell Direct

#One function called funk_cnkermit initiates a connection to the computer name (-ComputerName) of the server and the other, funk_vmserver2016, connects to a virtual machine name (-VMName). The function name can be anything that is guaranteed to stay unique. The command inside the {} could be any commands that you find useful and use frequently. Multiple lines of code are also supported.

Function funk_cnkermit {Enter-PSSession -ComputerName KERMIT -Credential DOMAIN\administrator} #Set fucntion to enter a PowerShell Remote session
Function funk_vmserver2016 {Enter-PSSession -VMName Server2016 -Credential DOMAIN\administrator} #Set function to enter a PowerShell Direct session

#Use The Set-Alias PowerShell Command To Create Shorter Commands And To Trigger Custom Functions Into Action Without Repetitive Keystrokes

#Set an alias to each new function using the computer name kermit and the virtual machine name server2016 using the commands below:

Set-Alias kermit funk_cnkermit #Create Alias using computer name
Set-Alias server2016 funk_vmserver2016 #Create Alias using virtual machine name

 #Here Is A Useful Docker Function I Created

Function funk_DockerCleanExitedContainers {docker.exe rm $(docker ps -q -f status=exited)} #Function to automatically clean exited containers in Docker
Set-Alias Docker-CleanExitedContainers funk_DockerCleanExitedContainers #Set Alias name

#I’m sure there are much more complicated functions that I’ll add along the way, but just having an alias to Enter-PSSession is such a time saver. Don’t forget to use AutoComplete or Tab to save time when typing all of Docker-CleanExitedContainers. Once the Alias is set, it will be as if it was a command in the environment path.

 

Download And Install Remote Server Administration Tools for Windows 10 On Windows 10 Creators Edition Using PowerShell

#Download And Install Remote Server Administration Tools for Windows 10 On Windows 10 Creators Edition Using PowerShell

#Just the code to install Remote Server Administration Tools x64

$MSUPath = 'c:\RSAT' #Set temp path
New-Item -ItemType Directory -Path $MSUPath -Verbose #Create temp folder
Start-BitsTransfer -Source 'https://download.microsoft.com/download/1/D/8/1D8B5022-5477-4B9A-8104-6A71FF9D98AB/WindowsTH-RSAT_WS2016-x64.msu' -Destination $MSUPath\WindowsTH-RSAT_WS2016-x64.msu -Verbose #Download 64-bit RSAT tools
$ExpandOpt='-f:* "'+$MSUPath+'\WindowsTH-RSAT_WS2016-x64.msu" '+$MSUPath #Create argument list for expand.exe
$DismOpt="/Online /Add-Package /PackagePath:$MSUPath\WindowsTH-KB2693643-x64.cab" #Set dism.exe argument options
Start-Process -FilePath expand.exe -ArgumentList $ExpandOpt -PassThru -Wait #Expand RSAT installation files
Start-Process -FilePath dism.exe -ArgumentList $DismOpt -PassThru -Wait #Run dism with argument options. Takes a few minutes to install.

#Use the next command with care if you changed the temporary folder from c:\RSAT to something else

Remove-Item -Path $MSUPath -Recurse -Verbose

#The Longer Story…

#This was a real pain in the ass. .MSU files are not ideal to deal with in PowerShell and far different from .MSI installs. It is possible that Remote Server Administration Tools for Windows 10 can’t be installed remotely using wusa.exe. There are security issues with wusa.exe and Windows 10 for sure. The wusa.exe /extract option doesn’t work in Windows 10 either, due to the same security concerns.

#Set temporary path for installation

#Set this to whatever path you want. I prefer to use a empty new folder but any temporary folder will do. Watch out for the Remove-Item command later on though if you use an existing folder for your download location.

$MSUPath = 'c:\RSAT' #Set temp path
$MSUPath = 'c:\RSAT'
$MSUPath = ‘c:\RSAT’

#Create temporary folder

#Create the folder c:\RSAT or as set in the previous command. Skip this step if you plan to use an existing folder.

New-Item -ItemType Directory -Path $MSUPath -Verbose #Create temp folder
New-Item -ItemType Directory -Path $MSUPath -Verbose
New-Item -ItemType Directory -Path $MSUPath -Verbose

#Download 64-bit version of Remote Server Administration Tools for Windows 10

#I am dealing with the 64-bit version only. I don’t know why you would even have a 32-bit version of Windows 10 Creators Edition but I’m guessing there are people doing it. You need to figure out the link yourself or download the RSAT package some other way. This command only works in PowerShell and PowerShell Remote but not in PowerShell Direct since it uses BITS.

#Download Page: https://www.microsoft.com/en-us/download/details.aspx?id=45520

Start-BitsTransfer -Source 'https://download.microsoft.com/download/1/D/8/1D8B5022-5477-4B9A-8104-6A71FF9D98AB/WindowsTH-RSAT_WS2016-x64.msu' -Destination $MSUPath\WindowsTH-RSAT_WS2016-x64.msu -Verbose #Download 64-bit RSAT tools for Win10
Start-BitsTransfer -Source 'https://download.microsoft.com/download/1/D/8/1D8B5022-5477-4B9A-8104-6A71FF9D98AB/WindowsTH-RSAT_WS2016-x64.msu' -Destination $MSUPath\WindowsTH-RSAT_WS2016-x64.msu -Verbose
Start-BitsTransfer -Source ‘https://download.microsoft.com/download/1/D/8/1D8B5022-5477-4B9A-8104-6A71FF9D98AB/WindowsTH-RSAT_WS2016-x64.msu’ -Destination $MSUPath\WindowsTH-RSAT_WS2016-x64.msu -Verbose

#Set expand.exe options

#wusa.exe /extract does not work in Windows 10 so expand.exe must be used. These are the -ArgumentList options I had to set using a variable due to the really appalling quote and double quote bullshit that needs to happen to get some of these commands to work. I do not recommend trying to use the wusa.exe method of installing Remote Server Administration Tools for Windows 10 if even just to be stubborn as wusa.exe is just not designed to work properly when installing .MSU files via PowerShell in Windows 10.

$ExpandOpt='-f:* "'+$MSUPath+'\WindowsTH-RSAT_WS2016-x64.msu" '+$MSUPath #Create argument list for expand.exe
$ExpandOpt='-f:* "'+$MSUPath+'\WindowsTH-RSAT_WS2016-x64.msu" '+$MSUPath
$ExpandOpt=’-f:* “‘+$MSUPath+’\WindowsTH-RSAT_WS2016-x64.msu” ‘+$MSUPath

#Set options for Dism.exe

#Set -ArgumentList for Start-Process to launch the dism.exe command. Using dism.exe is just another crutch to get Remote Server Administration Tools for Windows 10 installed remotely using PowerShell Remote. There is not an equivalent native PowerShell command to replace dism.exe yet.

$DismOpt="/Online /Add-Package /PackagePath:$MSUPath\WindowsTH-KB2693643-x64.cab" #Set dism.exe argument options
$DismOpt="/Online /Add-Package /PackagePath:$MSUPath\WindowsTH-KB2693643-x64.cab"
$DismOpt=”/Online /Add-Package /PackagePath:$MSUPath\WindowsTH-KB2693643-x64.cab”

#Expand the .MSU file using expand.exe

#As I already mentioned… WUSA.exe – Extract option is gone in Windows 10

Start-Process -FilePath expand.exe -ArgumentList $ExpandOpt -PassThru -Wait #Expand RSAT installation files
Start-Process -FilePath expand.exe -ArgumentList $ExpandOpt -PassThru -Wait
Start-Process -FilePath expand.exe -ArgumentList $ExpandOpt -PassThru -Wait

#Install RSAT .CAB file using dism.exe

#Dism.exe is what actually works and is the method I recommend but it is slow. Takes about 5 minutes to install with my setup. You will have to wait. I have had varying degrees of success using pkgmgr.exe to install also but also I get a message in certain instances that pkgmgr.exe is depreciated so I have stayed away from using that method to install RSAT.

Start-Process -FilePath dism.exe -ArgumentList $DismOpt -PassThru -Wait #Run dism with argument options. Takes a few minutes to install.
Start-Process -FilePath dism.exe -ArgumentList $DismOpt -PassThru -Wait
Start-Process -FilePath dism.exe -ArgumentList $DismOpt -PassThru -Wait

#Remove c:\RSAT once install of WindowsTH-RSAT_WS2016-x64.msu has completed

#If you changed $MSUPath then pay attention here. You don’t want to delete a folder with other data in it. The RSAT install files are no longer needed though and can be safely deleted.

Remove-Item -Path $MSUPath -Recurse -Verbose
Remove-Item -Path $MSUPath -Recurse -Verbose
Remove-Item -Path $MSUPath -Recurse -Verbose

#You do not have to do anything else but here is the command to verify what features are currently installed.

#All Remote Server Administration Tool features are installed and enabled by default. Also you no longer need dism.exe to manage the RSAT package features. Instead Enable-WindowsOptionalFeature and Disable-WindowsOptionalFeature should be used at this point. The command below should get you started if you need to tweak available installed features. The list is too long to screen shot all at once so a snip is not included.

Get-WindowsOptionalFeature -Online -FeatureName *RSAT*|ft -a

#The Remote Server Administration Tools icons are there under Control Panel and then Administrative Tools.

#The image below shows what the default installation should look like in Windows 10.

Enabling Remote Desktop Via PowerShell Direct From A Windows 10 Hyper-V Host Machine

#Enabling Remote Desktop Via PowerShell Direct From A Windows 10 Hyper-V Host Machine

#Note: This does not work on Windows 10 Home Edition.

#Just the code:

If (Test-Path 'HKLM:\SYSTEM\CurrentControlSet\Control\Terminal Server') {Get-Item 'HKLM:\SYSTEM\CurrentControlSet\Control\Terminal Server'|Set-ItemProperty -Name fDenyTSConnections -Value 0 -PassThru|fl}
Get-NetFirewallRule -DisplayGroup "Remote Desktop"|Set-NetFirewallRule -enabled true -PassThru|select Name,DisplayName,Enabled,Profile|ft -a

#The Long Story…

#Yeah so PowerShell Direct doesn’t do everything and neither does PowerShell Remote.  Simply put, PowerShell Direct is a connection to a remote computer initiated with Enter-PSSession -VMName. PowerShell Remote uses WinRM to communicate and is initiated using Enter-PSSession -ComputerName. It is important to know the difference because each way of connecting doesn’t function exactly the same way. You will get errors in PowerShell Direct using commands that require the Background Intelligent Transfer Serviceor BITS, for one. BITS only works in PowerShell Remote.

#Sometimes using Remote Desktop isn’t even enough to do everything but you can do so much more running commands directly. Simple things like using Out-GridView for formatting complex command output needs to be run directly from the machine you are running PowerShell ISE on via a Remote Desktop session and PowerShell ISE. PowerShell Direct and PowerShell Remote sessions are not allowed to call on Out-Gridview at all.

#Note: These commands work in Windows 10 and in PowerShell Remote and PowerShell Direct.

These are the default Remote Desktop settings (Disabled)

#Enable the Remote Desktop Services (also known as RDP and Terminal Services)

#For maximum security only run this and the firewall command like I have shown above under #Just the code:.

If (Test-Path 'HKLM:\SYSTEM\CurrentControlSet\Control\Terminal Server') {Get-Item 'HKLM:\SYSTEM\CurrentControlSet\Control\Terminal Server'|Set-ItemProperty -Name fDenyTSConnections -Value 0 -PassThru|fl}

#Check configured port number for Remote Desktop Services (RDS). The default incoming port is 3389 unless you change it.

Get-ItemProperty 'HKLM:\SYSTEM\CurrentControlSet\Control\Terminal Server\WinStations\RDP-TCP\' -Name PortNumber -Verbose|ft -w #Check default Remote Desktop incoming port

#Open Firewall for Remote Desktop Services (RDS)

#Open the Windows Firewall for Remote Desktop Services.

Get-NetFirewallRule -DisplayGroup "Remote Desktop"|Set-NetFirewallRule -enabled true -PassThru|select Name,DisplayName,Enabled,Profile|ft -a

#Add users to the Remote Desktop Users group

#The default administrator account is automatically added so this is only needed if you have additional accounts to add. You can also add Active Directory domain user accounts and groups using domain\remoteuser credentials after the –Member switch.

Add-LocalGroupMember -Group 'Remote Desktop Users' -Member remoteuser -Verbose #username or domain\username will work

#Disable NLM authentication

#Allow older versions of Windows to connect with weaker authentication by issuing the following command. I would not disable NLM authentication unless you absolutely need to.

If (Get-ItemProperty 'HKLM:\SYSTEM\CurrentControlSet\Control\Terminal Server\WinStations\RDP-Tcp') {Get-ItemProperty 'HKLM:\SYSTEM\CurrentControlSet\Control\Terminal Server\WinStations\RDP-Tcp'|Set-ItemProperty -Name UserAuthentication -Value 0 -PassThru|fl} #disable NLM authentication

#I’ve already disabled Remote Assistance so the settings look like the screenshot below for me once NLM authentication is disabled: