Create an ISO file with PowerShell post by Ben Liebowitz

Recently I came across this post. As a VMware admin, you often want to create an ISO as a quick method to copy files or installation files to a VM.

Ben Liebowitz shows how to create an ISO of large files with PowerShell. For the full post use the link below

http://thelowercasew.com/create-an-iso-file-with-powershell

All credit to  for this script

This is a copy of function to use incase the link above fails :

function itself:

 


#Get-Help About-Classesfunction New-IsoFile
{
<# .Synopsis Creates a new .iso file .Description The New-IsoFile cmdlet creates a new .iso file containing content from chosen folders .Example New-IsoFile “c:\tools”,”c:Downloads\utils” This command creates a .iso file in $env:temp folder (default location) that contains c:\tools and c:\downloads\utils folders. The folders themselves are included at the root of the .iso image. .Example New-IsoFile -FromClipboard -Verbose Before running this command, select and copy (Ctrl-C) files/folders in Explorer first. .Example dir c:\WinPE | New-IsoFile -Path c:\temp\WinPE.iso -BootFile “${env:ProgramFiles(x86)}\Windows Kits\10\Assessment and Deployment Kit\Deployment Tools\amd64\Oscdimg\efisys.bin” -Media DVDPLUSR -Title “WinPE” This command creates a bootable .iso file containing the content from c:\WinPE folder, but the folder itself isn’t included. Boot file etfsboot.com can be found in Windows ADK. Refer to IMAPI_MEDIA_PHYSICAL_TYPE enumeration for possible media types: http://msdn.microsoft.com/en-us/library/windows/desktop/aa366217(v=vs.85).aspx .Notes NAME: New-IsoFile AUTHOR: Chris Wu LASTEDIT: 03/23/2016 14:46:50 #>

[CmdletBinding(DefaultParameterSetName=’Source’)]Param(
[parameter(Position=1,Mandatory=$true,ValueFromPipeline=$true, ParameterSetName=’Source’)]$Source,
[parameter(Position=2)][string]$Path = “$env:temp\$((Get-Date).ToString(‘yyyyMMdd-HHmmss.ffff’)).iso”,
[ValidateScript({Test-Path -LiteralPath $_ -PathType Leaf})][string]$BootFile = $null,
[ValidateSet(‘CDR’,’CDRW’,’DVDRAM’,’DVDPLUSR’,’DVDPLUSRW’,’DVDPLUSR_DUALLAYER’,’DVDDASHR’,’DVDDASHRW’,’DVDDASHR_DUALLAYER’,’DISK’,’DVDPLUSRW_DUALLAYER’,’BDR’,’BDRE’)][string] $Media = ‘DVDPLUSRW_DUALLAYER’,
[string]$Title = (Get-Date).ToString(“yyyyMMdd-HHmmss.ffff”),
[switch]$Force,
[parameter(ParameterSetName=’Clipboard’)][switch]$FromClipboard
)

Begin {
($cp = new-object System.CodeDom.Compiler.CompilerParameters).CompilerOptions = ‘/unsafe’
if (!(‘ISOFile’ -as [type])) {
Add-Type -CompilerParameters $cp -TypeDefinition @’
public class ISOFile
{
public unsafe static void Create(string Path, object Stream, int BlockSize, int TotalBlocks)
{
int bytes = 0;
byte[] buf = new byte[BlockSize];
var ptr = (System.IntPtr)(&bytes);
var o = System.IO.File.OpenWrite(Path);
var i = Stream as System.Runtime.InteropServices.ComTypes.IStream;

if (o != null) {
while (TotalBlocks– > 0) {
i.Read(buf, BlockSize, ptr); o.Write(buf, 0, bytes);
}
o.Flush(); o.Close();
}
}
}
‘@
}

if ($BootFile) {
if(‘BDR’,’BDRE’ -contains $Media) { Write-Warning “Bootable image doesn’t seem to work with media type $Media” }
($Stream = New-Object -ComObject ADODB.Stream -Property @{Type=1}).Open() # adFileTypeBinary
$Stream.LoadFromFile((Get-Item -LiteralPath $BootFile).Fullname)
($Boot = New-Object -ComObject IMAPI2FS.BootOptions).AssignBootImage($Stream)
}

$MediaType = @(‘UNKNOWN’,’CDROM’,’CDR’,’CDRW’,’DVDROM’,’DVDRAM’,’DVDPLUSR’,’DVDPLUSRW’,’DVDPLUSR_DUALLAYER’,’DVDDASHR’,’DVDDASHRW’,’DVDDASHR_DUALLAYER’,’DISK’,’DVDPLUSRW_DUALLAYER’,’HDDVDROM’,’HDDVDR’,’HDDVDRAM’,’BDROM’,’BDR’,’BDRE’)

Write-Verbose -Message “Selected media type is $Media with value $($MediaType.IndexOf($Media))”
($Image = New-Object -com IMAPI2FS.MsftFileSystemImage -Property @{VolumeName=$Title}).ChooseImageDefaultsForMediaType($MediaType.IndexOf($Media))

if (!($Target = New-Item -Path $Path -ItemType File -Force:$Force -ErrorAction SilentlyContinue)) { Write-Error -Message “Cannot create file $Path. Use -Force parameter to overwrite if the target file already exists.”; break }
}

Process {
if($FromClipboard) {
if($PSVersionTable.PSVersion.Major -lt 5) { Write-Error -Message ‘The -FromClipboard parameter is only supported on PowerShell v5 or higher’; break }
$Source = Get-Clipboard -Format FileDropList
}

foreach($item in $Source) {
if($item -isnot [System.IO.FileInfo] -and $item -isnot [System.IO.DirectoryInfo]) {
$item = Get-Item -LiteralPath $item
}

if($item) {
Write-Verbose -Message “Adding item to the target image: $($item.FullName)”
try { $Image.Root.AddTree($item.FullName, $true) } catch { Write-Error -Message ($_.Exception.Message.Trim() + ‘ Try a different media type.’) }
}
}
}

End {
if ($Boot) { $Image.BootImageOptions=$Boot }
$Result = $Image.CreateResultImage()
[ISOFile]::Create($Target.FullName,$Result.ImageStream,$Result.BlockSize,$Result.TotalBlocks)
Write-Verbose -Message “Target image ($($Target.FullName)) has been created”
$Target
}
}


