JB490

                        Penguin's dream:

                        WINter (with it's coldest WINDs)
                        is not forever, it's just a season!
                          + Chocolatey
                          + PowerShell 7
                          + Windows Terminal
                          + Start-Service SSHD
                          + WSL and WSL2
                          + UTF8, ASCII, Add-Content, Out-File

## OPENSSH on WINDOWS 1903 ENTERPRISE EVALUATION AND MORE.. ##

# PREFACE

1. Hyper-V on/off:

  PS#> Enable-WindowsOptionalFeature -Online -FeatureName Microsoft-Hyper-V -All
  PS#> Disable-WindowsOptionalFeature -Online -FeatureName Microsoft-Hyper-V-All
  
or

  CMD# dism.exe /Online /Enable-Feature:Microsoft-Hyper-V /All
  CMD# dism.exe /Online /Disable-Feature:Microsoft-Hyper-V-All
  
sometimes

  CMD# BCDEDIT /Set {current} hypervisorlaunchtype auto
  CMD# bcdedit /set hypervisorlaunchtype off


2. Clone and refresh MAC. Put both computers into NAT network with DHCP support.
 
  PS#> ipconfig /all
  10.0.2.4  BURATINO
  10.0.2.15 BARBIE

======
 
# AUTOMATIC UPDATES

  https://social.technet.microsoft.com/Forums/lync/en-US
    /d3a2694c-32da-4158-943a-81c2904ffb3d
    /disable-automatic-updates-in-2016?forum=WinServerPreview

  Local group policy editor
    Administrative Templates
      Windows Components
        Windows Updates
          R: Configure Automatic Updates -> Disabled
          
  (Inactive in Enterprise Evaluation 90 days Trial)

# a kind of dazibao: powershell pipe transfers objects, # 
# not visible cmdlet results.                           #
 
======
    
# SET HOSTNAME

  Settings -> Find [ Computer name ]
    View your PC name
      [ Rename this PC ]
      
  PS#> Rename-Computer -NewName "BARBIE" -Restart

======

# SET NETWORK TO PRIVATE

  Tray Network Icon -> 
    Ethernet (Connected) -> 
      DblClick Private networks

======

# ACTIVATE SSHD SERVICE

  PS#> Get-WindowsCapability -Online | ? Name -like 'OpenSSH*'
  
  PS#> Add-WindowsCapability -Online -Name OpenSSH.Server~~~~0.0.1.0
  
  PS#> Start-Service sshd
  PS#> Set-Service -Name sshd -StartupType 'Automatic'
  PS#> Get-NetFirewallRule -Name *ssh*
  
Set default shell for SSH sessions:

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

======

# SET ADMINISTRATOR PASSWORD
  
  run compmgmt.msc (rclick on Start, win+r) or
  
  PS#> compmgmt.msc
   
  Local Users and Groups ->
    Users -> rclick Administrator -> Set Password

======

# ENABLE PSREMOTING (OPTIONAL)

  PS#> Enable-PSRemoting -force
  
  PS#> winrm set winrm/config/client '@{TrustedHosts="10.0.2.4, 10.0.2.15"}'

======

# ELEVATING POWERSHELL (OPTIONAL)

It seems that it is enough to enable administrator account as here:
  https://www.ghacks.net/2014/11/12/how-to-enable-the-hidden-windows-10-administrator-account/

  PS#> net user 
  PS#> net user administrator /active:yes
  PS#> net user administrator 
  
Fig 1. Commented session snapshot: 

  PS C:\Windows\system32> net user

  User accounts for \\BURATINO

  ----------------------------------------------------------------------
  Administrator            DefaultAccount           Guest
  opilane                  sshd                     WDAGUtilityAccount
  The command completed successfully.

  PS C:\Windows\system32> net user administrator /active:yes
  The command completed successfully.

  PS C:\Windows\system32> net user administrator
  User name                    Administrator
  Full Name
  Comment                      Built-in account for administering 
                               the computer/domain
  User's comment
  Country/region code          000 (System Default)
  Account active               Yes                    <==== SUCCESS
  Account expires              Never

  Password last set            ‎11/‎3/‎2019 7:02:26 PM
  Password expires             Never
  Password changeable          ‎11/‎3/‎2019 7:02:26 PM
  Password required            Yes
  User may change password     Yes

  Workstations allowed         All
  Logon script
  User profile
  Home directory
  Last logon                   Never

  Logon hours allowed          All

  Local Group Memberships      *Administrators
  Global Group memberships     *None
  
  The command completed successfully.

  ----------------------------------------------------------------------

# CHOCOLATEY. 

Okay, It's time to install now.. Login with, say, putty as:

  login:    opilane
  password: <one_just_set_earlier>

  PS#> Set-ExecutionPolicy Unrestricted
  PS#> iex ((New-Object System.Net.WebClient).DownloadString('https://chocolatey.org/install.ps1'))

  PS# choco feature enable -n allowGlobalConfirmation
  PS# choco install vim strawberryperl notepadplusplus far thonny busybox grep wget
  
You need to restart once..

# WGET

  PS#> cd C:\ProgramData\chocolatey\bin\
  PS#> mv .\wget.exe uwget.exe

======

# ED

  PS#> cd ~
  PS#> busybox ed
  :a
  cd ~
  mkdir tmp
  cd tmp
  uwget -c --no-check-certificate https://iweb.dl.sourceforge.net/project/gnuwin32/ed/1.2/ed-1.2-bin.zip
  uwget -c --no-check-certificate https://iweb.dl.sourceforge.net/project/gnuwin32/ed/1.2/ed-1.2-dep.zip
  Expand-Archive ed-1.2-dep.zip
  Expand-Archive ed-1.2-bin.zip
  mv .\ed-1.2-dep\bin\regex2.dll C:\ProgramData\chocolatey\bin\
  mv .\ed-1.2-bin\bin\ed.exe C:\ProgramData\chocolatey\bin\
  cd ~
  .
  w install_ed.ps1
  q

  PS#> Set-ExecutionPolicy unrestricted
  PS#> .\install_ed.ps1
  PS#> rm .\install_ed.ps1

======

# ALIAS FOR NOTEPAD++, MD5SUM, C#, ISELEVATED.PS1

PS#> Write-Output "notepad++ %1" | Out-File -Force -Encoding "ASCII" "C:\ProgramData\chocolatey\bin\n.bat"
PS#> cat "C:\ProgramData\chocolatey\bin\n.bat"

PS#> Write-Output "certutil.exe -hashfile %1 MD5" | Out-File -Force -Encoding "ASCII" "C:\ProgramData\chocolatey\bin\md5sum.bat"

Add to system path:

  Control Panel ->
    System ->
      Advanced System Settings ->
        Environment Variables -> 
          System Variables:
            Path [New]
    
  C:\Windows\Microsoft.NET\Framework64\v4.0.30319
  
OR SCRIPT CAREFULLY:

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

  # CHECK THAT THE $oldpath CONTAINS CURRENT PATH 
  # AND SAVE THIS TO A BACKUP FILE:

  Write-Output $oldpath | Out-File -Force -Encoding "ASCII" "C:\ProgramData\chocolatey\bin\path.before"

  $newpath = "$oldpath;C:\Windows\Microsoft.NET\Framework64\v4.0.30319"
  
  # DANGEROUS. UPDATE WITH CARE:

  Set-ItemProperty -Path 'Registry::HKEY_LOCAL_MACHINE\System\CurrentControlSet\Control\Session Manager\Environment' -Name PATH -Value $newPath

NOTE: PATH will be modified after GUI relogin.

  PS#> ed /ProgramData/chocolatey/bin/iselevated.ps1
  a
  if ((New-Object Security.Principal.WindowsPrincipal([Security.Principal.WindowsIdentity]::GetCurrent())).IsInRole([Security.Principal.WindowsBuiltInRole]::Administrator))
  {
    Write-Output "Elevated."
  }
  else
  {
    Write-Output "Not elevated."
  }
  .
  w
  q
  PS#> 

NOTE. You see, much honored ed smashes pasted text like a charm!:) So, 

  PS#> choco install vim

