vin01
Expert
Expert

export output to text file

With this script I can deploy vms with the desired roles inside the guest OS. I'm thinking move all the displayed output while executing the script into a logfile(txt) and save it in a location.

Is it possible to add all the below script into a scriptblock and save the output into a variable and at the end we can export the data in the variable into txt file.

Write-Host "Enter the required Information when Prompted" -ForegroundColor Yellow

Add-Type -AssemblyName Microsoft.VisualBasic

$vcenter = [Microsoft.VisualBasic.Interaction]::InputBox("Enter vcenter Name")

$vcenterCred= Get-Credential -Message "Enter Credentials to Connect vCenter"

Write-Host 'All Required Inputs Received Script is starting VMs Deployment' -ForegroundColor Yellow

Write-Host "Connecting to vCenter $vcenter"

Try {

Connect-VIServer $vcenter -Credential $vcenterCred  -ErrorAction Stop

}

Catch [VMware.VimAutomation.Sdk.Types.V1.ErrorHandling.VimException.ViServerConnectionException] {

$wshell = New-Object -ComObject Wscript.Shell -ErrorAction Stop

$wshell.Popup("Incorrect vCenter",0,"vCenter Connection",16) | Out-Null

    return

}

catch {

$wshell = New-Object -ComObject Wscript.Shell -ErrorAction Stop

$wshell.Popup("Incorrect vCenter credentials",0,"vCenter Connection",16) | Out-Null

    return

}

$inputfile=Import-Csv -Path 'C:\LIBPROJECT\InputFile\answerfilecsv.csv' -UseCulture

$wusclientrolesetup= $inputfile |?{$_.serverroles -contains 'WUS'} -ErrorAction SilentlyContinue

$wsusclientserver=$wusclientrolesetup.VMName + '.' + $wusclientrolesetup.Sitename

$ntpclientrolesetup=$inputfile |?{$_.serverroles -contains 'NTP'} -ErrorAction SilentlyContinue

$ntpserver=$ntpclientrolesetup.VMName +'.'+$ntpclientrolesetup.Sitename

$deploytask=@()