Ben goes on to share how he was able to create a variable for the source data, and use get-childitem to get that location and pipe that to creating the ISO. See below:


$source_dir = “Z:\Install\App123”
get-childitem “$source_dir” | New-ISOFile -path e:\iso\app123.iso

 

List Computer Object in an Active Directory OU using PowerShell

How to get a list of computer objects in an active directory OU ( tested against Windows 2016 Active Directory )

A quick PowerShell script using Get-ADComputer  command, a wild card filter and a search base pointing to a specific OU

 

First import modules for active directory in powershell

 

Copy and edit the script below:

## cmd

## dsquery computer -name servername (server name in the OU to get the OU path)

#Example lists domain controller in test.com

#Export list of names to CSV

Get-ADComputer -Filter * -SearchBase “OU=Domain Controllers,DC=test,DC=com” | Select Name | export-csv C:\temp\DCs.csv

 

( Like the post click and advert of interest to give us support)

Sysinternals – Permissions, LoggedOn, Endpoints

How to Get the permission on folders:
PowerShell:
Get-ChildItem | Get-ACL
Path | Owner | Access

or more in depth use:

GUI based : Run AccessEnum against the drive or folder – (SysInternals tool) and save to text file (Run as administrator or a specific user)

Who is logged on via the resource shares:
Launch cmd and run PSLoggedon (SysInternals tool)
Displays :
1) Users logged on locally
2) Users logged on via resource shares

List TCP and UDP Endpoints connected
Run TCPView application (SysInternals tool) and save to text file