Well vim seems better.. Still need to pass file name as

  PS#> vim /ProgramData/chocolatey/bin/iselevated.ps1

NOTE FOR VIM HATERS: how to escape from vi ?

  Press ESC like a mad man, then type :q! or :wq if you believe you have to save entered text.
  
Now play with far editor:

  choco install far
  far /e myfile.txt
  ONLY USE FILES WITH WINDOWS EOL (0d 0a) TO COPY-PASTE
  
======

# WINDOWS SUBSYSTEM FOR LINUX

  https://docs.microsoft.com/en-us/windows/wsl/install-on-server
  https://docs.microsoft.com/en-us/windows/wsl/install-manual
  https://docs.microsoft.com/en-us/windows/wsl/initialize-distro

  PS#> Enable-WindowsOptionalFeature -Online -FeatureName Microsoft-Windows-Subsystem-Linux

Restart Required. (answer Y or PS# Restart-Computer)

Login over ssh as opilane.

  PS> Invoke-WebRequest -Uri https://aka.ms/wsl-ubuntu-1804 -OutFile Ubuntu.appx -UseBasicParsing
  
answers 225MB written.

  PS> Rename-Item ./Ubuntu.appx ./Ubuntu.zip
  PS> Expand-Archive ./Ubuntu.zip ./Ubuntu

To install -- run ubuntu1804.exe in the target folder.

To run type:

  PS > wsl
  
Sometimes helps this

  PS > wsl --unregister ubuntu-18.04 

======

# COSMETICS

Replace wallpaper, Adjust CMD and Powershell window settings

======

# USEFUL TRICKS

  csc is here
  
    C:\Windows\Microsoft.NET\Framework64\v4.0.30319

  PS> Start-Process Powershell -Verb runAs
  
Essentially, Out-File (and Out-File -Append) gives you Unicode by default and Add-Content gives ASCII by default*.

*) https://stackoverflow.com/questions/22672759
     /append-results-or-text-to-text-file-by-using-powershell
  
  PS> Write-Output "Alpha..Zulu" | Out-File -Encoding "UTF8" zulu
  PS> C:\Users\kiril> cat zulu
  Alpha..Zulu
  
  PS> "This is a test" | Add-Content zulu
  PS> cat zulu
  Alpha..Zulu
  This is a test
  PS> wsl
  $ cat zulu | xxd
  00000000: efbb bf41 6c70 6861 2e2e 5a75 6c75 0d0a  ...Alpha..Zulu..
  00000010: 5468 6973 2069 7320 6120 7465 7374 0d0a  This is a test..

  PS> Write-Output "Alpha..Zulu" | Out-File zulu
  PS> wsl
  $ cat zulu | xxd
  00000000: fffe 4100 6c00 7000 6800 6100 2e00 2e00  ..A.l.p.h.a.....
  00000010: 5a00 7500 6c00 7500 0d00 0a00            Z.u.l.u.....

  PS> Write-Output "Alpha..Zulu" | Out-File -Encoding "ASCII" zulu
  PS> C:\Users\kiril> cat zulu
  Alpha..Zulu
  PS> wsl
  $ cat zulu | xxd
  PS> Write-Output "Alpha..Zulu" | Out-File -Encoding "ASCII" zulu
  $ cat zulu | xxd
  00000000: 416c 7068 612e 2e5a 756c 750d 0a         Alpha..Zulu..
 
