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.

 

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:

 

Enable or Disable Game Mode In Windows 10 Creators Edition Using PowerShell Commands

#Enable Game Mode In Windows 10 Creators Edition Using PowerShell Commands

#Enable Game Mode in Windows 10 Creators Edition only. This does not work in previous or the latest version of Windows 10.  Windows Key + G will toggle Game Mode once the changes have been made. This command appears to have no effect in 1909.

#Just the command

If (Test-Path HKCU:\Software\Microsoft\GameBar) {Get-Item HKCU:\Software\Microsoft\GameBar|Set-ItemProperty -Name AllowAutoGameMode -Value 1 -Verbose -Force}

#The Longer Story…

#The above command enables Game Mode. The command below disables Game Mode. Again this feature is only available in Windows 10 Creators Edition. These commands work in both PowerShell and PowerShell Direct.

If (Test-Path HKCU:\Software\Microsoft\GameBar) {Get-Item HKCU:\Software\Microsoft\GameBar|Set-ItemProperty -Name AllowAutoGameMode -Value 0 -Verbose -Force}

#Check Game Bar Registry Key And Existing Configuration (1=Enabled, 0=Disabled)

#If the GameBar registry key has no properties then Game Mode is disabled.  If allow AllowAutoGameMode is set to 1 then Game Mode is enabled. If it is set to 0 then AllowAutoGameMode is disabled.

Get-Item -Path HKCU:\Software\Microsoft\GameBar -Verbose|ft -a

#▲Game Mode Disabled (Installation Default)

#▲Game Mode Enabled

#Enable Game Mode In Windows 10 For The First Time

#The -Force switch is used to a skip using New-Item or New-ItemProperty commands but specifying -Force will delete the key and recreate the key and you will lose all sub-keys.

If (Test-Path HKCU:\Software\Microsoft\GameBar) {Get-Item HKCU:\Software\Microsoft\GameBar|Set-ItemProperty -Name AllowAutoGameMode -Value 1 -Verbose -Force} #Enable Game Mode

#Disable Game Mode In Windows 10 Once Enabled Or To Manually Set Game Mode To Disabled

#If you just remove the registry key then Game Mode will stay enabled. Changing AllowAutoGameMode to 0 will disable Game Mode once it has been enabled.

If (Test-Path HKCU:\Software\Microsoft\GameBar) {Get-Item -Path HKCU:\Software\Microsoft\GameBar|Set-ItemProperty -Name AllowAutoGameMode -Value 0 -Verbose -Force}

#Check If AllowAutoGameMode Registry Property Is Enabled (1=Enabled, 0=Disabled)

#Is similar to the other command to check Game Mode status with more information about the registry key. This command will error if AllowAutoGameMode is not there but just means that Game Mode is disabled by default.

Get-ItemProperty -Path HKCU:\Software\Microsoft\GameBar\ -Name AllowAutoGameMode -Verbose|fl


#Keyboard Shortcuts for Game Barhttps://support.microsoft.com/en-us/instantanswers/a4cced71-b833-4e48-8523-8be8b7d29448/keyboard-shortcuts-for-game-bar

#Additional Microsoft Game Infohttps://www.microsoft.com/en-us/windows/windows-10-games

Automatically Determine Unallocated Space And Expand Drive C In PowerShell After Expanding Virtual Hard Drive In Hyper-V

#Automatically Determine Unallocated Space And Expand Drive C In PowerShell After Expanding Drive In Hyper-V

#Code to automatically determine unallocated space and expand boot drive C.

#NOTE: I am not responsible if you muck everything up. I am working in a lab under optimal conditions. Always backup your critical data before messing with your hard drives and virtual machines. BACKUP BACKUP BACKUP!!! if you are doing this in a production environment. At least create a checkpoint in Hyper-V so you can go back if needed. I am not responsible for random code snippets I wrote or posted here. You choose what to run on your computers and I am not part of that decision or any undesired consequences. Ok then, moving on…

#Change $Drive2Expand = 'C' to whatever other drive you wish to expand but be aware that I am running Get-Disk with the IsBoot parameter equal to Yes. If you change $Drive2Expand to a non-boot drive these commands with fail.

#Just the code:

$Drive2Expand='C' #Change to the NTFS drive letter you want to expand
$VirtDiskNum=(Get-Disk -FriendlyName 'Msft Virtual Disk'|? IsBoot -eq Yes) #Get disk number of default hyper-v boot drive but change if expanding a secondary or non-boot drive
$PartitionNum=(Get-Partition -DriveLetter $Drive2Expand) #Get the partition number for drive c 
$PartSize=(Get-PartitionSupportedSize -DiskNumber $VirtDiskNum.number -PartitionNumber $PartitionNum.PartitionNumber) #Get partition info for drive c 
Resize-Partition -PartitionNumber $PartitionNum.PartitionNumber -Size $PartSize.SizeMax -DiskNumber $VirtDiskNum.number #Expand drive C using all unallocated space available

#The longer story…

#This used to be done with diskpart but PowerShell can get the job done without launching an application and is much more easily scripted.

#Run Get-Disk to get the disk number