Ever need to identify the before and after changes in Active Directory
Use : ADExplorer (SystInternals tool)

Download Sysinternals 
https://docs.microsoft.com/en-gb/sysinternals/downloads/sysinternals-suite

Suggested top 10 sysinternals tools
https://www.techrepublic.com/blog/10-things/10-sysinternals-tools-you-shouldnt-be-without/
See an advert of interest, CLICK IT!  This site is funded by AD clicks.

Get-AdUser -Filter {Multiple Filters Complex } -Properties | Export to CSV

#Import AD modules

import-module servermanager
Add-WindowsFeature -Name “RSAT-AD-PowerShell” -IncludeAllSubFeature

#List AD user accounts and show DisplayName, Email, Title and export to CSV

Get-ADUser -Filter * -Properties DisplayName, EmailAddress, Title | select DisplayName, EmailAddress, Title | Export-CSV “C:\temp\Email_Addresses.csv”

#List AD user accounts and show DisplayName, Email, Title and export to CSV. Advanced filter to show ENABLED accounts only

Get-ADUser -Filter {Enabled -eq $true} -Properties DisplayName, SamAccountName, EmailAddress, Enabled, DistinguishedName | select DisplayName, SamAccountName, EmailAddress, Enabled, DistinguishedName | Export-CSV “C:\temp\Email_Addresses_allusers.csv”

#List AD user accounts and show DisplayName, Email, Title and export to CSV. Advanced filter to show ENABLED accounts only and email address ending @test.com

Get-ADUser -Filter {(Enabled -eq $true) -And (EmailAddress -Like “*@test.com”)} -Properties DisplayName, SamAccountName, EmailAddress, Enabled, DistinguishedName | select DisplayName, SamAccountName, EmailAddress, Enabled, DistinguishedName | Export-CSV “C:\temp\Email_Addresses_testdomain.csv”

Get a list of active computers which have logged on to the domain in the last 7 days

# Trying to work out is servers, laptops or desktops have been decommissioned
# Try this script
# Get a list of active computers which have logged on to the domain in the last 7 days

$Date = (Get-Date).AddDays(-7)
Get-ADComputer -Filter {LastLogonDate -gt $Date} | Select distinguishedName

# https://social.technet.microsoft.com/Forums/windows/en-US/4d412730-5937-48c2-bf17-0dc9db013241/list-active-computers-in-ad?forum=winserverDS
# Credit to Richard Mueller – MVP Enterprise Mobility (Directory Services)

Azure and Containers

What is a container?
A container is a live and running copy of an image which may have been customised.
An image is a read only copy of an image before it was running as a container

How do you implement containers in Azure

Two options, containers we deploy ourselves and containers Microsoft manage
Container can be running on Windows 2016 or Linux OS
CPU and Ram assigned to each individual container

Containers Limited security risk?
Microsoft offers Hyper-V running containers for those concerned
Azure container covers this way.
Others offer shared application containers.

Notes around Docker?
A docker file is like a script to build the container which takes a source and makes an app on an image, which makes a container as its running.

Docker has other tools: Docker toolbox, Docker client and Kitematic (GUI client)

How to Install Docker for Windows

https://docs.docker.com/docker-for-windows/install/

Quick install guide :
1) Navigate to https://docs.docker.com/docker-for-windows/install/#download-docker-for-windows
2) 
On the Install Docker for Windows page, click Get Docker for Windows (Stable).
3) When prompted whether to run or save Docker for Windows Installer.exe, click Run.
4) Once the installation completed, click Close and log out.
<https://github.com/MicrosoftLearning/20533-ImplementingMicrosoftAzureInfrastructureSolutions/blob/master/Instructions/20533D_LAB_AK_07.md>

Note
When you make a mistake deploying a docker-machine .. Ie.. Forget to enter a region… But the machine builds and you enter an error state.
Start again by removing the docker-machine

Launch CMD as admin : docker-machine rm “machine name”

 