NOTE: BOM!

======

# LICENSING

Windows Evaluation Center

  https://www.microsoft.com/en-us/evalcenter/evaluate-windows-10-enterprise
  
Please select your evaluation file type:

  (*) ISO - Enterprise
      ISO - LTSC

Rearm (? times)

  https://www.petri.com/how-to-extend-windows-server-evaluation
  
  slmgr -dlv
  slmgr -rearm
  slmgr -dli (like dlv but short)
  
License types:

  Retail
  OEM
  Volume (organisations, domain based)
  Digital license (using hardware signature)
  
Check here:

  * Settings ->
      Update and security ->
        Activation
        
or

  Slmgr.vbs /dlv

======

# LINKS

0. Set or reset a Windows administrator password

  https://kb.iu.edu/d/arni

1. How to use SSH Client and Server on Windows 10
   Written on May 31, 2019 by Dr Donald Kinghorn

  https://www.pugetsystems.com/labs/hpc
    /How-To-Use-SSH-Client-and-Server-on-Windows-10-1470/
    
2. Check if my PowerShell session is elevated

  https://www.itprotoday.com/powershell/check-elevation-powershell
  
3. How to run powershell as an administrator  
  
  https://danielengberg.com/how-to-run-powershell-as-an-administrator/

4. https://blogs.msdn.microsoft.com/virtual_pc_guy
     /2010/09/23/a-self-elevating-powershell-script/
  
5. https://github.com/mkellerman/Invoke-CommandAs

6. https://raymii.org/s/tutorials/SSH_on_Windows_Server_2019.html

7. https://tinkertry.com/how-to-change-windows-10-network-type-from-
     public-to-private
     
8. Create a Custom ISO for Windows 10

    https://itknowledgeexchange.techtarget.com
    /windows-enterprise-desktop
    /create-a-custom-iso-for-windows-10-part-1-of-6/ .. part-6-of-6