#? is an alias to the where command. You can change IsBoot to any parameter or value listed with the Format-List command or fl in the code I type. I am basing this on working with virtual hard drives in Hyper-V but these command can be modified to address the same issues with physical drives.

Get-Disk|ft -a #If you have only one virtual disk installed then this command is fine.
Get-Disk -FriendlyName 'Msft Virtual Disk'|? IsBoot -eq Yes|fl #Get a list of the available parameters on an automatically created default boot drive

#Run Get-Partition on -DriveLetter C to get drive C configuration information

#Note the PartitionNumber in the command output as that will be needed for the rest of the commands. Change -DriveLetter to whatever drive you wish to expand.

Get-Partition -DriveLetter C

#Another option is to get only the PartitionNumber value instead of the standard output.

Get-PartitionSupportedSize -DiskNumber 0 -PartitionNumber $PartitionNum.PartitionNumber

#Check minimum and maximum supported sizes for the partition

Get-PartitionSupportedSize -DiskNumber 0 -PartitionNumber 4

#Use Resize-Partition to use the maximum size available to expand –PartitionNumber 4.

#I just copied and pasted the SizeMax number from above to the command below. I can’t screenshot this command at the moment since my drive is fully expanded but I update with screenshot soon.

Resize-Partition -PartitionNumber 4 -Size 2209358000 -DiskNumber 0 #Expand drive C using all unallocated space available

#SCREENSHOT PLACEHOLDER#

 

 

#Get free space on drive C

#The following commands are  to get the free space on drive C and display it in a friendly manor. This code is just for fun.  It is not really needed. Is just to show how to manipulate number results in PowerShell by converting the free space on drive C to a easily readable format. Many of the principles below can be applied to the results of the above commands.

$Free = (Get-PSDrive C) #Set drive information to variable
$Free = ($Free.free/1GB) #Get free space and divide by 1 gigabyte
$Free = ([math]::Round($Free,2)) #Round free space to two decimal places
Write-Host $Free'/GB Free on Drive C:\' #Display free space is an easily readable format

Update Path Environment Variable Using PowerShell In Windows 10 Creators Edition

#Update Path Environment Variable Using PowerShell In Windows 10 Creators Edition

#These are the two PowerShell commands you need to permanently update the Path environment variable in Windows 10 Creators Edition and Windows 10 Anniversary Edition.  If that is all you want to do then you do not need to read further than the following two commands. These commands all work in both PowerShell and PowerShell Direct.

$Old_Path=(Get-ItemProperty -Path 'Registry::HKEY_LOCAL_MACHINE\System\CurrentControlSet\Control\Session Manager\Environment' -Name Path).Path #Save old Path variable value
Set-ItemProperty -Path 'Registry::HKEY_LOCAL_MACHINE\System\CurrentControlSet\Control\Session Manager\Environment' -Name PATH -Value ($Old_Path += ';c:\Important Executables') #Append new path to existing path variable

#The Longer Story…

#Setx is the old way to modify registry entries and set environment variables. It still works if needed but PowerShell commands are all I am attempting to use at this point.

#Check mounted drives and filesystems

#You do not need to run the command below. Is just to prove a point about accessing different mount points.

#Run Get-PSDrive to see the drives available in PowerShell.

Get-PSDrive

#▲You will see Env listed under the Name column and Provider is Environment meaning that the environment variables are an actual mounted file system to PowerShell and the same commands you use to manage other filesystems will work when modifying or adding environment variables manually.

#Add c:\Important Executables to the existing environment path for the current session only.

#Disconnecting your PowerShell session loses these changes when you reconnect to a new session. You instead need to update the registry to make the change permanent. There is no output for the following command but you would need to change c:\Important Executables to the directory you would like to include in your system path. This command has no results or confirmation.

$env:Path += ';c:\Important Executables'

#Check current permanent Path variable

#Check the registry key value for the Path variable to see what it is currently set to.  Any changes so far are still not there after running the last command. The path will revert to the results of the command below once you disconnect and reconnect your PowerShell session.

(Get-ItemProperty -Path 'Registry::HKEY_LOCAL_MACHINE\System\CurrentControlSet\Control\Session Manager\Environment' -Name Path).Path|fl

#Get-ItemProperty before updating the registry value.

 

#▲Get-ItemProperty after updating the registry value.

 

#Use Get-Item Env:Path  to get the currently loaded Path environment variable value

Get-Item Env:Path|fl

#$Env:Path also works as a shortcut for Get-Item Env:Path

#$Env:Path after exiting PowerShell and reconnecting again.

#Perserve old path to $Old_Path and a new path to the existing path

#To save the current registry value for combining with the new path or at least have the original value stored in case you screw something up by typing:

$Old_Path=(Get-ItemProperty -Path 'Registry::HKEY_LOCAL_MACHINE\System\CurrentControlSet\Control\Session Manager\Environment' -Name Path).Path

#Set registry key to the old registry value combined with the new directory

#Modify HKEY_LOCAL_MACHINE\System\CurrentControlSet\Control\Session Manager\Environment|Path properties to include a new directory.