Kubernetes
Kubernetes a management tools to for Docker. An alternative Docker Swarm for large scale
Deploy Kubernetes cluster for Linux containers

From <https://docs.microsoft.com/en-us/azure/container-service/kubernetes/container-service-kubernetes-walkthrough>

https://docs.microsoft.com/en-us/azure/aks/intro-kubernetes

DCOS getting started with Kubernetes

https://kubernetes.io/docs/getting-started-guides/dcos/

Set Up Your Microsoft Azure Environment With PowerShell

Step 1 : Install Command Line Tool For PowerShell

https://azure.microsoft.com/en-in/downloads/

Step 2: Launch PowerShell as Administrator

Type in the following

# get the Azure RM module installed first

Install-Module AzureRM

# import the module for use

Import-Module AzureRM

 

Step 3: Getting started with IaaS & PowerShell scripts

#Create a resource group

New-AzureRmResourceGroup -Name Project1ResourceGroup -Location “West Europe”

#Create a new subnet and store in a variable

$Project1Subnet1 = New-AzureRmVirtualNetworkSubnetConfig -Name Project1Subnet1 -AddressPrefix “10.0.1.0/24”

#Create new network and add the subnet stored in variable

$virtualNetwork = New-AzureRmVirtualNetwork -Name ProjectNetwork -ResourceGroupName Project1ResourceGroup -Location “West Europe” -AddressPrefix “10.0.0.0/16” -Subnet $Project1Subnet1

#add additional subnet to the network

Add-AzureRmVirtualNetworkSubnetConfig -Name Project2Subnet2 -VirtualNetwork $virtualNetwork -AddressPrefix “10.0.2.0/24”

$virtualNetwork | Set-AzureRmVirtualNetwork

 

GitHub

Sign up to GitHub.. Create your own repository https://github.com/

Git Hub Desktop to grab a bunch of files… Full Git hub desktop to sync https://desktop.github.com/

Microsoft Azure Virtual Machines and Networking

Azure VMs

VMs types and sizes
https://docs.microsoft.com/en-us/azure/virtual-machines/windows/sizes

Only supported virtual machine type in Azure is “VHD”. VHDX is not currently supported.

Note : Managed disks are now preferred to use instead of storage accounts in legacy Classic Azure

Before migrating VMs to Azure, identify the workloads are supported in a virtual machine. 3rd party vendors may only support their software as PaaS instead of IaaS

VM availability.

2x VMs are better than 1x. I.E your solution is much better if its scalable. Try to utilise VMs in an “availability set”. Servers suitable for availability sets are identical machines file wise. This would give you high availability in the event of failure.

Alternatively, if you only want 1x a virtual machine (example domain controller or DNS), go for solid state (disks with an “s” in the name) and Microsoft have a better SLA for up time.

Managed Disks or Unmanaged Disks
Managed disks go with the VMs,
Try the Market Place for machine images

Scale sets
Scale sets provide VM auto scaling

  • Create rules for scaling
  • DSC config
  • Pure compute box with data at the backend
    i.e Stateless work loads
    Suggestion, for stateless servers, the backend database wont be SQL, it would be the Azure flat file or Azure Cosmos or some read/cache option.

Disk encryption and Azure Key Vault..thoughts
Requirement? Keys are stored in Azure key vault (secure area, no access).
But the drives aren’t physical, so to steal a physical disk would be very challenging to locate.

To steal an virtual drive and mount, its the administrator mistake? Lost or weak admin password?

Networking
Define the DNS server IP
Defining Peerings for vNETS. This allows routes between vNETS

Public IPs will fall in to a network security group for a default firewall. Its purely a basic firewall.

Use Market place to find a 3rd party firewall to lock down internet facing servers (fastest option)
Alternatively route via on prem firewall (slowest option) or route via another cloud firewall (second fastest)

Network Security Group
Inbound and Outbound security groups

By default network security groups have a public IP address and an RDP allow connection.