9. Белые окошки -- SysPrep

  https://www.white-windows.ru
    /sysprep-shtatnaya-utilita-adaptatsii-windows-k-novomu-zhelezu/
  
A. Какие бывают лицензии Windows

  https://www.white-windows.ru/kakie-byvayut-litsenzii-windows-
    i-kak-uznat-kakuyu-litsenziyu-imeet-vasha-sistema/

B. Создание загрузочных дисков и прочие полезные мелочи

  https://www.bootdev.ru/2018/09/Creating-a-WIM-image.html

C. Яндекс: обои Буратино

  https://www.wallpaperup.com/uploads/wallpapers/2017/03/08/1081087/bfe57da001f91caf469e99eb09be8bfb-1000.jpg

D. Яндекс: обои Барби

  https://wallpapertag.com/wallpaper/full/c/2/3/942731-popular-barbie-wallpapers-1920x1080-ipad-retina.jpg

E. Download and install the Windows ADK

  https://docs.microsoft.com/en-us/windows-hardware/get-started
     /adk-install
     
   https://go.microsoft.com/fwlink/?linkid=2086042


# ANNEX A. C# halo.cs

  // https://csharp.net-tutorials.com/getting-started/hello-world/

  using System;
  using System.Collections.Generic;
  using System.Linq;
  using System.Text;
  using System.Threading.Tasks;

  namespace helloWorld
  {
    class halo
    {
      static void Main(string[] args)
      {
          Console.WriteLine("Hello, world!");
          // Console.ReadLine();
      }
    }
  }
  
  
ANNEX B. C# formHalo.cs

  // https://docs.microsoft.com/en-us/dotnet/framework/winforms
  //   /how-to-create-a-windows-forms-application-from-the-command-line

  using System;
  using System.ComponentModel;
  using System.Drawing;
  using System.Windows.Forms;

  namespace FormWithButton {
    public class formHalo : Form
    {
      public Button button1;
      public formHalo(){
        button1 = new Button();
        button1.Size = new Size(40, 40);
        button1.Location = new Point(30, 30);
        button1.Text = "Click me";
        this.Controls.Add(button1);
        button1.Click += new EventHandler(button1_Click);
      }
      private void button1_Click(object sender, EventArgs e) {
        MessageBox.Show("Hello World");
      }
      [STAThread]
      static void Main(){
        Application.EnableVisualStyles();
        Application.Run(new formHalo());
      }
    }
  }
 
 
# ANNEX C. hexdump.c

  http://stahlworks.com/dev/index.php?tool=csc01
  
  https://www.codeproject.com/Articles/11705/Hex-Editor-in-c
  
  
# ANNEX D. AUTOTRANSLATION FROM RUSSIAN.

## VSYSPREP - A STANDARD UTILITY FOR ADAPTING WINDOWS 
TO A NEW HARDWARE

03/12/2018 Dmitry Demchenko

  https://www.white-windows.ru/sysprep-shtatnaya-utilita-
  adaptatsii-windows-k-novomu-zhelezu/

Sysprep is a standard Windows deployment tool, a utility designed primarily for OEMs and corporate IT professionals. Used to prepare branded and, accordingly, corporate assemblies of Windows. OEM-assemblers and IT specialists on a computer or virtual machine prepare a Windows reference image: they are installing updates into the system installed from the official distribution, they add corporate, brand or partner software, they remove or disable the functionality built into the system, and configure the necessary system settings.

Then, the already configured system is untied from the components of the computer device on which the work was carried out, identifying data is removed. And, finally, they pack all this into an image for deployment on the end devices of users or employees of the company. This can be either an ISO installation file or a backup. In this chain of actions, Sysprep plays the role of a decoupling mechanism from hardware and depersonalization. 

In what cases this utility can be useful to an ordinary user, how it works, what limitations it has, and how to deal with them - all this below.


# What is Sysprep

The Sysprep utility removes component drivers, resets the SID, cleans the system event log and Temp folders, resets activation (up to three times), destroys restore points. In general, it makes sure that with a new start we get a clean operating system, only with certain presets.


# Areas of use

Creating reference images of modified Windows assemblies for deployment to multiple client computers is Sysprep's primary goal. But the utility can also be used by ordinary users on their home devices. You can resort to it's help in case of unstable operation of Windows after replacing the components. Better yet, apply it before changing these components.