Set-ItemProperty -Path 'Registry::HKEY_LOCAL_MACHINE\System\CurrentControlSet\Control\Session Manager\Environment' -Name PATH -Value ($Old_Path += ';c:\Important Executables') -Verbose -PassThru|fl

#Delete Environment Variables

#Setting a variable = to an empty string will remove it completely.

$Env:VariableName = ''

#Default Path In Windows 10 Creators Edition

#For reference in case something gets screwed up. This is not a commnad
C:\Windows\system32;C:\Windows;C:\Windows\System32\Wbem;C:\Windows\System32\WindowsPowerShell\v1.0\

Enable File And Printer Sharing In Windows 10 Creators Edition Without Using The netsh Command In PowerShell

#Enable File And Printer Sharing In Windows 10 Without Using The netsh Command in PowerShell

#It is as simple as enabling  the pre-configured rule in Windows Firewall to enable File and Printer Sharing in Windows 10 but using netsh is the old fashion way.

#Run this command in an elevated PowerShell prompt and you are done.

Get-NetFirewallRule -DisplayGroup 'File and Printer Sharing'|Set-NetFirewallRule -Profile 'Private, Domain' -Enabled true -PassThru|select Name,DisplayName,Enabled,Profile|ft -a

#The Long Story…

#Allow File and Printer Sharing services through the Windows Firewall to access shared information and to share information of your own. These commands all work in both in PowerShell and PowerShell Direct.

#Get Firewall rules for File and Printer Sharing

#This command shows the individual rules and the network connection profiles that  are explicitly enabled and disabled for the File and Printer Sharing services.

Get-NetFirewallRule -DisplayGroup 'File and Printer Sharing'|select Name,DisplayName,Enabled,Profile|ft -a

#Enable File and Printer Sharing for Private and Domain network profiles

#Enable the  File and Printer Sharing services for the Private and Domain network connection profiles by applying the preconfigured Windows Firewall group rule called File and Printer Sharing by typing this:

Get-NetFirewallRule -DisplayGroup 'File and Printer Sharing'|Set-NetFirewallRule -Profile 'Private, Domain' -Enabled true -PassThru|select Name,DisplayName,Enabled,Profile|ft -a

#▲That is what it looks like under Advanced Sharing Settings when the File and Printer Sharing firewall rule is enabled.

#Set Network Connection Profile to Private.

#I set the variable $InterfaceAlias to automatically query my primary network interface or NIC. The -NlMtuBytes 1500 switch is what makes it work. If you have changed the Maximum Transmission Unit (MTU) from the defaults then this command will need to be modified:

$InterfaceAlias = (Get-NetIPInterface -AddressFamily IPv4 -ConnectionState Connected -NlMtuBytes 1500 -Verbose) #this works for me to automatically identify my nic - mtu 1500 may vary
Set-NetConnectionProfile -InterfaceIndex $InterfaceAlias.ifIndex -Ne

#Disable File and Printer Sharing on all network profiles

Get-NetFirewallRule -DisplayGroup 'File and Printer Sharing'|Set-NetFirewallRule -Enabled false -PassThru|select Name,DisplayName,Enabled,Profile|ft -a

#▲It will look like this when File and Printer Sharing is disabled.

Enable Network Discovery In Windows 10 Without Using the netsh Command In PowerShell

#Enable Network Discovery In Windows 10 Without Using the netsh Command In PowerShell

#It is as simple as enabling  the pre-configured rule in Windows Firewall to enable Network Discovery in Windows 10 but using netsh is the old fashion way.

#Run just this one command in an elevated PowerShell prompt to enable Network Discovery

Get-NetFirewallRule -DisplayGroup 'Network Discovery'|Set-NetFirewallRule -Profile 'Private, Domain' -Enabled true -PassThru|select Name,DisplayName,Enabled,Profile|ft -a

#The Longer Story…

#Enabling the Network Discovery services it what makes the Network icon (formally My Network Places) work properly. These commands all work in both PowerShell and PowerShell Direct.

#Get Firewall rules for Network Discovery

#This command shows the individual rules and the network connection profiles that  are explicitly enabled and disabled for Network Discovery.

Get-NetFirewallRule -DisplayGroup 'Network Discovery'|select Name,DisplayName,Enabled,Profile|ft -a

#Enable Network Discovery for Private and Domain network profiles

#Enable the Network Discovery service for the Private and Domain network profiles by applying the preconfigured Windows Firewall group rule called Network Discovery by typing this:

Get-NetFirewallRule -DisplayGroup 'Network Discovery'|Set-NetFirewallRule -Profile 'Private, Domain' -Enabled true -PassThru|select Name,DisplayName,Enabled,Profile|ft -a

#▲It will look like that in the GUI setup when Network Discovery is enabled.

#Set Network Connection Profile to Private.

Set-NetConnectionProfile -NetworkCategory Private -PassThru

#Disable Network Discovery for all network profiles

#Run this command to disable Network Discovery on all network profiles if you do not wish to keep the service available.

Get-NetFirewallRule -DisplayGroup 'Network Discovery'|Set-NetFirewallRule -Enabled false -PassThru|select Name,DisplayName,Enabled,Profile|ft -a

#▲It will look like that in the GUI setup when Network Discovery is disabled.