Network security groups can be assigned to a network card, a subnet or the subnet a load balancer sits within.

Cost : Networks and Network Security Groups are Free

Create your own route tables. Then you have options to assign routes to a subnet or a virtual machine.

Additionally configure the Windows Firewall settings on a virtual machine.

(My thoughts and opinions, are my own @stephenhackers)

Implementing Microsoft Azure Infrastructure Solutions – Overview

Azure – What are the options?

IaaS, PaaS & SaaS

IaaS – Virtual Servers in the Cloud.
Easiest/ Logical method of moving to the cloud is IaaS. Drag your on prem Virtual Machines in the cloud. Basically transferring your on prem virtual machines in to the Cloud (Azure).
In event of failure on prem option, to run in azure, or migrate to azure
Active Directory – Azure AD connect. In a Hybrid environment

PaaS – Azure App Service
Storage, back and recovery services
More advanced – AI – Audio to Text PaaS

SaaS
Complete Software solution

What is the exam?
Exam : 70-533 Implementing Microsoft Azure Infrastructure Solutions.
Expect 1-4 questions are PowerShell based

In theory, you will need another exam to qualify for the certification MCSE Cloud

Why move to Azure?
DR solutions
Hybrid options
Cost saving option – Turning off services over night will massively save money IaaS.
Auto scaling
Pay As You Go : Azure for your dev environment

SaaS

Location knowledge
Note : Geographic areas and some cost more to host and some have limited features.

West Europe would appear to be the best option for local businesses in Sunderland (UK).

But – Check features are available in a region.
https://azure.microsoft.com/en-gb/regions/services/

Pricing Calculator / Estimator
https://azure.microsoft.com/en-gb/pricing/calculator/

Documentation
Location to learn information https://docs.microsoft.com/en-us/azure/

DevOPS : How to deploy to Azure . https://docs.microsoft.com/en-gb/vsts/deploy-azure/

Market Place : Search for products available on Azure

Azure Services / Categories
Compute, Networking, Data and Storage, Web & Mobile, Other services include AD, automation, logging, monitoring

Azure Portals
https://Portal.azure.com
Or old world
https://account.azure.com

Deployment methodologies
Visual studio or visual studio code (free option)
Resource templates. Json files

Log Analytics and ( Operations Management Suite )
Centralised location for gathering log information
Patch management view
Change management view
Resource monitoring

Thought : Could this be described as a new version of System Center, SCOM, WSUS, but a cloud version?

GitHub 
Github.com/MicrosoftLearning

https://github.com/MicrosoftLearning/20533-ImplementingMicrosoftAzureInfrastructureSolutions/tree/master/Instructions

Resource Groups and RBAC
Setup Resource Groups & Tags
Setup Access Control (IAM) Roles (RBAC)

Basic PowerShell Commands
Add-azureRMaccount
Get-AzureRMsubscription
Get-AzureRMresourceProvider

Networking and Providers
Location Providers – UK is London

London

AT&T NetBond, British Telecom, Colt, Equinix, InterCloud, Internet Solutions – Cloud Connect, Interxion, Jisc, Level 3 Communications, Megaport, MTN, NTT Communications, Orange, Tata Communications, Telecity Group, Telehouse – KDDI, Telenor, Verizon, Vodafone, Zayo Group+

From <https://docs.microsoft.com/en-us/azure/expressroute/expressroute-locations-providers>

Azure Virtual Networks
Choose the IP address spaces. Don’t use a subnet where you might duplicate your on prem servers.
Azure utilises some IPs .. So smallest subnet /29 subnet

Azure Load Balancer – Overview
Internal, Internet, Application Gateway, Traffic manager
SSL offload & WAF

Azure DNS
PaaS DNS is quite limited or Create a VM hosting VMs for internal DNS / Domain Controller.

Template Examples
Github.com/Azure-quickstart-templates
Deploy to azure ( for speed, test it out at your own risk )

(My thoughts and opinions, are my own @stephenhackers)