Sysprep is also a tool with which you can transfer the working system to another computer device with different components. Professional-level backup software for such cases provides functions like Universal Restore, Adaptive Restore, etc. These functions do, in fact, the same as Sysprep, only at the recovery stage. Thanks to this, any old Windows backup can be turned into a reference image. But such kind of functions are rarely seen in free backup tools. For example, they are a part of the paid software from Acronis and Paragon, and are also available only in paid software editions from AOMEI and EaseUS. If you untie Windows from components using Sysprep, you can transfer it to another computer using bootable media using free backup tools, for example, from the same developers as AOMEI and EaseUS.


# Launch utility

Starting Sysprep is easy using the Win+R:

  Run: sysprep

Thus, in Explorer, we will get direct access to its launch file.

  Explorer
  
  C:\Windows\System32\Sysprep
  
    sysprep.exe


# Unlinking from hardware

To untie Windows from the current components before replacing them or creating a backup of the system for transferring to another device, use the "Go to OOBE window" and select shutdown.

  fig. 1. Sysprep.exe
  

# System preparation program

In this situation, the utility will only reset the component drivers. If you check the "Prepare for use" option, some of actions will be taken to transfer the system to a new user -- cleaning the system log and temporary files, deleting recovery points, resetting the SID, resetting activation, etc.

The utility will do its job and the computer will shut down. Next, you can proceed with certain actions -- change components, backup the system from bootable media. With a new start-up -- both on the source device and on one where the system was transferred using recovery from backup -- we will first see how the drivers are installed on new hardware components, and then we get to the OOBE window. The OOBE window is nothing more than the system welcome screen, which we usually see at the final stage of the Windows installation, where we need to specify regional data and create our account.

  fig 2. OOBE window

And since there is no need to create a new account when replacing hardware components or restoring Windows on other computers, we can safely reset this process with Ctrl+Shift+F3. These are the login keys to the hidden administrator account. The system will try to load it, but will refuse to access. Click OK.

  fig 3. Login

And after the restart, we will see the familiar lock screen with all existing accounts.


# Audit mode

Audit mode provides the ability to access the Windows environment without creating a specific user account, as in mentioned above administrator account mode.

  fig 4. Audit mode

In this mode, in fact, OEM-manufacturers and IT-specialists of the companies configure the reference image of the system with the necessary drivers, parameters and implemented software. Initial entry into audit mode is performed during the installation phase of Windows -- the one that should subsequently become the reference image, and on which there should not be any user accounts and identifying data. After the device preparation stage, we get to the final stage of the system installation, starting with setting regional settings. And here we press the keys Ctrl+Shift+F3.

  fig 5. Region

After the reboot, we get into audit mode. The latter boots with the default Sysprep window running for convenience. In this mode you can proceed with Windows modification. If in the process of making changes to the system, for example, when installing certain software, a reboot is required, all you need to do is close the utility window and reboot in the usual way. After rebooting, the system will restart in audit mode. The work in this mode is completed as it was discussed in the previous paragraph of the article by selecting the OOBE screen in the Sysprep window. And usually using the preparation for use option.

  fig 6. sysprep

Reference modified Windows is usually made from a clean, freshly installed system. But it is possible to create a reference install image based on an used system. To do this, run Sysprep inside the working Windows and select the transition to audit mode in its window. The final parameter is a reboot.

  fig 7. Switch to audit mode

Entering the audit mode, we can delete the accounts of those users who have previously worked with the system, configure what is needed, and then unlink from the components (and, if necessary, from the identifying data) with the transition to the OOBE window.

Not every working system may be used to make a reference image. This mechanism has its limitations.


# Solving problems with starting Sysprep

Unfortunately Sysprep would not work if Windows was not installed cleanly, but upgraded from a previous version, cloned, or restored from a backup created on another hardware. In such cases, when you run the utility, we usually get such notification.

  fig 8. Error

In such case something still can be done, however, without guaranteed success in all 100% of cases.

We create a backup of the system or at least stock up on a recovery point, since we will continue to work with the system registry.

We launch it.

We open the way:

  HKEY_LOCAL_MACHINE\SYSTEM\Setup

If the system was updated from the previous version, first of all, in the "Setup" directory itself, we delete the "Upgrade" parameter.

  fig 9. RegEdit

Then we open the "Setup" directory, click on the "Status" subdirectory, here we need the "CleanupState" parameter. Set its value to 7.

  fig 10. CleanupState

If there is no such parameter, create it. In the context menu of the registry window, click "Create", then - "DWORD Parameter (32 bits)"

  fig 11. DWORD parameter

Give a name to the "CleanupState" parameter.

  fig 12. Registry Editor

Set its value to 7. After rebooting, try again to start Sysprep.