if($dnsserver=$inputfile|?{$_.serverroles -contains 'DNS'}){

$vmhost= (Get-Cluster $dnsserver.Cluster |Get-VMHost |Get-Random|select).name

$dst= (Get-VMHost $vmhost |Get-Datastore 'LIBDatastore').Name

#| Sort-Object -Property FreespaceGB -Descending:$deploytask1rue | Select-Object -First 1

$vmnetwork= (Get-VirtualPortGroup -VMHost $vmhost |?{$_.VLanID -eq $dnsserver.vLANID}).Name

$Chars = [Char[]]"abcdefghijklmnopqrstuvwxyz" 

$RandomNameWindows = ($Chars | Get-Random -Count 😎 -join ""

$deploytask1empwindowsSpec = New-OSCustomizationSpec -OSType Windows -Name $RandomNameWindows -FullName $dnsserver.UserName -AdminPassword $dnsserver.Password -AutoLogonCount 1  -Workgroup 'NCR' -OrgName 'NCR' -NamingScheme vm -ChangeSid -Type NonPersistent

$networkspecProperties = @{OSCustomizationNicMapping= Get-OSCustomizationNicMapping -OSCustomizationSpec $RandomNameWindows}

$networkspecProperties.IpMode = "UseStaticIP"

$networkspecProperties.IpAddress = $dnsserver.IP

$networkspecProperties.SubNetMask = $dnsserver.Subnet

$networkspecProperties.DefaultGateway = $dnsserver.Gateway

$networkspecProperties.dns = $dnsserver.DNS1,$dnsserver.DNS2

$networkspecProperties.Position = '1'

Set-OSCustomizationNicMapping @networkspecProperties | Out-Null

$deploytask+=New-VM -Name $dnsserver.VMName -Template $dnsserver.Template -Host $vmhost  -Datastore $dst -DiskStorageFormat Thin  -OSCustomizationSpec $deploytask1empwindowsSpec -Confirm:$false -RunAsync

while('Running','Queued' -contains $deploytask.State){

Write-Progress -Activity "$($dnsserver.VMName) Creation Status" -Status "0%" -PercentComplete $deploytask.PercentComplete

1..10 | ForEach-Object -Process {     

sleep 2

Write-Progress -Activity "$($dnsserver.VMName) Creation Status" -Status "$($_ * 10)%" -PercentComplete ($_ * 10)  }

$deploytask = Get-Task -Id $deploytask.Id 

Write-Progress -Activity '$dnsserver.VMName Creation is' -Completed

}

Remove-OSCustomizationSpec -OSCustomizationSpec $deploytask1empwindowsSpec -Confirm:$false

Set-VM -VM $dnsserver.VMName -MemoryGB $dnsserver.Memory -NumCpu $dnsserver.vCpu -Confirm:$false

Get-NetworkAdapter $dnsserver.VMName | Set-NetworkAdapter -NetworkName $vmnetwork -Confirm:$false -StartConnected:$true -ErrorAction SilentlyContinue

Start-VM -VM $dnsserver.VMName -Confirm:$false

$now = Get-Date

$eventTypes = Get-VIEvent -Entity $dnsserver.VMName -Start $now -MaxSamples ([int]::MaxValue) | % {$_.GetType().Name}

while ($eventTypes -notcontains 'CustomizationSucceeded' -and

  $eventTypes -notcontains 'CustomizationFailed’) {

  Start-Sleep -Seconds 5

  $eventTypes = Get-VIEvent -Entity $dnsserver.VMName -Start $now -MaxSamples ([int]::MaxValue) | % {$_.GetType().Name}

}

$dnsvm= Get-VM $dnsserver.VMName

while($dnsvm.ExtensionData.Guest.ToolsRunningStatus -eq "guestToolsNotRunning"){

Start-Sleep -Seconds 3

$dnsvm.ExtensionData.UpdateViewData("Guest.ToolsRunningStatus")

}

$dnsserverinstall= @'

Install-WindowsFeature  DNS -includeManagementTools

Add-DnsServerPrimaryZone -Name $($dnsserver.Sitename) -ZoneFile $($dnsserver.Sitename)

Add-DnsServerPrimaryZone -NetworkId "$($dnsserver.IP.Split('.')[0..2] -join '.').0/24" -ZoneFile $($dnsserver.Sitename)

'@

$dnsserverinstallSub = $ExecutionContext.InvokeCommand.ExpandString($dnsserverinstall)

$guestoperationstatus= Get-VM $dnsserver.VMName

while($guestoperationstatus.ExtensionData.Guest.GuestOperationsReady -ne "True"){

Start-Sleep -Seconds 3

$guestoperationstatus.ExtensionData.UpdateViewData("Guest.GuestOperationsReady")

}

Invoke-VMScript -VM $dnsserver.VMName -GuestUser $dnsserver.UserName -GuestPassword $dnsserver.Password -ScriptType Powershell -ScriptText $dnsserverinstallSub

$defaultwindowssettings= @'

Set-ItemProperty -Path "HKLM:\Software\Policies\Microsoft\Windows\WindowsUpdate" -Name "WUServer" -Value "https://$($wsusclientserver):80"

Set-ItemProperty -Path "HKLM:\Software\Policies\Microsoft\Windows\WindowsUpdate" -Name "WUStatusServer" -Value "https://$($wsusclientserver):80"

Get-ItemProperty -Path "HKLM:\Software\Policies\Microsoft\Windows\WindowsUpdate\AU"

Set-ItemProperty -Path "HKLM:\Software\Policies\Microsoft\Windows\WindowsUpdate\AU" -Name "NoAutoUpdate" -Value "0"

Set-ItemProperty -Path "HKLM:\Software\Policies\Microsoft\Windows\WindowsUpdate\AU" -Name "AUOptions" -Value "3"

Set-ItemProperty -Path "HKLM:\Software\Policies\Microsoft\Windows\WindowsUpdate\AU" -Name "ScheduledInstallDay" -Value "0"

Set-ItemProperty -Path "HKLM:\Software\Policies\Microsoft\Windows\WindowsUpdate\AU" -Name "ScheduledInstallTime" -Value "3"

Set-ItemProperty -Path "HKLM:\Software\Policies\Microsoft\Windows\WindowsUpdate\AU" -Name "UseWUServer" -Value "1"

#NTPClientSetup

Push-Location

Set-Location HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\DateTime\Servers

Set-ItemProperty . 0 $ntpserver

Set-ItemProperty . "(Default)" "0"

Set-Location HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\DateTime\Servers

Set-ItemProperty . 1 $ntpserver

Set-Location HKLM:\SYSTEM\CurrentControlSet\services\W32Time\Parameters

Set-ItemProperty . NtpServer "$ntpserver,0x8"

Set-Location HKLM:\SYSTEM\CurrentControlSet\Services\W32Time\Parameters

Set-ItemProperty . Type "NTP"

Set-Location HKLM:\SYSTEM\CurrentControlSet\Services\W32Time\Config\

Set-ItemProperty . AnnounceFlags "5"

Pop-Location

Stop-Service w32time

Start-Service w32time

'@

$defaultwindowssettingssub = $ExecutionContext.InvokeCommand.ExpandString($defaultwindowssettings)

$guestoperationstatus= Get-VM $dnsserver.VMName

while($guestoperationstatus.ExtensionData.Guest.GuestOperationsReady -ne "True"){

Start-Sleep -Seconds 3

$guestoperationstatus.ExtensionData.UpdateViewData("Guest.GuestOperationsReady")

}

Invoke-VMScript -VM $dnsserver.VMName -GuestUser $dnsserver.UserName -GuestPassword $dnsserver.Password -ScriptType Powershell -ScriptText $defaultwindowssettingssub

$addRecord = @'

Add-DnsServerResourceRecordA -Name $($dnsrecords.VMName) -IPv4Address $($dnsrecords.IP) -ZoneName $($dnsrecords.Sitename) -CreatePtr

'@

foreach($dnsrecords in $inputfile){

$addRecordSub = $ExecutionContext.InvokeCommand.ExpandString($addRecord)

$guestoperationstatus= Get-VM $dnsserver.VMName

while($guestoperationstatus.ExtensionData.Guest.GuestOperationsReady -ne "True"){

Start-Sleep -Seconds 3

$guestoperationstatus.ExtensionData.UpdateViewData("Guest.GuestOperationsReady")

}

Invoke-VMScript -VM $dnsserver.VMName -GuestUser $dnsserver.UserName -GuestPassword $dnsserver.Password -ScriptType Powershell -ScriptText $addRecordSub

}

$featureName = 'DNS'

$code = @'

Get-WindowsFeature -Name $featureName | Select -ExpandProperty Installed

'@

$codeSub = $ExecutionContext.InvokeCommand.ExpandString($code)

$result = Invoke-VMScript -VM $dnsserver.VMName -GuestUser $dnsserver.UserName -GuestPassword $dnsserver.Password -ScriptType Powershell -ScriptText $codeSub

if($result.ScriptOutput -match 'True'){

    Write-Host "Feature $featureName installed" -ForegroundColor Yellow

    }

else{

    Write-Host "Feature $featureName installation failed" -ForegroundColor Yellow

}

}

foreach($vmsautodeploy in $inputfile|?{$_.serverroles -notcontains 'DNS'}){

$deploytask1=@()

$vmhost= (Get-Cluster $dnsserver.Cluster |Get-VMHost |Get-Random|select).name

$dst= (Get-VMHost $vmhost |Get-Datastore 'LIBDatastore').Name

#| Sort-Object -Property FreespaceGB -Descending:$deploytask1rue | Select-Object -First 1

$vmnetwork= (Get-VirtualPortGroup -VMHost $vmhost |?{$_.VLanID -eq $dnsserver.vLANID}).Name

if($vmsautodeploy.GuestOSType -eq 'windows'){

$Chars = [Char[]]"abcdefghijklmnopqrstuvwxyz" 

$RandomNameWindows = ($Chars | Get-Random -Count 😎 -join ""

$deploytask1empwindowsSpec = New-OSCustomizationSpec -OSType Windows -Name $RandomNameWindows -FullName $vmsautodeploy.UserName -AdminPassword $vmsautodeploy.Password -AutoLogonCount 1  -Workgroup 'NCR' -OrgName 'NCR' -NamingScheme vm -ChangeSid -Type NonPersistent

$networkspecProperties = @{OSCustomizationNicMapping= Get-OSCustomizationNicMapping -OSCustomizationSpec $RandomNameWindows }

$networkspecProperties.IpMode = "UseStaticIP"

$networkspecProperties.IpAddress = $vmsautodeploy.IP

$networkspecProperties.SubNetMask = $vmsautodeploy.Subnet

$networkspecProperties.DefaultGateway = $vmsautodeploy.Gateway

$networkspecProperties.dns = $dnsserver.DNS1,$dnsserver.DNS2

$networkspecProperties.Position = '1'

Set-OSCustomizationNicMapping @networkspecProperties | Out-Null

$deploytask1+=New-VM -Name $vmsautodeploy.VMName -Template $vmsautodeploy.Template -Host $vmhost  -Datastore $dst -DiskStorageFormat Thin  -OSCustomizationSpec $deploytask1empwindowsSpec -Confirm:$false -RunAsync

while('Running','Queued' -contains $deploytask1.State){

Write-Progress -Activity "$($vmsautodeploy.VMName) Creation Status" -Status "0%" -PercentComplete $deploytask1.PercentComplete

1..10 | ForEach-Object -Process {     

sleep 2

Write-Progress -Activity "$($vmsautodeploy.VMName) Creation Status" -Status "$($_ * 10)%" -PercentComplete ($_ * 10)  }

$deploytask1 = Get-Task -Id $deploytask1.Id 

Write-Progress -Activity "$($vmsautodeploy.VMName) Creation is" -Completed

}

Remove-OSCustomizationSpec -OSCustomizationSpec $deploytask1empwindowsSpec -Confirm:$false

Start-Sleep -Seconds 5

Set-VM -VM $vmsautodeploy.VMName -MemoryGB $vmsautodeploy.Memory -NumCpu $vmsautodeploy.vCpu -Confirm:$false

Get-NetworkAdapter $vmsautodeploy.VMName | Set-NetworkAdapter -NetworkName $vmnetwork -Confirm:$false -StartConnected:$true -ErrorAction SilentlyContinue

Start-VM -VM $vmsautodeploy.VMName -Confirm:$false

$now = Get-Date

$eventTypes = Get-VIEvent -Entity $vmsautodeploy.VMName -Start $now -MaxSamples ([int]::MaxValue) | % {$_.GetType().Name}

while ($eventTypes -notcontains 'CustomizationSucceeded' -and

  $eventTypes -notcontains 'CustomizationFailed’) {

  Start-Sleep -Seconds 5

  $eventTypes = Get-VIEvent -Entity $vmsautodeploy.VMName -Start $now -MaxSamples ([int]::MaxValue) | % {$_.GetType().Name}

}

$vmsautodeploytoolstatus= Get-VM $vmsautodeploy.VMName

while($vmsautodeploytoolstatus.ExtensionData.Guest.ToolsRunningStatus -eq "guestToolsNotRunning"){

Start-Sleep -Seconds 5

$vmsautodeploytoolstatus.ExtensionData.UpdateViewData("Guest.ToolsRunningStatus")

}

if($vmsautodeploy.ServerRoles -eq 'WUS'){

$wusfeatureinstall=@'

Install-WindowsFeature -Name UpdateServices, UpdateServices-WidDB, UpdateServices-Services, UpdateServices-RSAT, UpdateServices-API, UpdateServices-UI

'@

$guestoperationstatus= Get-VM $vmsautodeploy.VMName

while($guestoperationstatus.ExtensionData.Guest.GuestOperationsReady -ne "True"){

Start-Sleep -Seconds 3

$guestoperationstatus.ExtensionData.UpdateViewData("Guest.GuestOperationsReady")

}

Invoke-VMScript -VM $vmsautodeploy.VMName -GuestUser $vmsautodeploy.UserName -GuestPassword $vmsautodeploy.Password -ScriptType Powershell -ScriptText $wusfeatureinstall

$defaultwindowssettings= @'

Set-ItemProperty -Path "HKLM:\Software\Policies\Microsoft\Windows\WindowsUpdate" -Name "WUServer" -Value "https://$($wsusclientserver):80"

Set-ItemProperty -Path "HKLM:\Software\Policies\Microsoft\Windows\WindowsUpdate" -Name "WUStatusServer" -Value "https://$($wsusclientserver):80"

Get-ItemProperty -Path "HKLM:\Software\Policies\Microsoft\Windows\WindowsUpdate\AU"

Set-ItemProperty -Path "HKLM:\Software\Policies\Microsoft\Windows\WindowsUpdate\AU" -Name "NoAutoUpdate" -Value "0"

Set-ItemProperty -Path "HKLM:\Software\Policies\Microsoft\Windows\WindowsUpdate\AU" -Name "AUOptions" -Value "3"

Set-ItemProperty -Path "HKLM:\Software\Policies\Microsoft\Windows\WindowsUpdate\AU" -Name "ScheduledInstallDay" -Value "0"

Set-ItemProperty -Path "HKLM:\Software\Policies\Microsoft\Windows\WindowsUpdate\AU" -Name "ScheduledInstallTime" -Value "3"

Set-ItemProperty -Path "HKLM:\Software\Policies\Microsoft\Windows\WindowsUpdate\AU" -Name "UseWUServer" -Value "1"

#NTPClientSetup

Push-Location

Set-Location HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\DateTime\Servers

Set-ItemProperty . 0 $ntpserver

Set-ItemProperty . "(Default)" "0"

Set-Location HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\DateTime\Servers

Set-ItemProperty . 1 $ntpserver

Set-Location HKLM:\SYSTEM\CurrentControlSet\services\W32Time\Parameters

Set-ItemProperty . NtpServer "$ntpserver,0x8"

Set-Location HKLM:\SYSTEM\CurrentControlSet\Services\W32Time\Parameters

Set-ItemProperty . Type "NTP"

Set-Location HKLM:\SYSTEM\CurrentControlSet\Services\W32Time\Config\

Set-ItemProperty . AnnounceFlags "5"

Pop-Location

Stop-Service w32time

Start-Service w32time

'@

$defaultwindowssettingssub = $ExecutionContext.InvokeCommand.ExpandString($defaultwindowssettings)

$guestoperationstatus= Get-VM $vmsautodeploy.VMName

while($guestoperationstatus.ExtensionData.Guest.GuestOperationsReady -ne "True"){

Start-Sleep -Seconds 3

$guestoperationstatus.ExtensionData.UpdateViewData("Guest.GuestOperationsReady")

}

Invoke-VMScript -VM $vmsautodeploy.VMName -GuestUser $vmsautodeploy.UserName -GuestPassword $vmsautodeploy.Password -ScriptType Powershell -ScriptText $defaultwindowssettingssub

$wsusdownstreamserversetup= @'

New-Item -Path $env:SystemDrive\WSUS -ItemType Directory -Force

sl "C:\Program Files\Update Services\Tools"

.\wsusutil.exe postinstall CONTENT_DIR=C:\WSUS

`$wsus = Get-WSUSServer

`$wsusConfig =`$wsus.GetConfiguration() 

`$wsusConfig.SyncFromMicrosoftUpdate=`$false 

`$wsusConfig.UpstreamWsusServerName='$($vmsautodeploy.UpStreamWUSServer)'

`$wsusConfig.UpstreamWsusServerPortNumber='$($vmsautodeploy.UpStreamWUSServerPort)'

`$wsusConfig.IsReplicaServer=`$True 

`$wsusConfig.TargetingMode="Client" 

`$wsusConfig.Save() 

`$wsusSub = `$wsus.GetSubscription() 

`$wsusSub.SynchronizeAutomatically=`$True 

`$wsusSub.SynchronizeAutomaticallyTimeOfDay="12:00:00" 

`$wsusSub.NumberOfSynchronizationsPerDay="1"  

`$wsusSub.Save() 

`$wsusSub.StartSynchronization()

'@

$wsusdownstreamserversetupSub = $ExecutionContext.InvokeCommand.ExpandString($wsusdownstreamserversetup)

$guestoperationstatus= Get-VM $vmsautodeploy.VMName

while($guestoperationstatus.ExtensionData.Guest.GuestOperationsReady -ne "True"){

Start-Sleep -Seconds 3

$guestoperationstatus.ExtensionData.UpdateViewData("Guest.GuestOperationsReady")

}

Invoke-VMScript -VM $vmsautodeploy.VMName -GuestUser $vmsautodeploy.UserName -GuestPassword $vmsautodeploy.Password -ScriptType Powershell -ScriptText $wsusdownstreamserversetupSub

$featureName = 'UpdateServices'

$code = @'

Get-WindowsFeature -Name $featureName | Select -ExpandProperty Installed

'@

$codeSub = $ExecutionContext.InvokeCommand.ExpandString($code)

$result = Invoke-VMScript -VM $vmsautodeploy.VMName -GuestUser $vmsautodeploy.UserName -GuestPassword $vmsautodeploy.Password -ScriptType Powershell -ScriptText $codeSub

if($result.ScriptOutput -match 'True'){

    Write-Host "Feature $featureName installed" -ForegroundColor Yellow

    }

else{

    Write-Host "Feature $featureName installation failed" -ForegroundColor Yellow

}

}

elseif($vmsautodeploy.ServerRoles -eq 'NTP'){

$ntpautoconfigwindows=@'

Push-Location

Set-Location HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\DateTime\Servers

Set-ItemProperty . 0 "time00.sweng.ncr.com"

Set-ItemProperty . "(Default)" "0"

Set-Location HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\DateTime\Servers

Set-ItemProperty . 1 "time01.sweng.ncr.com"

Set-Location HKLM:\SYSTEM\CurrentControlSet\services\W32Time\Parameters

Set-ItemProperty . NtpServer "time00.sweng.ncr.com,0x8"

Set-Location HKLM:\SYSTEM\CurrentControlSet\Services\W32Time\Parameters

Set-ItemProperty . Type "NTP"

Set-Location HKLM:\SYSTEM\CurrentControlSet\Services\W32Time\Config\

Set-ItemProperty . AnnounceFlags "5"

Pop-Location

Stop-Service w32time

Start-Service w32time

'@

$guestoperationstatus= Get-VM $vmsautodeploy.VMName

while($guestoperationstatus.ExtensionData.Guest.GuestOperationsReady -ne "True"){

Start-Sleep -Seconds 3

$guestoperationstatus.ExtensionData.UpdateViewData("Guest.GuestOperationsReady")

}

Invoke-VMScript -VM $vmsautodeploy.VMName -GuestUser $vmsautodeploy.UserName -GuestPassword $vmsautodeploy.Password -ScriptType Powershell -ScriptText $ntpautoconfigwindows

$defaultwindowssettings= @'

Set-ItemProperty -Path "HKLM:\Software\Policies\Microsoft\Windows\WindowsUpdate" -Name "WUServer" -Value "https://$($wsusclientserver):80"

Set-ItemProperty -Path "HKLM:\Software\Policies\Microsoft\Windows\WindowsUpdate" -Name "WUStatusServer" -Value "https://$($wsusclientserver):80"

Get-ItemProperty -Path "HKLM:\Software\Policies\Microsoft\Windows\WindowsUpdate\AU"

Set-ItemProperty -Path "HKLM:\Software\Policies\Microsoft\Windows\WindowsUpdate\AU" -Name "NoAutoUpdate" -Value "0"

Set-ItemProperty -Path "HKLM:\Software\Policies\Microsoft\Windows\WindowsUpdate\AU" -Name "AUOptions" -Value "3"

Set-ItemProperty -Path "HKLM:\Software\Policies\Microsoft\Windows\WindowsUpdate\AU" -Name "ScheduledInstallDay" -Value "0"

Set-ItemProperty -Path "HKLM:\Software\Policies\Microsoft\Windows\WindowsUpdate\AU" -Name "ScheduledInstallTime" -Value "3"

Set-ItemProperty -Path "HKLM:\Software\Policies\Microsoft\Windows\WindowsUpdate\AU" -Name "UseWUServer" -Value "1"

#NTPClientSetup

Push-Location

Set-Location HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\DateTime\Servers

Set-ItemProperty . 0 $ntpserver

Set-ItemProperty . "(Default)" "0"

Set-Location HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\DateTime\Servers

Set-ItemProperty . 1 $ntpserver

Set-Location HKLM:\SYSTEM\CurrentControlSet\services\W32Time\Parameters

Set-ItemProperty . NtpServer "$ntpserver,0x8"

Set-Location HKLM:\SYSTEM\CurrentControlSet\Services\W32Time\Parameters

Set-ItemProperty . Type "NTP"

Set-Location HKLM:\SYSTEM\CurrentControlSet\Services\W32Time\Config\

Set-ItemProperty . AnnounceFlags "5"

Pop-Location

Stop-Service w32time

Start-Service w32time

'@

$defaultwindowssettingssub = $ExecutionContext.InvokeCommand.ExpandString($defaultwindowssettings)

$guestoperationstatus= Get-VM $vmsautodeploy.VMName

while($guestoperationstatus.ExtensionData.Guest.GuestOperationsReady -ne "True"){

Start-Sleep -Seconds 3

$guestoperationstatus.ExtensionData.UpdateViewData("Guest.GuestOperationsReady")

}

Invoke-VMScript -VM $vmsautodeploy.VMName -GuestUser $vmsautodeploy.UserName -GuestPassword $vmsautodeploy.Password -ScriptType Powershell -ScriptText $defaultwindowssettingssub

}

elseif($vmsautodeploy.ServerRoles -eq 'FileServer'){

$fileserverfeature=@'

Install-WindowsFeature -Name FS-Resource-Manager, RSAT-FSRM-Mgmt

New-FsrmQuotaTemplate -Name '25GB Volume Usage Limit' -Description 'limit usage to 25GB' -Size 25GB

New-FsrmQuotaTemplate -Name '50GB Volume Usage Limit' -Description 'limit usage to 50GB' -Size 50GB

New-FsrmQuotaTemplate -Name '100GB Volume Usage Limit' -Description 'limit usage to 100GB' -Size 100GB

'@

$guestoperationstatus= Get-VM $vmsautodeploy.VMName

while($guestoperationstatus.ExtensionData.Guest.GuestOperationsReady -ne "True"){

Start-Sleep -Seconds 3

$guestoperationstatus.ExtensionData.UpdateViewData("Guest.GuestOperationsReady")

}

Invoke-VMScript -VM $vmsautodeploy.VMName -GuestUser $vmsautodeploy.UserName -GuestPassword $vmsautodeploy.Password -ScriptType Powershell -ScriptText $fileserverfeature

$defaultwindowssettings= @'

Set-ItemProperty -Path "HKLM:\Software\Policies\Microsoft\Windows\WindowsUpdate" -Name "WUServer" -Value "https://$($wsusclientserver):80"

Set-ItemProperty -Path "HKLM:\Software\Policies\Microsoft\Windows\WindowsUpdate" -Name "WUStatusServer" -Value "https://$($wsusclientserver):80"

Get-ItemProperty -Path "HKLM:\Software\Policies\Microsoft\Windows\WindowsUpdate\AU"

Set-ItemProperty -Path "HKLM:\Software\Policies\Microsoft\Windows\WindowsUpdate\AU" -Name "NoAutoUpdate" -Value "0"

Set-ItemProperty -Path "HKLM:\Software\Policies\Microsoft\Windows\WindowsUpdate\AU" -Name "AUOptions" -Value "3"

Set-ItemProperty -Path "HKLM:\Software\Policies\Microsoft\Windows\WindowsUpdate\AU" -Name "ScheduledInstallDay" -Value "0"

Set-ItemProperty -Path "HKLM:\Software\Policies\Microsoft\Windows\WindowsUpdate\AU" -Name "ScheduledInstallTime" -Value "3"

Set-ItemProperty -Path "HKLM:\Software\Policies\Microsoft\Windows\WindowsUpdate\AU" -Name "UseWUServer" -Value "1"

#NTPClientSetup

Push-Location

Set-Location HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\DateTime\Servers

Set-ItemProperty . 0 $ntpserver

Set-ItemProperty . "(Default)" "0"

Set-Location HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\DateTime\Servers

Set-ItemProperty . 1 $ntpserver

Set-Location HKLM:\SYSTEM\CurrentControlSet\services\W32Time\Parameters

Set-ItemProperty . NtpServer "$ntpserver,0x8"

Set-Location HKLM:\SYSTEM\CurrentControlSet\Services\W32Time\Parameters

Set-ItemProperty . Type "NTP"

Set-Location HKLM:\SYSTEM\CurrentControlSet\Services\W32Time\Config\

Set-ItemProperty . AnnounceFlags "5"

Pop-Location

Stop-Service w32time

Start-Service w32time

'@

$defaultwindowssettingssub = $ExecutionContext.InvokeCommand.ExpandString($defaultwindowssettings)

$guestoperationstatus= Get-VM $vmsautodeploy.VMName

while($guestoperationstatus.ExtensionData.Guest.GuestOperationsReady -ne "True"){

Start-Sleep -Seconds 3

$guestoperationstatus.ExtensionData.UpdateViewData("Guest.GuestOperationsReady")

}

Invoke-VMScript -VM $vmsautodeploy.VMName -GuestUser $vmsautodeploy.UserName -GuestPassword $vmsautodeploy.Password -ScriptType Powershell -ScriptText $defaultwindowssettingssub

$featureName = 'FS-Resource-Manager'

$code = @'

Get-WindowsFeature -Name $featureName | Select -ExpandProperty Installed

'@

$codeSub = $ExecutionContext.InvokeCommand.ExpandString($code)

$result = Invoke-VMScript -VM $vmsautodeploy.VMName -GuestUser $vmsautodeploy.UserName -GuestPassword $vmsautodeploy.Password -ScriptType Powershell -ScriptText $codeSub

if($result.ScriptOutput -match 'True'){

    Write-Host "Feature $featureName installed" -ForegroundColor Yellow

    }

else{

    Write-Host "Feature $featureName installation failed" -ForegroundColor Yellow

}

}

else{

$defaultwindowssettings= @'

Set-ItemProperty -Path "HKLM:\Software\Policies\Microsoft\Windows\WindowsUpdate" -Name "WUServer" -Value "https://$($wsusclientserver):80"

Set-ItemProperty -Path "HKLM:\Software\Policies\Microsoft\Windows\WindowsUpdate" -Name "WUStatusServer" -Value "https://$($wsusclientserver):80"

Get-ItemProperty -Path "HKLM:\Software\Policies\Microsoft\Windows\WindowsUpdate\AU"

Set-ItemProperty -Path "HKLM:\Software\Policies\Microsoft\Windows\WindowsUpdate\AU" -Name "NoAutoUpdate" -Value "0"

Set-ItemProperty -Path "HKLM:\Software\Policies\Microsoft\Windows\WindowsUpdate\AU" -Name "AUOptions" -Value "3"

Set-ItemProperty -Path "HKLM:\Software\Policies\Microsoft\Windows\WindowsUpdate\AU" -Name "ScheduledInstallDay" -Value "0"

Set-ItemProperty -Path "HKLM:\Software\Policies\Microsoft\Windows\WindowsUpdate\AU" -Name "ScheduledInstallTime" -Value "3"

Set-ItemProperty -Path "HKLM:\Software\Policies\Microsoft\Windows\WindowsUpdate\AU" -Name "UseWUServer" -Value "1"

#NTPClientSetup

Push-Location

Set-Location HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\DateTime\Servers

Set-ItemProperty . 0 $ntpserver

Set-ItemProperty . "(Default)" "0"

Set-Location HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\DateTime\Servers

Set-ItemProperty . 1 $ntpserver

Set-Location HKLM:\SYSTEM\CurrentControlSet\services\W32Time\Parameters

Set-ItemProperty . NtpServer "$ntpserver,0x8"

Set-Location HKLM:\SYSTEM\CurrentControlSet\Services\W32Time\Parameters

Set-ItemProperty . Type "NTP"

Set-Location HKLM:\SYSTEM\CurrentControlSet\Services\W32Time\Config\

Set-ItemProperty . AnnounceFlags "5"

Pop-Location

Stop-Service w32time

Start-Service w32time

'@

$defaultwindowssettingssub = $ExecutionContext.InvokeCommand.ExpandString($defaultwindowssettings)

$guestoperationstatus= Get-VM $vmsautodeploy.VMName

while($guestoperationstatus.ExtensionData.Guest.GuestOperationsReady -ne "True"){

Start-Sleep -Seconds 3

$guestoperationstatus.ExtensionData.UpdateViewData("Guest.GuestOperationsReady")

}

Invoke-VMScript -VM $vmsautodeploy.VMName -GuestUser $vmsautodeploy.UserName -GuestPassword $vmsautodeploy.Password -ScriptType Powershell -ScriptText $defaultwindowssettingssub

}

}

else {

$Chars = [Char[]]"abcdefghijklmnopqrstuvwxyz" 

$RandomNameLinux = ($Chars | Get-Random -Count 9) -join ""

$deploytask1emplinuxSpec = New-OSCustomizationSpec -OSType Linux -Name $RandomNameLinux -Domain 'NCR'  -Type NonPersistent -ErrorAction SilentlyContinue

$networkspecProperties = @{OSCustomizationNicMapping= Get-OSCustomizationNicMapping -OSCustomizationSpec $RandomNameLinux }

$networkspecProperties.IpMode = "UseStaticIP"

$networkspecProperties.IpAddress = $vmsautodeploy.IP

$networkspecProperties.SubNetMask = $vmsautodeploy.Subnet

$networkspecProperties.DefaultGateway = $vmsautodeploy.Gateway

#$networkspecProperties.dns = $dnsserver.DNS1,$dnsserver.DNS2

$networkspecProperties.Position = '1'

Set-OSCustomizationNicMapping @networkspecProperties | Out-Null

$deploytask1+=New-VM -Name $vmsautodeploy.VMName -Template $vmsautodeploy.Template -Host $vmhost  -Datastore $dst -DiskStorageFormat Thin  -OSCustomizationSpec $deploytask1emplinuxSpec -Confirm:$false -RunAsync

while('Running','Queued' -contains $deploytask1.State){

Write-Progress -Activity "$($vmsautodeploy.VMName) Creation Status" -Status "0%" -PercentComplete $deploytask1.PercentComplete

1..10 | ForEach-Object -Process {     

sleep 2

Write-Progress -Activity "$($vmsautodeploy.VMName) Creation Status" -Status "$($_ * 10)%" -PercentComplete ($_ * 10)  }

$deploytask1 = Get-Task -Id $deploytask1.Id 

Write-Progress -Activity "$($vmsautodeploy.VMName) Creation is" -Completed

}

Remove-OSCustomizationSpec -OSCustomizationSpec $deploytask1emplinuxSpec -Confirm:$false

Start-Sleep -Seconds 3

Set-VM -VM $vmsautodeploy.VMName -MemoryGB $vmsautodeploy.Memory -NumCpu $vmsautodeploy.vCpu -Confirm:$false

Get-NetworkAdapter $vmsautodeploy.VMName | Set-NetworkAdapter -NetworkName $vmnetwork -Confirm:$false -StartConnected:$true -ErrorAction SilentlyContinue

Start-VM -VM $vmsautodeploy.VMName -Confirm:$false

$now = Get-Date

$eventTypes = Get-VIEvent -Entity $vmsautodeploy.VMName -Start $now -MaxSamples ([int]::MaxValue) | % {$_.GetType().Name}

while ($eventTypes -notcontains 'CustomizationSucceeded' -and

  $eventTypes -notcontains 'CustomizationFailed’) {

  Start-Sleep -Seconds 5

  $eventTypes = Get-VIEvent -Entity $vmsautodeploy.VMName -Start $now -MaxSamples ([int]::MaxValue) | % {$_.GetType().Name}

}

$vmsautodeploytoolstatus= Get-VM $vmsautodeploy.VMName

while($vmsautodeploytoolstatus.ExtensionData.Guest.ToolsRunningStatus -eq "guestToolsNotRunning"){

Start-Sleep -Seconds 3

$vmsautodeploytoolstatus.ExtensionData.UpdateViewData("Guest.ToolsRunningStatus")

}

if($vmsautodeploy.ServerRoles -eq 'Yum Server'){

$yumserverautoconfiglinux=@'

cd /tmp

rpm -ivh vsftpd-3.0.2-22.el7.x86_64.rpm

service vsftpd restart

chkconfig vsftpd on

systemctl start vsftpd.service

systemctl enable vsftpd.service

mkdir /tmp1

mkdir /var/ftp/pub/CentOS7.5x64Bit

mount /dev/cdrom /tmp1

cd /tmp1

cp -r /tmp1/* /var/ftp/pub/CentOS7.5x64Bit/

umount /dev/cdrom

'@

$guestoperationstatus= Get-VM $vmsautodeploy.VMName

while($guestoperationstatus.ExtensionData.Guest.GuestOperationsReady -ne "True"){

Start-Sleep -Seconds 3

$guestoperationstatus.ExtensionData.UpdateViewData("Guest.GuestOperationsReady")

}

Copy-VMGuestFile -VM $vmsautodeploy.VMName -Source 'C:\Prerequisites\Linux\vsftpd-3.0.2-22.el7.x86_64.rpm' -Destination '/tmp' -GuestUser $vmsautodeploy.UserName -GuestPassword $vmsautodeploy.Password -LocalToGuest

Invoke-VMScript -VM $vmsautodeploy.VMName -GuestUser $vmsautodeploy.UserName -GuestPassword $vmsautodeploy.Password -ScriptText $yumserverautoconfiglinux -ScriptType Bash

#Copy-VMGuestFile -VM $vmsautodeploy.VMName -Source 'C:\Prerequisites\Linux\CentOS7_5x64Bit.zip' -Destination '/var/ftp/pub/' -GuestUser $vmsautodeploy.UserName -GuestPassword $vmsautodeploy.Password -LocalToGuest

}

elseif($vmsautodeploy.ServerRoles -eq 'NTP'){

$ntpautoconfiglinux=@'

'@

$guestoperationstatus= Get-VM $vmsautodeploy.VMName

while($guestoperationstatus.ExtensionData.Guest.GuestOperationsReady -ne "True"){

Start-Sleep -Seconds 3

$guestoperationstatus.ExtensionData.UpdateViewData("Guest.GuestOperationsReady")

}

Invoke-VMScript -VM $vmsautodeploy.VMName -GuestUser $vmsautodeploy.UserName -GuestPassword $vmsautodeploy.Password -ScriptText $ntpautoconfiglinux -ScriptType Bash

}

else{

$yumserverIP=$inputfile |?{$_.serverroles -eq 'None'}

$defaultlinuxsettings=@'

cd /etc/yum.repos.d/

rm -rf *

cat <<EOF >  Cent.repo

[$($yumserverIP.IP)]

comment ="CentOS7_5x64Bit"

baseurl=ftp://$($yumserverIP.IP)/pub/CentOS7_5x64Bit

gpgcheck=0

EOF

'@

$defaultlinuxsettingssub=$ExecutionContext.InvokeCommand.ExpandString($defaultlinuxsettings)

$guestoperationstatus= Get-VM $vmsautodeploy.VMName

while($guestoperationstatus.ExtensionData.Guest.GuestOperationsReady -ne "True"){

Start-Sleep -Seconds 3

$guestoperationstatus.ExtensionData.UpdateViewData("Guest.GuestOperationsReady")

}

Invoke-VMScript -VM $vmsautodeploy.VMName -GuestUser $vmsautodeploy.UserName -GuestPassword $vmsautodeploy.Password -ScriptText $defaultlinuxsettingssub -ScriptType Bash

}

}

}

Write-Host '***VMS were sucessfully deployed***' -ForegroundColor Yellow

Regards Vineeth.K
0 Kudos
3 Replies
LucD
Leadership
Leadership

Why a script block?

Just place this in a .ps1 file, and then redirect the output of the run.
But since you have been using Write-Host, you will have to start the script via the System.Diagnostics.Process method.

There are other ways, but this one is rather straightforward.

For example, you have the following script named hello.ps1 in folder C:\Scripts

Write-Host "Hello World!"

Now you can run this and capture the output (in C:\Temp\log.txt) with

$pinfo = New-Object System.Diagnostics.ProcessStartInfo

$pinfo.FileName = "powershell.exe"

$pinfo.RedirectStandardError = $true

$pinfo.RedirectStandardOutput = $true

$pinfo.UseShellExecute = $false

$pinfo.Arguments = "C:\Scripts\hello.ps1"


$p = New-Object System.Diagnostics.Process

$p.StartInfo = $pinfo

$p.Start() | Out-Null

$p.WaitForExit()


$output = $p.StandardOutput.ReadToEnd()

$output += $p.StandardError.ReadToEnd()

$output | Out-File -FilePath C:\Temp\log.txt


Blog: lucd.info  Twitter: @LucD22  Co-author PowerCLI Reference

0 Kudos
vin01
Expert
Expert

When I executed (Write-Host "Hello World!") in a ps1 file it just opens power shell window and from there no progress.

pastedImage_0.png

I tried to run a simple authentication to vcenter (.ps1) it asked the required details but the output file shows vcenter name not recognized.

Used ps1 file

Write-Host "Enter the required Information when Prompted" -ForegroundColor Yellow

Add-Type -AssemblyName Microsoft.VisualBasic

$vcenter = [Microsoft.VisualBasic.Interaction]::InputBox("Enter vcenter Name")

$vcenterCred= Get-Credential -Message "Enter Credentials to Connect vCenter"

Write-Host 'All Required Inputs Received Script is starting VMs Deployment' -ForegroundColor Yellow

Write-Host "Connecting to vCenter $vcenter"

Try {

Connect-VIServer $vcenter -Credential $vcenterCred  -ErrorAction Stop

}

Catch [VMware.VimAutomation.Sdk.Types.V1.ErrorHandling.VimException.ViServerConnectionException] {

$wshell = New-Object -ComObject Wscript.Shell -ErrorAction Stop

$wshell.Popup("Incorrect vCenter",0,"vCenter Connection",16) | Out-Null

    return

}

catch {

$wshell = New-Object -ComObject Wscript.Shell -ErrorAction Stop

$wshell.Popup("Incorrect vCenter credentials",0,"vCenter Connection",16) | Out-Null

    return

}

Get-VM LIBPRO06 |Select Name

Output snap with logfile:

pastedImage_2.png

Regards Vineeth.K
0 Kudos
LucD
Leadership
Leadership

Perhaps an easier solution might be to change all your Write-Host cmdlets with Write-Output.

That output can be redirected.

For example, pleace these 2 lines in a .ps1 file

Write-Host "Hello World 1"

Write-Output  "Hello World 2"

Now you can run the script with

C:\Scripts\test2.ps1 > C:\Temp\log.txt

And the log file will contain
Hello World 2


Blog: lucd.info  Twitter: @LucD22  Co-author PowerCLI Reference

0 Kudos