├── .gitignore
├── README.rst
├── answer_files
├── 2012_r2.xml
└── 81.xml
├── build.ps1
├── build_template.json
├── deploy.ps1
├── iso
├── New-SymLink.ps1
├── README.rst
└── features
│ └── 2012_r2.txt
├── machines
├── _default.ps1
└── eval-base-server.ps1
├── scripts
├── Get-WUInstall.ps1
├── Install-GuestAdditions.ps1
├── Install-OpenSSH.ps1
├── Set-PinnedApplication.ps1
├── Set-PoshAsDefault.ps1
├── Set-VagrantUser.ps1
├── _provision.ps1
├── _setup.ps1
├── enable-rdp.ps1
├── enable-winrm.ps1
├── finalize.ps1
├── oracle-cert.cer
├── proxy-module.psm1
├── sdelete.exe
├── set-proxy.ps1
├── vagrant.pub
├── windows-features.ps1
├── windows-tweaks.ps1
└── windows-update.ps1
├── vagrant
└── Vagrantfile
├── vagrant_metadata.json
└── vagrantfile.template
/.gitignore:
--------------------------------------------------------------------------------
1 | /vagrant/.vagrant
2 | /output
3 | /iso/*.ISO
4 |
--------------------------------------------------------------------------------
/README.rst:
--------------------------------------------------------------------------------
1 | Posher
2 | ======
3 |
4 | .. contents::
5 | :local:
6 |
7 | Posher is a build system that generates images for Windows 2012 family of operating systems - all variants of Windows Server 2012 and Windows 8. Machines are defined using Powershell scripts and built using `Packer `__.
8 |
9 | The main features of the system are:
10 |
11 | - Hierarchical machine definition - machine can inherit from another one which serves as a base system and then it can add or tweak options, features and provisioning elements on top of those already defined in the parent machines. The system is made so that all the different types of machines used for specific project can be described and created in this manner while keeping the entire process `DRY `__.
12 | - Strict usage of the Powershell scripting rather then outdated cmd.exe shell.
13 | - Extensive auditing of installed options so that one can understand what is inside the machine just by looking in the log file of the build system.
14 | - Support for multiple virtualization platforms via Packer. Currently, the machines are built for vmWare and VirtualBox providers with addition of Vagrant box. Other providers that Packer supports can easily by added if required.
15 |
16 | Posher can be used for:
17 |
18 | - Creation of referent machines for which developers program desired features. Usage of referent machines solve the *it works on my computer* problem as functionality is considered done if it is successfully deployed and tested on the referent machine(s).
19 | - Using single code base for setting up machines for all types of environments in a service life cycle.
20 | - Creation of immutable infrastructure which is defined and versioned as a source code.
21 |
22 |
23 | Prerequisites
24 | -------------
25 |
26 | - `Windows Management Framework 4.0 `_ or newer.
27 | - `Packer `__
28 | - `VirtualBox `__ (if the build type includes VirtualBox output)
29 | - `vmWare Workstation `__ (if the build type includes vmware output)
30 | - `Vagrant `__ (to test virtualbox boxes)
31 |
32 | The easiest way to install all open source prerequisites is via `Chocolatey `__ repository::
33 |
34 | choco install packer virtualbox vagrant
35 |
36 |
37 | Creating machine
38 | ----------------
39 |
40 | Machines are placed in the ``machines`` directory and described in Powershell syntax. The only input for the machine apart from assets required for provisioning of vendor tools is the ISO image of the desired OS. ISO files can be linked from the Internet, SMB share or locally by placing them into ``iso`` directory (using symbolic link is also an option via ``iso\New-SymLink.ps1`` function).
41 |
42 | To start defining a machine in a Powershell, first check `machines\_default.ps1 `__ which contains all variables supported by the build system and their default values. This file should not be edited - a new Powershell file should be created for each machine which sources aforementioned defaults.
43 |
44 | As an example, lets say we want all servers for the service to have some common foundation on which we can further specialise for different roles. We can create ``base-server.ps1`` to describe this configuration::
45 |
46 | . "$PSScriptRoot/_default.ps1"
47 |
48 | $OS_ISO_NAME = 'SW_DVD5_Windows_Svr_Std_and_DataCtr_2012_R2_64Bit_English_Core_MLF_X19-05182'
49 | $OS_ISO_CHECKSUM = '6823c34a84d22886baea88f60e08b73001c31bc8'
50 | $OS_TYPE = @{vmWare = 'windows8srv-64'; virtualbox = 'Windows2012_64'}
51 | $OS_ANSWER_FILE = '2012_r2'
52 |
53 | $WINDOWS_UPDATE = $true
54 | $WINDOWS_UPDATE_CATEGORIES_LIST += 'CriticalUpdates', 'SecurityUpdates'
55 | #$WINDOWS_UPDATE_KB_LIST += 'KB2939087'
56 |
57 | $WINDOWS_TWEAKS = $true
58 | $WINDOWS_TWEAKS_SCRIPT = {
59 | Explorer-Feature -ShowHidden -ShowSupperHidden -ShowFileExtensions -ShowRun -ShowAdminTools -PSOpenHere
60 | CLI-Feature -EnableQuickEdit
61 | System-Feature -NoUAC -NoHibernation -NoShutDownTracker -NoAutoUpdate
62 | }
63 |
64 | $WINDOWS_FEATURE = $true
65 | $WINDOWS_FEATURE_LIST = @(
66 | "PowerShell-ISE"
67 | )
68 |
69 | This will define the ``base-server`` so that:
70 |
71 | - It will use specified ISO image and answer file with the given name ( ``OS_ISO_NAME`` and ``OS_ANSWER_FILE`` variables ).
72 | - The build option ``WINDOWS_UPDATE`` is enabled which means that during OS setup the specified windows updates will be installed. In this example only critical and security updates are installed (variable ``WINDOWS_UPDATE_CATEGORIES_LIST``). The commented option ``WINDOWS_UPDATE_KB_LIST`` is used for deterministic updates as defining updates via category list will produce non-deterministic operating system on which updates are installed as soon as they are available which can potentially create a problem with some applications.
73 | - The build option ``WINDOWS_TWEAKS`` is enabled which is integrated list of small Windows customizations which are self describing in above case. The option accepts single script block which calls 3 functions that tweak OS installation.
74 | - At the end, there is one Windows features that will be installed on the base server - Powershell-ISE.
75 |
76 | Later we can either build this base server or create another machine based on it. If, for instance, we need IIS web server on top of the base server definition, we can define the machine ``server-web.ps1`` such as::
77 |
78 | . "$PSScriptRoot/base-server.ps1"
79 |
80 | $CPU = 4
81 | $MEMORY = 4GB
82 | $DISK = 60GB
83 |
84 | $WINDOWS_FEATURE_LIST += @(
85 | # Web server modules
86 | "Web-Common-Http",
87 | "Web-Security",
88 | # "Web-App-Dev"
89 | "Web-CGI",
90 | "Web-ISAPI-Ext",
91 | "Web-ISAPI-Filter",
92 | "Web-Includes",
93 | # Web Management Tools
94 | "Web-Mgmt-Console",
95 | "Web-Scripting-Tools",
96 | "Web-Mgmt-Service",
97 | # Dot.Net 4.5
98 | "NET-Framework-45-ASPNET"
99 | "NET-Framework-45-Features"
100 | )
101 |
102 | # Vagrant settings
103 | $BOX_DESCRIPTION = "IIS web server"
104 | $BOX_VERSION = 1.1
105 | $BOX_STORE = "file:////itshare.mycompany.com/_images/projectX/projectx-server-web"
106 |
107 | In the above example the new server is defined so that it:
108 |
109 | - uses specified number of CPUs (default is 1) and desired memory and disk size.
110 | - adds new Windows features to the ``WINDOWS_FEATURE_LIST`` of the already specified features in the base server (hence ``+=``).
111 | - defines few Vagrant related variables - ``BOX_XXX`` - which may be needed for the development environments with the machine.
112 |
113 | Depending on the parameter, the machine can either inherit the parameter value from the parent machine, redefine it, or add it to the existing list. Machines can be defined this way to the arbitrary depth and any machine in the hierarchy can be built by specifying its name as an argument of the build script.
114 |
115 | Host and guest provision
116 | ------------------------
117 |
118 | There is an option to specify provision scriptblock on either the host (the one that builds the image, before or after the image build process is started) or the machine that is being built.
119 |
120 | The following machine ``server-web-extra`` inherits from the ``server-web`` and during the build it requires credentials for the share, exports the credentials temporarily to copy and use them within the context of the new machine in order to install the application from the share. At the end of the build it deletes temporary file on the host::
121 |
122 | . "$PSScriptRoot/server-web.ps1"
123 |
124 | #Executes on host
125 | $BUILD_START_LIST += {
126 | $err = export_credential $args.Credential -Store './machines' -AskMsg 'Enter credentials for the administrative share:'
127 | if ($err) { "Credential export failed - $err"; return $false }
128 | }
129 |
130 | #Executes on host
131 | $BUILD_END_LIST += {
132 | "Deleting temporary files on host"
133 | rm "./machines/*.sss" -ea ignore
134 | }
135 |
136 | #Executes on guest
137 | $PROVISION_LIST += {
138 | "Loading credentials"
139 | $f = gi "*.sss"
140 | $Credential = load_credential $f
141 | if (!$Credential) { throw "Can't load credentials." }
142 | rm $f
143 |
144 | New-PSDrive -Name adminshare -PSProvider FileSystem -Root \\itshare.mycompany.com\install -Credential $Credential
145 | $installer = "adminshare:\ToolXYZ\toolxyz.msi"
146 | start -Wait msiexec -ArgumentList "/quiet", "ADDLOCAL=ALL", "/i $installer"
147 | if (Test-Path 'c:\program files\toolxyz\toolxyz.exe) { "Install OK" } else { throw "Install failed" }
148 | }
149 |
150 | function load_credential($File) {
151 | if (!$File) { return }
152 | $u = $File.BaseName.Replace('-', '\')
153 | $p = ConvertTo-SecureString (gc $File) -Key (1..16)
154 | New-Object -Type PSCredential -ArgumentList $u, $p
155 | }
156 |
157 | function export_credential($Credential, $Store, $AskMsg){
158 | gi $Store -ErrorVariable err -ea 0 | out-null
159 | if ($err) { return $err }
160 |
161 | if (!$Credential -or $Credential.gettype() -ne [PSCredential]) {
162 | $Credential = Get-Credential $Credential -Message $AskMsg
163 | if (!$Credential) { Write-Error "Credential input canceled." -ev err -ea 0; return $err }
164 | }
165 |
166 | try {
167 | $fp = "{0}/{1}.sss" -f $Store, $Credential.UserName.Replace('\', '-')
168 | rm $fp -ea ignore
169 | ConvertFrom-SecureString -SecureString $Credential.Password -Key (1..16) | out-file $fp
170 | } catch { $_ }
171 | }
172 |
173 | Options
174 | -------
175 |
176 | The build system currently supports the following options that are so commonly tweaked that they deserved to be specially handled:
177 |
178 | WINDOWS_UPDATE
179 | Allows installation of predefined set of updates with desired level of determination. To be totally deterministic specify list of KBs, otherwise specify some of the allowed categories.
180 |
181 | WINDOWS_TWEAKS
182 | Allows for installation of small tweaks from the list of supported tweaks. For the complete list of tweaks see ``scripts\windows-tweaks.ps1``.
183 |
184 | WINDOWS_FEATURES
185 | Enables the list of the Windows features that are shipped with the OS and installed using ``OptionalFeatures.exe`` on a workstation Windows (Control Panel -> Turn Windows Features On or Off) or using Server Manager Roles and Features GUI interface on a server. To get the complete list of features, use the following cmdlets: ``Get-WindowsOptionalFeature`` (workstation) and ``Get-WindowsFeature`` (server).
186 |
187 | PROVISION
188 | Enables the list of provisioning Powershell scriptblocks. Each machine can add its own provisioner in the ``$PROVISION_LIST`` list.
189 |
190 | FINALIZE
191 | Allows finalization script to run. This script cleans up the system, deletes temporary files, defragments and shreds the disk etc. The procedure is lengthy and can be disabled while testing.
192 |
193 | Each of those options can be turned on or off using simple Powershell statement. For instance::
194 |
195 | $WINDOWS_UPDATE = $false
196 |
197 | will turn off integrated Windows update build option which may be useful during testing as updates usually take a long time to finish.
198 |
199 | For detailed description of all options check out comments in the ``machines\_default.ps1`` script.
200 |
201 | Build
202 | -----
203 |
204 | To generate the virtual image use ``build.ps1`` script::
205 |
206 | .\build.ps1 -Machine server-web
207 |
208 | The length of the procedure depends on the machine definition - location of the ISO file, whether Windows updates are enabled and so on. After the build process finishes, the images and log files will be available in the ``output\`` directory. Detailed log of the complete operation is saved in the file ``posher.log``. Distribution of the machine should include this file because it provides information about the machine installation and any step of the installation starting from the ISO file can be manually reconstructed using the information within the log file and few other files that are also stored in the output folder.
209 |
210 | To build the machine only for the specific platform use the build parameter ``Only``::
211 |
212 | .\build.ps1 -Machine server-web -Only virtualbox
213 |
214 | Without this parameter build will produce machines for all supported platforms in parallel.
215 |
216 | When you try to build above machine with host and guest provisioning ( server-web-extra ), credential pop up will appear on the host and the build continues after the user enters it correctly or fails on any error. To build this machine non-interactively, parameter can be passed to the build script via ``Data`` argument::
217 |
218 | ./build.ps1 -Machine base-server-extra -Data @{ Credential = Get-Credential } -Verbose
219 |
220 | If the provisioning code is big, put it in the separate script file in the ``./machines`` directory and source it from the provisioning scriptblock.
221 |
222 | For detailed description of the build function execute ``man .\build.ps1 -Full``.
223 |
224 | Accessing the machine
225 | ---------------------
226 |
227 | After the build is completed, you can boot up the VirtualBox image using Vagrant. ``Vagrantfile`` is designed in such way that you can easily test any local images (those in the ``output`` directory). Quickly switch from using local to remote box storage using ``VAGRANT_LOCAL`` variable. Any machine that is created in ``machines`` directory can be booted this way without modifications of the ``Vagrantfile``::
228 |
229 | vagrant destroy server-web
230 | vagrant box remove server-web
231 |
232 | $Env:VAGRANT_LOCAL=1
233 | vagrant up server-web
234 | vagrant rdp server-web
235 |
236 | The last two commands will fire up the machine and connect to it via remote desktop. If something goes wrong and RDP is not working you can set ``$Env:VAGRANT_GUI=1`` to show VirtualBox GUI, otherwise machine will run in the headless mode.
237 |
238 | The other way to connect to the machine is via Powershell remoting using its IP address::
239 |
240 | etsn 192.168.0.xx -Credential localhost\vagrant
241 |
242 | For this to work the machine IP (or glob ``*``) must be specified in the ``TrustedHosts`` parameter in the WinRM client settings::
243 |
244 | Set-Item WSMan:\localhost\Client\TrustedHosts * -Force
245 |
246 | Once you are happy with the machines those should be deployed to the share. For this purpose Vagrant metadata json is crafted that among other things provides option to version remote boxes so that users can see when those boxes they use are later updated during ``vagrant up`` command. Developers can use those boxes but to provide access to them manual intervention of ``Vagrantfile`` is required to specify exact machine names - simply replace dynamic ruby hash ``$machines`` with static version listing machine names.
247 |
248 | To test wmWare images with Vagrant require proprietary Vagrant driver. If those are not available testing can be done with vmWare Workstation command line tools easily, although setting advanced options such as shared folders and customizing memory and disk will require extra work::
249 |
250 | vmrun -T ws start "output\server-web\packer-server-web-vmware.vmx"
251 |
252 | On production
253 | -------------
254 |
255 | Although one of the design goals of the system was to use the same machine code in the production, test and development environments with any specific configuration moved to environment variables, it is not currently tested in production environments and would at minimal require some security related actions such as removal of vagrant administrative user. Some of the future versions will address those issues.
256 |
257 | More info
258 | ---------
259 |
260 | **Articles**
261 |
262 | - `Immutable Server `__
263 | - `Virtualize Your Windows Development Environments with Vagrant, Packer, and Chocolatey `__
264 | - `In search of a light weight windows vagrant box `__
265 |
266 | **Related Projects**
267 |
268 | - `Packer-Windows `__
269 | - `Boxcutter Windows templates `__
270 |
--------------------------------------------------------------------------------
/answer_files/2012_r2.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 | en-US
7 |
8 | en-US
9 | en-US
10 | en-US
11 | en-US
12 | en-US
13 |
14 |
15 |
16 |
17 |
18 |
19 | Primary
20 | 1
21 | 350
22 |
23 |
24 | 2
25 | Primary
26 | true
27 |
28 |
29 |
30 |
31 | true
32 | NTFS
33 |
34 | 1
35 | 1
36 |
37 |
38 | NTFS
39 |
40 | C
41 | 2
42 | 2
43 |
44 |
45 | 0
46 | true
47 |
48 |
49 |
50 |
51 |
52 |
53 | /IMAGE/NAME
54 | Windows Server 2012 R2 SERVERSTANDARD
55 |
56 |
57 |
58 | 0
59 | 2
60 |
61 |
62 |
63 |
64 |
65 |
66 |
67 |
68 |
69 | OnError
70 |
71 | true
72 | Vagrant
73 | Vagrant
74 |
75 |
76 |
77 |
78 |
79 |
80 | false
81 |
82 | vagrant-2012-r2
83 | Pacific Standard Time
84 |
85 |
86 |
87 | true
88 |
89 |
90 | false
91 | false
92 |
93 |
94 | true
95 |
96 |
97 | true
98 |
99 |
100 |
101 |
102 |
103 |
104 | vagrant
105 | true
106 |
107 | true
108 | vagrant
109 |
110 |
111 |
112 | powershell -ExecutionPolicy Bypass -Command "A:\_setup.ps1 2>&1 | tee c:\packer.log"
113 | Run setup powershell script
114 | 1
115 | true
116 |
117 |
118 |
119 | true
120 | true
121 | true
122 | true
123 | true
124 | Home
125 | 1
126 |
127 |
128 |
129 | vagrant
130 | true
131 |
132 |
133 |
134 |
135 | vagrant
136 | true
137 |
138 | administrators
139 | Vagrant
140 | vagrant
141 | Vagrant User
142 |
143 |
144 |
145 |
146 |
147 |
148 |
149 |
150 | false
151 |
152 |
153 |
154 |
155 |
--------------------------------------------------------------------------------
/answer_files/81.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
9 |
10 | 1
11 | Primary
12 | 60000
13 |
14 |
15 |
16 |
17 | false
18 | NTFS
19 | C
20 | 1
21 | 1
22 |
23 |
24 |
25 | 0
26 | true
27 |
28 | OnError
29 |
30 |
31 | true
32 | Vagrant Administrator
33 | Vagrant Inc.
34 |
35 | Never
36 |
37 |
38 |
39 |
40 |
41 | 0
42 | 1
43 |
44 | OnError
45 | false
46 |
47 |
48 | /IMAGE/NAME
49 | Windows 8.1 Enterprise
50 |
51 |
52 |
53 |
54 |
55 |
56 |
57 | en-US
58 |
59 | en-US
60 | en-US
61 | en-US
62 | en-US
63 | en-US
64 |
65 |
66 |
67 |
68 | false
69 |
70 |
71 |
72 |
73 |
74 |
75 | vagrant
76 | true
77 |
78 |
79 |
80 |
81 | vagrant
82 | true
83 |
84 | Vagrant User
85 | vagrant
86 | administrators
87 | vagrant
88 |
89 |
90 |
91 |
92 | true
93 | true
94 | Home
95 | 1
96 |
97 |
98 |
99 | vagrant
100 | true
101 |
102 | vagrant
103 | true
104 |
105 |
106 |
107 | powershell -ExecutionPolicy Bypass -Command "A:\_setup.ps1 2>&1 | tee c:\packer.log"
108 | Run setup powershell script
109 | 1
110 | true
111 |
112 | false
113 |
114 |
115 |
116 |
117 |
118 | false
119 |
120 |
121 | vagrant-win81
122 | Pacific Standard Time
123 |
124 |
125 |
126 | true
127 |
128 |
129 |
130 |
--------------------------------------------------------------------------------
/build.ps1:
--------------------------------------------------------------------------------
1 | <#
2 | .SYNOPSIS
3 | Build system for packer
4 |
5 | .EXAMPLE
6 | .\build.ps1 -Machine server-web -DeleteOldBuild -Only virtualbox -Headless
7 |
8 | Build only virtualbox and vagrant images for the machine defined in './machines/server-web.ps1',
9 | delete older builds and don't show GUI.
10 | #>
11 | [CmdletBinding()]
12 | param(
13 | # Name of the machine definition file without extension
14 | [parameter(Mandatory=$true)]
15 | [string]$Machine,
16 | # Delete all build. If not specified existance of previous build output will stop the process.
17 | [switch]$DeleteOldBuild,
18 | # Invoke only specified builders
19 | [ValidateSet("vmware", "virtualbox")]
20 | [string]$Only,
21 | # If specified, install without GUI
22 | [switch]$Headless,
23 | # Data for hook scripts
24 | [object]$Data,
25 | # Wait indefintelly at the end of the installation until user intervention.
26 | [switch]$WaitOnEnd
27 | )
28 |
29 | function main() {
30 | $ErrorActionPreference = "Stop"
31 | trap { log ("{0}`n{1}" -f $_, $_.InvocationInfo.PositionMessage) -ExitCode error }
32 |
33 | if ($DeleteOldBuild) { rm ./output/* -r -force -ea ignore }
34 | init_fs
35 |
36 | log "Starting build at $(get-date)"
37 | log "Build command line:`n $build_cmdline`n"
38 |
39 | check_prereq
40 |
41 | . load_machine
42 | render_machine_template
43 |
44 | run_hooks 'BUILD_START_LIST'
45 | if ($WaitOnEnd) { out-file $waitfile }
46 | run_packer
47 | on_end -NoPackerError
48 | }
49 |
50 | function init_fs () {
51 | mkdir './tmp', $output -ea ignore | out-null
52 | out-file -Encoding ascii -InputObject $null $logfile
53 | }
54 |
55 | function load_machine () {
56 | log "Loading machine definition script for '$Machine'"
57 |
58 | $m = "${machines}/${Machine}.ps1"
59 | if (!(Test-Path $m)) { log "Machine file doesn't exist:`n $m" -ExitCode no_machine }
60 | cp $m "./tmp/__machine.ps1" -force
61 | . $m; rv m
62 |
63 | if ($OS_IMAGE) {
64 | gc "./answer_files/$OS_ANSWER_FILE.xml" | % { $_ -replace 'Windows Server 2012 R2 SERVERSTANDARD', $OS_IMAGE } | sc $build_answerfile
65 | } else {
66 | cp "./answer_files/$OS_ANSWER_FILE.xml" $build_answerfile -force
67 | }
68 | }
69 |
70 | function check_prereq() {
71 | log "Validating packer installation"
72 | $p = gcm "packer.exe" -ea ignore
73 | if ($p.Count -eq 0) { log "Packer must be installed and on the PATH. See https://www.packer.io/downloads" -ExitCode prereq }
74 | }
75 |
76 | function create_vagrant_metadata() {
77 | log "Rendering vagrant metadata template"
78 | $BOX_NAME = "$Machine"
79 | $BOX_URL = "$BOX_STORE/${Machine}-virtualbox.box"
80 | $BOX_REVISION = get_revision
81 | gc $vagrant_metadata | out-string | render | Out-File -Encoding ascii "$output/${Machine}.json"
82 | }
83 |
84 | function get_revision() {
85 | if (gcm svn.exe -ea 0) {
86 | try {
87 | $rev = svn info . 2>&1 | sls ^Revision: | out-string
88 | $rev = $rev.Trim() -split ' '
89 | } catch {}
90 | if ($rev) {return $rev[1]}
91 | }
92 | if (gcm git.exe -ea 0) {
93 | $rev = git rev-parse HEAD 2>&1
94 | if ($rev -notlike '*Not a git repository*') { return $rev }
95 | }
96 | }
97 |
98 | function log {
99 | [CmdletBinding()]
100 | param( [parameter(ValueFromPipeline = $true)] [string] $Msg, $ExitCode='')
101 | begin {
102 | if ($exitcode) {
103 | $ErrorActionPreference = "Continue"
104 | Write-Error $Msg 2>&1 | tee $logfile -Append
105 | on_end
106 | exit $ExitCodes[$ExitCode]
107 | }
108 | }
109 | process { $msg | tee $logfile -Append }
110 | }
111 |
112 | function run_hooks([string]$HooksListVar) {
113 | $hooks = Get-Variable $HooksListVar -ea ignore
114 | if (!$hooks) { return }
115 | $hooks = $hooks.Value
116 |
117 | $cnt = $hooks.Length
118 | log "Executing build hooks in $HooksListVar ($cnt)"
119 | $hooks | % {
120 | icm -ScriptBlock $_ -ArgumentList $Data -OutVariable out | log
121 | $last = $out[$out.Count-1]
122 | if ($last.GetType() -eq [Boolean] -and $last -eq $false) {
123 | log "Build start hook terminated the build" -ExitCode hook_fail
124 | }
125 | }
126 | log "Finished executing build hooks in $HooksListVar"
127 | }
128 |
129 | function on_end([switch]$NoPackerError)
130 | {
131 | # DO NOT USE log -ExitCode IN THIS FUNCTION [possible infinite recursion]
132 |
133 | if ($NoPackerError) { create_vagrant_metadata }
134 | run_hooks 'BUILD_END_LIST'
135 | clean_up
136 |
137 | if ($NoPackerError) { log "Build finished OK" } else { log "Build failed!" }
138 | }
139 |
140 | function clean_up()
141 | {
142 | log "Cleaning up"
143 | rm ./packer_cache -r -force -ea ignore
144 | rm ./tmp -r -force -ea ignore
145 | rm ./scripts/__waitfile -ea ignore
146 | }
147 |
148 | function render() {
149 | [CmdletBinding()]
150 | param ( [parameter(ValueFromPipeline = $true)] [string] $s)
151 | $ExecutionContext.InvokeCommand.ExpandString($s)
152 | }
153 |
154 | function render_machine_template()
155 | {
156 | log "Rendering machine build template"
157 | $BUILD_NAME = $Machine
158 | $BUILD_HEADLESS = $Headless.ToString().ToLower()
159 |
160 | $MEMORY = $MEMORY / 1MB
161 | $DISK = $DISK / 1MB
162 |
163 | #Due to the bug in some versions of posh can't use hash in expandstring: http://goo.gl/FoYzVl
164 | # hash works in 5 & 2, doesn't in 4
165 | $OS_TYPE.GetEnumerator() | % { Set-Variable "OS_TYPE_$($_.Name)" $_.Value }
166 | gc $build_template | out-string | render | Out-File -Encoding ascii $buildfile
167 |
168 | log "Validating machine build file"
169 | packer validate $buildfile
170 | if ($LastExitCode) { log "Machine build template validation failed" -ExitCode template }
171 |
172 | }
173 |
174 | function run_packer()
175 | {
176 | log "Building packer command line"
177 | $pa = @("build","-color=false")
178 | if ($Only) { $pa += "-only=$Machine-$Only" }
179 | $pa += $buildfile
180 | $cmd = "packer $pa"
181 |
182 | log "Executing packer:`n $cmd`n"
183 | iex $cmd | log
184 | if ($LastExitCode) { log "Packer build failed (ExitCode: $LastExitCode)" -ExitCode packer }
185 | }
186 |
187 | $ExitCodes = @{
188 | packer = 1
189 | prereq = 2
190 | no_machine = 3
191 | template = 4
192 | hook_fail = 5
193 | error = 9
194 | }
195 |
196 | $output = "./output/$Machine"
197 | $machines = "./machines"
198 | $build_template = "build_template.json"
199 | $vagrant_metadata = "vagrant_metadata.json"
200 |
201 | $buildfile = "$output/build.json"
202 | $logfile = "$output/posher.log"
203 | $waitfile = './scripts/__waitfile'
204 | $build_cmdline = $MyInvocation.Line
205 | $build_answerfile = "$output/Autounattend.xml"
206 |
207 | main
208 |
--------------------------------------------------------------------------------
/build_template.json:
--------------------------------------------------------------------------------
1 | {
2 | "variables": {
3 | "iso_store": "iso",
4 | "iso_name": "$OS_ISO_NAME",
5 | "iso_checksum": "$OS_ISO_CHECKSUM",
6 |
7 | "ssh_name": "vagrant",
8 | "ssh_pass": "vagrant",
9 |
10 | "shutdown": "shutdown /s /t 10 /f /d p:4:1 /c \"Packer Shutdown\"",
11 |
12 | "cpu": "$CPU",
13 | "mem": "$MEMORY",
14 | "disk": "$DISK",
15 |
16 | "headless": $BUILD_HEADLESS,
17 | "output_dir": "output/${BUILD_NAME}"
18 | },
19 | "builders": [
20 | {
21 | "name": "${BUILD_NAME}-vmware",
22 | "type": "vmware-iso",
23 | "iso_url": "{{user ``iso_store``}}/{{user ``iso_name``}}.iso",
24 | "iso_checksum": "{{user ``iso_checksum``}}",
25 | "iso_checksum_type": "sha1",
26 |
27 | "headless": "{{user ``headless``}}",
28 | "boot_wait": "2m",
29 |
30 | "ssh_username": "{{user ``ssh_name``}}",
31 | "ssh_password": "{{user ``ssh_pass``}}",
32 | "ssh_wait_timeout": "4h",
33 |
34 | "shutdown_command": "{{user ``shutdown``}}",
35 | "guest_os_type": "$OS_TYPE_VMWARE",
36 | "disk_size": "{{user ``disk``}}",
37 | "disk_type_id": "0",
38 | "tools_upload_flavor": "windows",
39 | "floppy_files": [ "$BUILD_ANSWERFILE", "./scripts", "./machines", "./tmp/__machine.ps1" ],
40 |
41 | "vnc_port_min": 5900,
42 | "vnc_port_max": 5980,
43 |
44 | "vmx_data": {
45 | "RemoteDisplay.vnc.enabled": "false",
46 | "RemoteDisplay.vnc.port": "5900",
47 | "memsize": "{{user ``mem``}}",
48 | "numvcpus": "{{user ``cpu``}}",
49 | "scsi0.virtualDev": "lsisas1068"
50 | },
51 | "output_directory": "{{user ``output_dir``}}/vmware"
52 | },
53 |
54 | {
55 | "name": "${BUILD_NAME}-virtualbox",
56 | "type": "virtualbox-iso",
57 | "iso_url": "{{user ``iso_store``}}/{{user ``iso_name``}}.iso",
58 | "iso_checksum": "{{user ``iso_checksum``}}",
59 | "iso_checksum_type": "sha1",
60 |
61 | "headless": "{{user ``headless``}}",
62 | "boot_wait": "2m",
63 |
64 | "ssh_username": "{{user ``ssh_name``}}",
65 | "ssh_password": "{{user ``ssh_pass``}}",
66 | "ssh_wait_timeout": "4h",
67 |
68 | "shutdown_command": "{{user ``shutdown``}}",
69 | "guest_os_type": "$OS_TYPE_VIRTUALBOX",
70 | "disk_size": "{{user ``disk``}}",
71 | "floppy_files": [ "$BUILD_ANSWERFILE", "./scripts", "./machines", "./tmp/__machine.ps1" ],
72 | "vboxmanage": [
73 | [ "modifyvm", "{{.Name}}", "--memory", "{{user ``mem``}}" ],
74 | [ "modifyvm", "{{.Name}}", "--cpus", "{{user ``cpu``}}" ]
75 | ],
76 | "output_directory": "{{user ``output_dir``}}/vbox"
77 | }
78 | ],
79 | "provisioners": [
80 | {
81 | "type": "file",
82 | "source": "scripts",
83 | "destination": "/cygdrive/c"
84 | },
85 | {
86 | "type": "file",
87 | "source": "machines/",
88 | "destination": "/cygdrive/c/scripts"
89 | },
90 | {
91 | "type": "file",
92 | "source": "tmp/__machine.ps1",
93 | "destination": "/cygdrive/c/scripts/__machine.ps1"
94 | },
95 | {
96 | "type": "shell",
97 | "remote_path": "C:/Windows/Temp/script.ps1",
98 | "execute_command": "{{.Vars}} powershell -ExecutionPolicy Bypass -File {{ .Path }}",
99 | "scripts": [ "./scripts/_provision.ps1" ]
100 | }
101 | ],
102 | "post-processors": [
103 | {
104 | "type": "vagrant",
105 | "compression_level": 1,
106 | "only": ["${BUILD_NAME}-virtualbox"],
107 | "keep_input_artifact": false,
108 | "vagrantfile_template": "vagrantfile.template",
109 | "output": "{{user ``output_dir``}}/${BUILD_NAME}-{{.Provider}}.box"
110 | }
111 | ]
112 | }
113 |
--------------------------------------------------------------------------------
/deploy.ps1:
--------------------------------------------------------------------------------
1 | param(
2 | # Machine name to copy to the Windows share
3 | # Storage is taken from the machine Metadata
4 | [string]$Machine
5 | )
6 |
7 | $ErrorActionPreference = "Stop"
8 |
9 | if (!(ls output\$Machine\*.box -ea ignore)) { throw "Invalid machine" }
10 |
11 | # Determine storage from the machine metadata
12 | $meta = ls output\$Machine\$Machine.json | gc
13 | $url = $meta -match '"url"'
14 | $store = $url -split '////' | select -Last 1
15 | $store = $store -split "/$machine" | select -First 1
16 | $store = "\\" + $store.Replace('/', '\')
17 |
18 | "Deploying machine: $machine"
19 | "Using store:`n $store"
20 |
21 | $local = "./output/$machine"
22 | $remote = "$store/$machine"
23 | $remote_tmp = "$remote-tmp"
24 |
25 | try {
26 | cp -force -r -Verbose $local $remote_tmp
27 | rm $remote -r -force
28 | mv $remote_tmp $remote
29 | "Deploy OK"
30 | } catch {
31 | "Deploy failed"
32 | $_
33 | rm $remote_tmp -r -force -ea ignore
34 | exit 1
35 | }
36 |
37 | "Deploy finshed"
38 |
39 |
--------------------------------------------------------------------------------
/iso/New-SymLink.ps1:
--------------------------------------------------------------------------------
1 | Function New-SymLink {
2 | <#
3 | .SYNOPSIS
4 | Creates a Symbolic link to a file or directory
5 |
6 | .DESCRIPTION
7 | Creates a Symbolic link to a file or directory as an alternative to mklink.exe
8 |
9 | .PARAMETER Path
10 | Name of the path that you will reference with a symbolic link.
11 |
12 | .PARAMETER SymName
13 | Name of the symbolic link to create. Can be a full path/unc or just the name.
14 | If only a name is given, the symbolic link will be created on the current directory that the
15 | function is being run on.
16 |
17 | .PARAMETER File
18 | Create a file symbolic link
19 |
20 | .PARAMETER Directory
21 | Create a directory symbolic link
22 |
23 | .NOTES
24 | Name: New-SymLink
25 | Author: Boe Prox
26 | Created: 15 Jul 2013
27 |
28 |
29 | .EXAMPLE
30 | New-SymLink -Path "C:\users\admin\downloads" -SymName "C:\users\admin\desktop\downloads" -Directory
31 |
32 | SymLink Target Type
33 | ------- ------ ----
34 | C:\Users\admin\Desktop\Downloads C:\Users\admin\Downloads Directory
35 |
36 | Description
37 | -----------
38 | Creates a symbolic link to downloads folder that resides on C:\users\admin\desktop.
39 |
40 | .EXAMPLE
41 | New-SymLink -Path "C:\users\admin\downloads\document.txt" -SymName "SomeDocument" -File
42 |
43 | SymLink Target Type
44 | ------- ------ ----
45 | C:\users\admin\desktop\SomeDocument C:\users\admin\downloads\document.txt File
46 |
47 | Description
48 | -----------
49 | Creates a symbolic link to document.txt file under the current directory called SomeDocument.
50 | #>
51 | [cmdletbinding(
52 | DefaultParameterSetName = 'Directory',
53 | SupportsShouldProcess=$True
54 | )]
55 | Param (
56 | [parameter(Position=0,ParameterSetName='Directory',ValueFromPipeline=$True,
57 | ValueFromPipelineByPropertyName=$True,Mandatory=$True)]
58 | [parameter(Position=0,ParameterSetName='File',ValueFromPipeline=$True,
59 | ValueFromPipelineByPropertyName=$True,Mandatory=$True)]
60 | [ValidateScript({
61 | If (Test-Path $_) {$True} Else {
62 | Throw "`'$_`' doesn't exist!"
63 | }
64 | })]
65 | [string]$Path,
66 | [parameter(Position=1,ParameterSetName='Directory')]
67 | [parameter(Position=1,ParameterSetName='File')]
68 | [string]$SymName,
69 | [parameter(Position=2,ParameterSetName='File')]
70 | [switch]$File,
71 | [parameter(Position=2,ParameterSetName='Directory')]
72 | [switch]$Directory
73 | )
74 | Begin {
75 | Try {
76 | $null = [mklink.symlink]
77 | } Catch {
78 | Add-Type @"
79 | using System;
80 | using System.Runtime.InteropServices;
81 |
82 | namespace mklink
83 | {
84 | public class symlink
85 | {
86 | [DllImport("kernel32.dll")]
87 | public static extern bool CreateSymbolicLink(string lpSymlinkFileName, string lpTargetFileName, int dwFlags);
88 | }
89 | }
90 | "@
91 | }
92 | }
93 | Process {
94 | #Assume target Symlink is on current directory if not giving full path or UNC
95 | If ($SymName -notmatch "^(?:[a-z]:\\)|(?:\\\\\w+\\[a-z]\$)") {
96 | $SymName = "{0}\{1}" -f $pwd,$SymName
97 | }
98 | $Flag = @{
99 | File = 0
100 | Directory = 1
101 | }
102 | If ($PScmdlet.ShouldProcess($Path,'Create Symbolic Link')) {
103 | Try {
104 | $return = [mklink.symlink]::CreateSymbolicLink($SymName,$Path,$Flag[$PScmdlet.ParameterSetName])
105 | If ($return) {
106 | $object = New-Object PSObject -Property @{
107 | SymLink = $SymName
108 | Target = $Path
109 | Type = $PScmdlet.ParameterSetName
110 | }
111 | $object.pstypenames.insert(0,'System.File.SymbolicLink')
112 | $object
113 | } Else {
114 | Throw "Unable to create symbolic link!"
115 | }
116 | } Catch {
117 | Write-warning ("{0}: {1}" -f $path,$_.Exception.Message)
118 | }
119 | }
120 | }
121 | }
--------------------------------------------------------------------------------
/iso/README.rst:
--------------------------------------------------------------------------------
1 | This folder contains ISO files.
2 | You can copy them here or link them from other directory (including windows shares) using ``mklink`` command.
3 |
4 | In Powershell, use `New-SymLink `_ script::
5 |
6 | $p = "\\storage.mydomain.com\images\win-server-2012\SW_DVD5_Windows_Svr_Std_and_DataCtr_2012_R2_64Bit_English_Core_MLF_X19-05182.ISO"
7 | New-SymLink $p -SymName $(Split-Path $p -Leaf) -File
8 |
--------------------------------------------------------------------------------
/iso/features/2012_r2.txt:
--------------------------------------------------------------------------------
1 |
2 | Display Name Name Install State
3 | ------------ ---- -------------
4 | [ ] Active Directory Certificate Services AD-Certificate Available
5 | [ ] Certification Authority ADCS-Cert-Authority Available
6 | [ ] Certificate Enrollment Policy Web Service ADCS-Enroll-Web-Pol Available
7 | [ ] Certificate Enrollment Web Service ADCS-Enroll-Web-Svc Available
8 | [ ] Certification Authority Web Enrollment ADCS-Web-Enrollment Available
9 | [ ] Network Device Enrollment Service ADCS-Device-Enrollment Available
10 | [ ] Online Responder ADCS-Online-Cert Available
11 | [ ] Active Directory Domain Services AD-Domain-Services Available
12 | [ ] Active Directory Federation Services ADFS-Federation Available
13 | [ ] Active Directory Lightweight Directory Services ADLDS Available
14 | [ ] Active Directory Rights Management Services ADRMS Available
15 | [ ] Active Directory Rights Management Server ADRMS-Server Available
16 | [ ] Identity Federation Support ADRMS-Identity Available
17 | [ ] Application Server Application-Server Available
18 | [ ] .NET Framework 4.5 AS-NET-Framework Available
19 | [ ] COM+ Network Access AS-Ent-Services Available
20 | [ ] Distributed Transactions AS-Dist-Transaction Available
21 | [ ] WS-Atomic Transactions AS-WS-Atomic Available
22 | [ ] Incoming Network Transactions AS-Incoming-Trans Available
23 | [ ] Outgoing Network Transactions AS-Outgoing-Trans Available
24 | [ ] TCP Port Sharing AS-TCP-Port-Sharing Available
25 | [ ] Web Server (IIS) Support AS-Web-Support Available
26 | [ ] Windows Process Activation Service Support AS-WAS-Support Available
27 | [ ] HTTP Activation AS-HTTP-Activation Available
28 | [ ] Message Queuing Activation AS-MSMQ-Activation Available
29 | [ ] Named Pipes Activation AS-Named-Pipes Available
30 | [ ] TCP Activation AS-TCP-Activation Available
31 | [ ] DHCP Server DHCP Available
32 | [ ] DNS Server DNS Available
33 | [ ] Fax Server Fax Available
34 | [X] File and Storage Services FileAndStorage-Services Installed
35 | [ ] File and iSCSI Services File-Services Available
36 | [ ] File Server FS-FileServer Available
37 | [ ] BranchCache for Network Files FS-BranchCache Available
38 | [ ] Data Deduplication FS-Data-Deduplication Available
39 | [ ] DFS Namespaces FS-DFS-Namespace Available
40 | [ ] DFS Replication FS-DFS-Replication Available
41 | [ ] File Server Resource Manager FS-Resource-Manager Available
42 | [ ] File Server VSS Agent Service FS-VSS-Agent Available
43 | [ ] iSCSI Target Server FS-iSCSITarget-Server Available
44 | [ ] iSCSI Target Storage Provider (VDS and V... iSCSITarget-VSS-VDS Available
45 | [ ] Server for NFS FS-NFS-Service Available
46 | [ ] Work Folders FS-SyncShareService Available
47 | [X] Storage Services Storage-Services Installed
48 | [ ] Hyper-V Hyper-V Available
49 | [ ] Network Policy and Access Services NPAS Available
50 | [ ] Network Policy Server NPAS-Policy-Server Available
51 | [ ] Health Registration Authority NPAS-Health Available
52 | [ ] Host Credential Authorization Protocol NPAS-Host-Cred Available
53 | [ ] Print and Document Services Print-Services Available
54 | [ ] Print Server Print-Server Available
55 | [ ] Distributed Scan Server Print-Scan-Server Available
56 | [ ] Internet Printing Print-Internet Available
57 | [ ] LPD Service Print-LPD-Service Available
58 | [ ] Remote Access RemoteAccess Available
59 | [ ] DirectAccess and VPN (RAS) DirectAccess-VPN Available
60 | [ ] Routing Routing Available
61 | [ ] Web Application Proxy Web-Application-Proxy Available
62 | [ ] Remote Desktop Services Remote-Desktop-Services Available
63 | [ ] Remote Desktop Connection Broker RDS-Connection-Broker Available
64 | [ ] Remote Desktop Gateway RDS-Gateway Available
65 | [ ] Remote Desktop Licensing RDS-Licensing Available
66 | [ ] Remote Desktop Session Host RDS-RD-Server Available
67 | [ ] Remote Desktop Virtualization Host RDS-Virtualization Available
68 | [ ] Remote Desktop Web Access RDS-Web-Access Available
69 | [ ] Volume Activation Services VolumeActivation Available
70 | [X] Web Server (IIS) Web-Server Installed
71 | [X] Web Server Web-WebServer Installed
72 | [X] Common HTTP Features Web-Common-Http Installed
73 | [X] Default Document Web-Default-Doc Installed
74 | [ ] Directory Browsing Web-Dir-Browsing Available
75 | [ ] HTTP Errors Web-Http-Errors Available
76 | [ ] Static Content Web-Static-Content Available
77 | [ ] HTTP Redirection Web-Http-Redirect Available
78 | [ ] WebDAV Publishing Web-DAV-Publishing Available
79 | [ ] Health and Diagnostics Web-Health Available
80 | [ ] HTTP Logging Web-Http-Logging Available
81 | [ ] Custom Logging Web-Custom-Logging Available
82 | [ ] Logging Tools Web-Log-Libraries Available
83 | [ ] ODBC Logging Web-ODBC-Logging Available
84 | [ ] Request Monitor Web-Request-Monitor Available
85 | [ ] Tracing Web-Http-Tracing Available
86 | [ ] Performance Web-Performance Available
87 | [ ] Static Content Compression Web-Stat-Compression Available
88 | [ ] Dynamic Content Compression Web-Dyn-Compression Available
89 | [X] Security Web-Security Installed
90 | [X] Request Filtering Web-Filtering Installed
91 | [ ] Basic Authentication Web-Basic-Auth Available
92 | [ ] Centralized SSL Certificate Support Web-CertProvider Available
93 | [ ] Client Certificate Mapping Authentic... Web-Client-Auth Available
94 | [ ] Digest Authentication Web-Digest-Auth Available
95 | [ ] IIS Client Certificate Mapping Authe... Web-Cert-Auth Available
96 | [ ] IP and Domain Restrictions Web-IP-Security Available
97 | [ ] URL Authorization Web-Url-Auth Available
98 | [ ] Windows Authentication Web-Windows-Auth Available
99 | [X] Application Development Web-App-Dev Installed
100 | [ ] .NET Extensibility 3.5 Web-Net-Ext Available
101 | [X] .NET Extensibility 4.5 Web-Net-Ext45 Installed
102 | [ ] Application Initialization Web-AppInit Available
103 | [ ] ASP Web-ASP Available
104 | [ ] ASP.NET 3.5 Web-Asp-Net Available
105 | [X] ASP.NET 4.5 Web-Asp-Net45 Installed
106 | [ ] CGI Web-CGI Available
107 | [X] ISAPI Extensions Web-ISAPI-Ext Installed
108 | [X] ISAPI Filters Web-ISAPI-Filter Installed
109 | [ ] Server Side Includes Web-Includes Available
110 | [ ] WebSocket Protocol Web-WebSockets Available
111 | [ ] FTP Server Web-Ftp-Server Available
112 | [ ] FTP Service Web-Ftp-Service Available
113 | [ ] FTP Extensibility Web-Ftp-Ext Available
114 | [X] Management Tools Web-Mgmt-Tools Installed
115 | [X] IIS Management Console Web-Mgmt-Console Installed
116 | [X] IIS 6 Management Compatibility Web-Mgmt-Compat Installed
117 | [X] IIS 6 Metabase Compatibility Web-Metabase Installed
118 | [X] IIS 6 Management Console Web-Lgcy-Mgmt-Console Installed
119 | [X] IIS 6 Scripting Tools Web-Lgcy-Scripting Installed
120 | [X] IIS 6 WMI Compatibility Web-WMI Installed
121 | [X] IIS Management Scripts and Tools Web-Scripting-Tools Installed
122 | [X] Management Service Web-Mgmt-Service Installed
123 | [ ] Windows Deployment Services WDS Available
124 | [ ] Deployment Server WDS-Deployment Available
125 | [ ] Transport Server WDS-Transport Available
126 | [ ] Windows Server Essentials Experience ServerEssentialsRole Available
127 | [ ] Windows Server Update Services UpdateServices Available
128 | [ ] WID Database UpdateServices-WidDB Available
129 | [ ] WSUS Services UpdateServices-Services Available
130 | [ ] Database UpdateServices-DB Available
131 | [ ] .NET Framework 3.5 Features NET-Framework-Features Available
132 | [ ] .NET Framework 3.5 (includes .NET 2.0 and 3.0) NET-Framework-Core Removed
133 | [ ] HTTP Activation NET-HTTP-Activation Available
134 | [ ] Non-HTTP Activation NET-Non-HTTP-Activ Available
135 | [X] .NET Framework 4.5 Features NET-Framework-45-Fea... Installed
136 | [X] .NET Framework 4.5 NET-Framework-45-Core Installed
137 | [X] ASP.NET 4.5 NET-Framework-45-ASPNET Installed
138 | [X] WCF Services NET-WCF-Services45 Installed
139 | [ ] HTTP Activation NET-WCF-HTTP-Activat... Available
140 | [ ] Message Queuing (MSMQ) Activation NET-WCF-MSMQ-Activat... Available
141 | [ ] Named Pipe Activation NET-WCF-Pipe-Activat... Available
142 | [ ] TCP Activation NET-WCF-TCP-Activati... Available
143 | [X] TCP Port Sharing NET-WCF-TCP-PortShar... Installed
144 | [ ] Background Intelligent Transfer Service (BITS) BITS Available
145 | [ ] IIS Server Extension BITS-IIS-Ext Available
146 | [ ] Compact Server BITS-Compact-Server Available
147 | [ ] BitLocker Drive Encryption BitLocker Available
148 | [ ] BitLocker Network Unlock BitLocker-NetworkUnlock Available
149 | [ ] BranchCache BranchCache Available
150 | [ ] Client for NFS NFS-Client Available
151 | [ ] Data Center Bridging Data-Center-Bridging Available
152 | [ ] Direct Play Direct-Play Available
153 | [ ] Enhanced Storage EnhancedStorage Available
154 | [ ] Failover Clustering Failover-Clustering Available
155 | [ ] Group Policy Management GPMC Available
156 | [ ] IIS Hostable Web Core Web-WHC Available
157 | [ ] Ink and Handwriting Services InkAndHandwritingSer... Available
158 | [ ] Internet Printing Client Internet-Print-Client Available
159 | [ ] IP Address Management (IPAM) Server IPAM Available
160 | [ ] iSNS Server service ISNS Available
161 | [ ] LPR Port Monitor LPR-Port-Monitor Available
162 | [ ] Management OData IIS Extension ManagementOdata Available
163 | [ ] Media Foundation Server-Media-Foundation Available
164 | [ ] Message Queuing MSMQ Available
165 | [ ] Message Queuing Services MSMQ-Services Available
166 | [ ] Message Queuing Server MSMQ-Server Available
167 | [ ] Directory Service Integration MSMQ-Directory Available
168 | [ ] HTTP Support MSMQ-HTTP-Support Available
169 | [ ] Message Queuing Triggers MSMQ-Triggers Available
170 | [ ] Multicasting Support MSMQ-Multicasting Available
171 | [ ] Routing Service MSMQ-Routing Available
172 | [ ] Message Queuing DCOM Proxy MSMQ-DCOM Available
173 | [ ] Multipath I/O Multipath-IO Available
174 | [ ] Network Load Balancing NLB Available
175 | [ ] Peer Name Resolution Protocol PNRP Available
176 | [ ] Quality Windows Audio Video Experience qWave Available
177 | [ ] RAS Connection Manager Administration Kit (CMAK) CMAK Available
178 | [ ] Remote Assistance Remote-Assistance Available
179 | [ ] Remote Differential Compression RDC Available
180 | [ ] Remote Server Administration Tools RSAT Available
181 | [ ] Feature Administration Tools RSAT-Feature-Tools Available
182 | [ ] SMTP Server Tools RSAT-SMTP Available
183 | [ ] BitLocker Drive Encryption Administratio... RSAT-Feature-Tools-B... Available
184 | [ ] BitLocker Drive Encryption Tools RSAT-Feature-Tools-B... Available
185 | [ ] BitLocker Recovery Password Viewer RSAT-Feature-Tools-B... Available
186 | [ ] BITS Server Extensions Tools RSAT-Bits-Server Available
187 | [ ] Failover Clustering Tools RSAT-Clustering Available
188 | [ ] Failover Cluster Management Tools RSAT-Clustering-Mgmt Available
189 | [ ] Failover Cluster Module for Windows ... RSAT-Clustering-Powe... Available
190 | [ ] Failover Cluster Automation Server RSAT-Clustering-Auto... Available
191 | [ ] Failover Cluster Command Interface RSAT-Clustering-CmdI... Available
192 | [ ] IP Address Management (IPAM) Client IPAM-Client-Feature Available
193 | [ ] Network Load Balancing Tools RSAT-NLB Available
194 | [ ] SNMP Tools RSAT-SNMP Available
195 | [ ] WINS Server Tools RSAT-WINS Available
196 | [ ] Role Administration Tools RSAT-Role-Tools Available
197 | [ ] AD DS and AD LDS Tools RSAT-AD-Tools Available
198 | [ ] Active Directory module for Windows ... RSAT-AD-PowerShell Available
199 | [ ] AD DS Tools RSAT-ADDS Available
200 | [ ] Active Directory Administrative ... RSAT-AD-AdminCenter Available
201 | [ ] AD DS Snap-Ins and Command-Line ... RSAT-ADDS-Tools Available
202 | [ ] Server for NIS Tools [DEPRECATED] RSAT-NIS Available
203 | [ ] AD LDS Snap-Ins and Command-Line Tools RSAT-ADLDS Available
204 | [ ] Hyper-V Management Tools RSAT-Hyper-V-Tools Available
205 | [ ] Hyper-V GUI Management Tools Hyper-V-Tools Available
206 | [ ] Hyper-V Module for Windows PowerShell Hyper-V-PowerShell Available
207 | [ ] Remote Desktop Services Tools RSAT-RDS-Tools Available
208 | [ ] Remote Desktop Gateway Tools RSAT-RDS-Gateway Available
209 | [ ] Remote Desktop Licensing Diagnoser T... RSAT-RDS-Licensing-D... Available
210 | [ ] Remote Desktop Licensing Tools RDS-Licensing-UI Available
211 | [ ] Windows Server Update Services Tools UpdateServices-RSAT Available
212 | [ ] API and PowerShell cmdlets UpdateServices-API Available
213 | [ ] User Interface Management Console UpdateServices-UI Available
214 | [ ] Active Directory Certificate Services Tools RSAT-ADCS Available
215 | [ ] Certification Authority Management T... RSAT-ADCS-Mgmt Available
216 | [ ] Online Responder Tools RSAT-Online-Responder Available
217 | [ ] Active Directory Rights Management Servi... RSAT-ADRMS Available
218 | [ ] DHCP Server Tools RSAT-DHCP Available
219 | [ ] DNS Server Tools RSAT-DNS-Server Available
220 | [ ] Fax Server Tools RSAT-Fax Available
221 | [ ] File Services Tools RSAT-File-Services Available
222 | [ ] DFS Management Tools RSAT-DFS-Mgmt-Con Available
223 | [ ] File Server Resource Manager Tools RSAT-FSRM-Mgmt Available
224 | [ ] Services for Network File System Man... RSAT-NFS-Admin Available
225 | [ ] Share and Storage Management Tool RSAT-CoreFile-Mgmt Available
226 | [ ] Network Policy and Access Services Tools RSAT-NPAS Available
227 | [ ] Print and Document Services Tools RSAT-Print-Services Available
228 | [ ] Remote Access Management Tools RSAT-RemoteAccess Available
229 | [ ] Remote Access GUI and Command-Line T... RSAT-RemoteAccess-Mgmt Available
230 | [ ] Remote Access module for Windows Pow... RSAT-RemoteAccess-Po... Available
231 | [ ] Volume Activation Tools RSAT-VA-Tools Available
232 | [ ] Windows Deployment Services Tools WDS-AdminPack Available
233 | [ ] RPC over HTTP Proxy RPC-over-HTTP-Proxy Available
234 | [ ] Simple TCP/IP Services Simple-TCPIP Available
235 | [X] SMB 1.0/CIFS File Sharing Support FS-SMB1 Installed
236 | [ ] SMB Bandwidth Limit FS-SMBBW Available
237 | [ ] SMTP Server SMTP-Server Available
238 | [ ] SNMP Service SNMP-Service Available
239 | [ ] SNMP WMI Provider SNMP-WMI-Provider Available
240 | [ ] Telnet Client Telnet-Client Available
241 | [ ] Telnet Server Telnet-Server Available
242 | [ ] TFTP Client TFTP-Client Available
243 | [X] User Interfaces and Infrastructure User-Interfaces-Infra Installed
244 | [X] Graphical Management Tools and Infrastructure Server-Gui-Mgmt-Infra Installed
245 | [ ] Desktop Experience Desktop-Experience Available
246 | [X] Server Graphical Shell Server-Gui-Shell Installed
247 | [ ] Windows Biometric Framework Biometric-Framework Available
248 | [ ] Windows Feedback Forwarder WFF Available
249 | [ ] Windows Identity Foundation 3.5 Windows-Identity-Fou... Available
250 | [ ] Windows Internal Database Windows-Internal-Dat... Available
251 | [X] Windows PowerShell PowerShellRoot Installed
252 | [X] Windows PowerShell 4.0 PowerShell Installed
253 | [ ] Windows PowerShell 2.0 Engine PowerShell-V2 Removed
254 | [ ] Windows PowerShell Desired State Configurati... DSC-Service Available
255 | [X] Windows PowerShell ISE PowerShell-ISE Installed
256 | [ ] Windows PowerShell Web Access WindowsPowerShellWeb... Available
257 | [ ] Windows Process Activation Service WAS Available
258 | [ ] Process Model WAS-Process-Model Available
259 | [ ] .NET Environment 3.5 WAS-NET-Environment Available
260 | [ ] Configuration APIs WAS-Config-APIs Available
261 | [ ] Windows Search Service Search-Service Available
262 | [ ] Windows Server Backup Windows-Server-Backup Available
263 | [ ] Windows Server Migration Tools Migration Available
264 | [ ] Windows Standards-Based Storage Management WindowsStorageManage... Available
265 | [ ] Windows TIFF IFilter Windows-TIFF-IFilter Available
266 | [ ] WinRM IIS Extension WinRM-IIS-Ext Available
267 | [ ] WINS Server WINS Available
268 | [ ] Wireless LAN Service Wireless-Networking Available
269 | [X] WoW64 Support WoW64-Support Installed
270 | [ ] XPS Viewer XPS-Viewer Available
271 |
--------------------------------------------------------------------------------
/machines/_default.ps1:
--------------------------------------------------------------------------------
1 | #
2 | # DO NOT MODIFY THIS FILE, IT CONTAINS DEFAULT VALUES OF THE BUILD SYSTEM
3 | # INSTEAD, MODIFY DEFAULTS FROM YOUR OWN SCRIPT THAT SOURCES THIS FILE
4 | #
5 |
6 | #ISO file name without extension from ./iso folder. Mandatory.
7 | $OS_ISO_NAME = ''
8 |
9 | #ISO file SHA1 checksum. Mandatory.
10 | $OS_ISO_CHECKSUM = ''
11 |
12 | #Windows image to install, empty means serverstandard for server and enterprise for workstation.
13 | #Possible values:
14 | # Windows Server 2012 R2 SERVERSTANDARD
15 | # Windows Server 2012 R2 SERVERSTANDARDCORE
16 | # Windows Server 2012 R2 SERVERDATACENTER
17 | # Windows Server 2012 R2 SERVERDATACENTERCORE
18 | # Windows 8.1 Pro
19 | # Windows 8.1 Enterprise
20 | $OS_IMAGE = ''
21 |
22 | #Answer file file name without extension from ./answer_files folder. Mandatory.
23 | $OS_ANSWER_FILE = ''
24 |
25 | #Hash containing OS type for providers. Mandatory for best performance.
26 | $OS_TYPE = @{vmware='other'; virtualbox='other'}
27 |
28 | #Numbert of CPUs
29 | $CPU = 1
30 |
31 | #Memory size
32 | $MEMORY = 2GB
33 |
34 | #Disk size
35 | $DISK = 60GB
36 |
37 | #OpenSSH installer URL. Optional, by default empty which means that internet location is used.
38 | $INSTALL_OPENSSH_URL = ''
39 |
40 | # Proxy server for the administrative user. Optional.
41 | $PROXY_SERVER = ''
42 |
43 | # Proxy exclusions for the administrative user. Optional.
44 | $PROXY_OVERRIDE = ''
45 |
46 | # Enable/disable windows update build feature. Optional, on by default.
47 | $WINDOWS_UPDATE = $true
48 |
49 | # Array of KB numbers for deterministic updates. Optional, empty by default.
50 | $WINDOWS_UPDATE_KB_LIST = @()
51 |
52 | # Array of update categories for non-deterministic updates. Optional, use all categories by default.
53 | $WINDOWS_UPDATE_CATEGORIES_LIST = @()
54 |
55 | # Enable/disable windows features installation. Optional, on by default.
56 | $WINDOWS_FEATURE = $true
57 |
58 | # Array of feature names obtained by Get-WindowsFeature (server) or get-WindowsOptionalFeature (workstation)
59 | $WINDOWS_FEATURE_LIST = @()
60 |
61 | # Remove all unused features from the disk
62 | $WINDOWS_FEATURE_PURGE = $false
63 |
64 | # Enable/disable small Windows tweaks. Optional, on by default.
65 | $WINDOWS_TWEAKS = $true
66 |
67 | # Scriptblock to define tweaks. See ./scripts/windows-tweaks.ps1 for details. Optional, does nothing by default.
68 | $WINDOWS_TWEAKS_SCRIPT = [scriptblock]{}
69 |
70 | # Enable/disable Powershell provision. Optional, on by default.
71 | $PROVISION = $true
72 |
73 | # Array of scriptblocks to run. Optional, does nothing by default.
74 | $PROVISION_LIST = @()
75 |
76 | # Enable/disable finalization script
77 | $FINALIZE = $true
78 |
79 | # Vagrant metadata Description property, visible in .json file of the output. Optional, empty by default.
80 | $BOX_DESCRIPTION = ''
81 |
82 | # Vagrant metadata Version property visible in .json file of the output. Optional, 0 by default.
83 | $BOX_VERSION = 0
84 |
85 | # Used to craft Vagrant metadata BOX_URL property: BOX_URL = "$BOX_STORE/${Machine}-virtualbox.box". Mandatory.
86 | $BOX_STORE = ''
87 |
88 | # Array of scriptblocks to be executed on host when build starts. Optional, does nothing by default.
89 | # All scriptblocks in the list receive one argument, passed to build script as 'Data' parameter.
90 | # If the last object the scriptblock returns is of type Boolean and is false, the build terminates.
91 | $BUILD_START_LIST = @()
92 |
93 | # Array of scriptblocks to be executed on host when build ends, even with error. Optional, does nothing by default.
94 | $BUILD_END_LIST = @()
95 |
--------------------------------------------------------------------------------
/machines/eval-base-server.ps1:
--------------------------------------------------------------------------------
1 | . "$PSScriptRoot/_default.ps1"
2 |
3 | # http://download.microsoft.com/download/6/2/A/62A76ABB-9990-4EFC-A4FE-C7D698DAEB96/9600.16384.WINBLUE_RTM.130821-1623_X64FRE_SERVER_EVAL_EN-US-IRM_SSS_X64FREE_EN-US_DV5.ISO
4 | $OS_ISO_NAME = '9600.16384.WINBLUE_RTM.130821-1623_X64FRE_SERVER_EVAL_EN-US-IRM_SSS_X64FREE_EN-US_DV5'
5 | $OS_ISO_CHECKSUM = '7e3f89dbff163e259ca9b0d1f078daafd2fed513'
6 | $OS_TYPE = @{vmWare = 'windows8srv-64'; virtualbox = 'Windows2012_64'}
7 | $OS_ANSWER_FILE = '2012_r2'
8 |
9 |
10 | $WINDOWS_UPDATE = $true
11 | #$WINDOWS_UPDATE_CATEGORIES_LIST += 'CriticalUpdates', 'SecurityUpdates'
12 | $WINDOWS_UPDATE_KB_LIST += 'KB2939087'
13 |
14 | $WINDOWS_TWEAKS = $true
15 | $WINDOWS_TWEAKS_SCRIPT = {
16 | Explorer-Feature -ShowHidden -ShowSupperHidden -ShowFullPath -ShowFileExtensions -ShowRun -ShowAdminTools -PSOpenHere
17 | CLI-Feature -EnableQuickEdit
18 | System-Feature -NoUAC -NoHibernation -NoShutDownTracker -NoAutoUpdate
19 | }
20 |
21 |
22 |
--------------------------------------------------------------------------------
/scripts/Get-WUInstall.ps1:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/majkinetor/posher/c38bd3b1ecb275dcd37e8a4904ad066917c476d2/scripts/Get-WUInstall.ps1
--------------------------------------------------------------------------------
/scripts/Install-GuestAdditions.ps1:
--------------------------------------------------------------------------------
1 | param(
2 | [string]$User="vagrant",
3 |
4 | [ValidateSet('vmWare', 'VirtualBox')]
5 | [string]$Type
6 | )
7 |
8 | if (!$Type) {
9 | $Type = $Env:PACKER_BUILDER_TYPE -replace '-iso', ''
10 | }
11 |
12 | "==> Installing Guest Additions for $Type"
13 |
14 | switch($Type) {
15 | 'vmWare' {$image = "C:\Users\${User}\windows.iso"}
16 | 'VirtualBox' {$image = "C:\Users\${User}\VBoxGuestAdditions.iso"}
17 | }
18 |
19 | "Using: $image"
20 | if (!(Test-Path $image)) { throw "ERROR: Can't find guest additions: $image" }
21 |
22 | $iso = Mount-DiskImage $image -PassThru
23 | pushd "$((Get-Volume -DiskImage $iso).DriveLetter):"
24 | ls
25 |
26 | switch($Type) {
27 | 'vmWare' {
28 | start -Wait ./setup.exe -ArgumentList '/S /v "/qn REBOOT=R ADDLOCAL=ALL"' #http://goo.gl/TOZJYT
29 |
30 | if (!(gsv VMTools -ea ignore)) { throw "ERROR: Installation failed - service not running" }
31 | }
32 | 'VirtualBox' {
33 |
34 | # To prevent user intervention popups which will undermine a silent installation.
35 | "Setting Oracle certificate"
36 | $cert = "A:\oracle-cert.cer"
37 | if (!(Test-Path $cert)) { throw "ERROR: Can't find Oracle certificate"; }
38 | certutil.exe -addstore -f "TrustedPublisher" $cert
39 |
40 | start -Wait ./VBoxWindowsAdditions.exe -ArgumentList '/S'
41 | if (!(Test-Path 'C:\Program Files\Oracle\VirtualBox Guest Additions')) { throw "ERROR: Installation failed" }
42 | }
43 | }
44 |
45 | popd
46 | Dismount-DiskImage $image
47 | rm $image
48 | "Guest Additions installed"
49 |
--------------------------------------------------------------------------------
/scripts/Install-OpenSSH.ps1:
--------------------------------------------------------------------------------
1 | #TODO:
2 | # Fix SSH admin pass in script
3 | # Replace netsh calls with powershell firewall
4 |
5 | param(
6 | [string]$URL = $null,
7 | [switch]$AutoStart
8 | )
9 |
10 | "==> Install OpenSSH"
11 |
12 | $ssh_admin_pass = "D@rj33l1ng"
13 | $ssh_user = "vagrant"
14 | $ssh_root = "C:\Program Files\OpenSSH"
15 |
16 | #==============================================================================
17 |
18 | if (!$URL) { $URL = "http://www.mls-software.com/files/setupssh-6.7p1-2.exe" }
19 |
20 | $is_64bit = [IntPtr]::size -eq 8
21 | $passwd = "$ssh_root\etc\passwd"
22 | $temp = "C:\Windows\Temp"
23 | $exeName = Split-Path $URL -Leaf
24 |
25 | "Installing OpenSSH using installer: $exeName"
26 | "Autostart set to $AutoStart"
27 |
28 | if (!(Test-Path "$ssh_root\bin\ssh.exe"))
29 | {
30 |
31 | "Downloading from: $URL"
32 |
33 | $wc = new-object system.net.WebClient
34 | if ($Env:http_proxy) {
35 | $wc.proxy = [System.Net.WebRequest]::DefaultWebProxy
36 | "Proxy enabled, override is {0}" -f ($wc.proxy.GetProxy($URL).AbsoluteUri -ne "${Env:http_proxy}/")
37 | }
38 | $wc.DownloadFile($URL, "$temp\openssh.exe")
39 | if (!(Test-Path "$temp\openssh.exe")) { "ERROR: Can't download OpenSSH"; exit 1}
40 | "Download finished"
41 |
42 | Start-Process "$temp\openssh.exe" "/S /port=22 /privsep=1 /password=$ssh_admin_pass" -NoNewWindow -Wait
43 | }
44 |
45 |
46 | Stop-Service "OpenSSHd" -Force
47 |
48 | "Setting $ssh_user user file permissions"
49 | mkdir -force "C:\Users\$ssh_user\.ssh"
50 |
51 | # set permissions
52 | icacls.exe "C:\Users\${ssh_user}" /grant "${ssh_user}:(OI)(CI)F"
53 | icacls.exe "$ssh_root\bin" /grant "${ssh_user}:(OI)RX"
54 | icacls.exe "$ssh_root\usr\sbin" /grant "${ssh_user}:(OI)RX"
55 |
56 | "Setting SSH home directories"
57 | (gc $passwd) | % { $_ -replace '/home/(\w+)', '/cygdrive/c/Users/$1' } | sc $passwd
58 |
59 | # Set shell to /bin/sh to return exit status
60 | (gc $passwd) | % {$_ -replace '/bin/bash', '/bin/sh' } | sc $passwd
61 |
62 | # fix opensshd to not be strict
63 | "Setting OpenSSH to be non-strict"
64 | (gc "$ssh_root\etc\sshd_config") | % {
65 | $_ -replace 'StrictModes yes', 'StrictModes no' `
66 | -replace '#PubkeyAuthentication yes', 'PubkeyAuthentication yes' `
67 | -replace '#PermitUserEnvironment no', 'PermitUserEnvironment yes' `
68 | -replace '#UseDNS yes', 'UseDNS no' `
69 | -replace 'Banner /etc/banner.txt', '#Banner /etc/banner.txt'
70 | } | sc "$ssh_root\etc\sshd_config"
71 |
72 | # use c:\Windows\Temp as /tmp location
73 | "Setting temp directory location"
74 | rm -Force -ErrorAction SilentlyContinue "$ssh_root\tmp"
75 | start "$ssh_root\bin\junction.exe" "/accepteula '$ssh_root\tmp' '$temp'"
76 | icacls.exe "$temp" /grant "${ssh_user}:(OI)(CI)F"
77 |
78 | "Setting up SSH environment"
79 | $sshenv = "TEMP=$temp"
80 | if ($is_64bit) {
81 | # add 64 bit environment variables missing from SSH
82 | $env_vars = "ProgramFiles(x86)=C:\Program Files (x86)", `
83 | "ProgramW6432=C:\Program Files", `
84 | "CommonProgramFiles(x86)=C:\Program Files (x86)\Common Files", `
85 | "CommonProgramW6432=C:\Program Files\Common Files"
86 | $sshenv = $sshenv + "`r`n" + ($env_vars -join "`r`n")
87 | }
88 | sc "C:\Users\$ssh_user\.ssh\environment" $sshenv
89 |
90 | # configure firewall
91 | Write-Host "Configuring firewall"
92 | netsh advfirewall firewall add rule name="SSHD" dir=in action=allow service=OpenSSHd enable=yes
93 | netsh advfirewall firewall add rule name="SSHD" dir=in action=allow program="$ssh_root\usr\sbin\sshd.exe" enable=yes
94 | netsh advfirewall firewall add rule name="ssh" dir=in action=allow protocol=TCP localport=22
95 |
96 | if ($AutoStart) { Start-Service "OpenSSHd" }
97 |
--------------------------------------------------------------------------------
/scripts/Set-PinnedApplication.ps1:
--------------------------------------------------------------------------------
1 | # Author: Miodrag Milic
2 | # Last Change: 03-Mar-2015.
3 | # Adapted from: http://goo.gl/xvHcSE
4 |
5 | #requires -version 1.0
6 |
7 | <#
8 | .SYNOPSIS
9 | This function are used to pin and unpin programs from the taskbar and Start-menu.
10 |
11 | .EXAMPLE
12 | Set-PinnedApplication -Action PinToTaskbar -FilePath "C:\WINDOWS\system32\notepad.exe"
13 |
14 | .EXAMPLE
15 | gcm notepad,explorer | Set-PinnedApplication -Action PinToTaskbar -Verbose
16 |
17 | .NOTES
18 | Tested on platforms: Windows 7, Windows Server 2008 R2, Windows 8.1, Windows 10
19 | #>
20 | function Set-PinnedApplication
21 | {
22 | [CmdletBinding()]
23 | param(
24 | # Action to take: PinToTaskbar (default), PinToStartMenu, UnPinFromTaskbar, UnPinFromStartMenu
25 | [ValidateSet('PinToTaskbar', 'PinToStartMenu', 'UnPinFromTaskbar', 'UnPinFromStartMenu')]
26 | [string]$Action='PinToTaskbar',
27 |
28 | # Path to executable for the action
29 | [Parameter(Mandatory=$true, ValueFromPipeline=$true, ValueFrompiPelinebyPropertyName=$true)]
30 | [Alias('Path')]
31 | [string[]]$FilePath
32 | )
33 |
34 | begin
35 | {
36 | function InvokeVerb ([string]$FilePath, $verb)
37 | {
38 | $verb = $verb.Replace("&","")
39 | $path = split-path $FilePath
40 | $shell = new-object -com "Shell.Application"
41 | $folder = $shell.Namespace($path)
42 | $item = $folder.Parsename((split-path $FilePath -leaf))
43 | $itemVerb = $item.Verbs() | ? {$_.Name.Replace("&","") -eq $verb}
44 | if($itemVerb -eq $null){ throw "Verb $verb not found." } else { $itemVerb.DoIt() }
45 | }
46 |
47 | function GetVerb ($verbId)
48 | {
49 | try {
50 | $t = [type]"CosmosKey.Util.MuiHelper"
51 | } catch {
52 | $def = @"
53 |
54 | [DllImport("user32.dll")]
55 | public static extern int LoadString(IntPtr h,uint id, System.Text.StringBuilder sb,int maxBuffer);
56 |
57 | [DllImport("kernel32.dll")]
58 | public static extern IntPtr LoadLibrary(string s);
59 | "@
60 | Add-Type -MemberDefinition $def -name MuiHelper -namespace CosmosKey.Util
61 | }
62 | if($global:CosmosKey_Utils_MuiHelper_Shell32 -eq $null){
63 | $global:CosmosKey_Utils_MuiHelper_Shell32 = [CosmosKey.Util.MuiHelper]::LoadLibrary("shell32.dll")
64 | }
65 |
66 | $maxVerbLength = 255
67 | $verbBuilder = new-object Text.StringBuilder "",$maxVerbLength
68 | [void][CosmosKey.Util.MuiHelper]::LoadString($CosmosKey_Utils_MuiHelper_Shell32, $verbId, $verbBuilder, $maxVerbLength)
69 | return $verbBuilder.ToString()
70 | }
71 |
72 | $verbs = @{
73 | "PintoStartMenu" = 5381
74 | "UnpinfromStartMenu" = 5382
75 | "PintoTaskbar" = 5386
76 | "UnpinfromTaskbar" = 5387
77 | }
78 | }
79 | process {
80 | $FilePath | % {
81 | if (!(Test-Path $_)) {Write-Verbose "Path doesn't exist: $_"; return}
82 | Write-Verbose "$Action for $_"
83 | InvokeVerb -FilePath $_ -Verb $(GetVerb -VerbId $verbs.$action)
84 | }
85 | }
86 | }
87 |
--------------------------------------------------------------------------------
/scripts/Set-PoshAsDefault.ps1:
--------------------------------------------------------------------------------
1 | # On Windows Core cmd.exe is default shell :S. Change it to Powershell.
2 |
3 | $definition = @"
4 | using System;
5 | using System.Runtime.InteropServices;
6 | namespace Win32Api
7 | {
8 | public class NtDll
9 | {
10 | [DllImport("ntdll.dll", EntryPoint="RtlAdjustPrivilege")]
11 | public static extern int RtlAdjustPrivilege(ulong Privilege, bool Enable, bool CurrentThread, ref bool Enabled);
12 | }
13 | }
14 | "@
15 | Add-Type -TypeDefinition $definition -PassThru
16 | $bEnabled = $false
17 |
18 | # Enable SeTakeOwnershipPrivilege
19 | $res = [Win32Api.NtDll]::RtlAdjustPrivilege(9, $true, $false, [ref]$bEnabled)
20 |
21 | # Take ownership of the registry key
22 | $key = [Microsoft.Win32.Registry]::LocalMachine.OpenSubKey('SOFTWARE\Microsoft\Windows NT\CurrentVersion\Winlogon\AlternateShells', [Microsoft.Win32.RegistryKeyPermissionCheck]::ReadWriteSubTree,[System.Security.AccessControl.RegistryRights]::takeownership)
23 | $acl = $key.GetAccessControl()
24 | $acl.SetOwner([System.Security.Principal.NTAccount]"Administrators")
25 |
26 | # Set Full Control for Administrators
27 | $rule = New-Object System.Security.AccessControl.RegistryAccessRule("Administrators","FullControl", "Allow")
28 | $acl.AddAccessRule($rule)
29 | [void]$key.SetAccessControl($acl)
30 |
31 | # Create Registry Value
32 | [void][Microsoft.Win32.Registry]::SetValue($key, "90000", 'powershell.exe -noexit -command "& {set-location $env:userprofile; clear-host}"')
33 |
--------------------------------------------------------------------------------
/scripts/Set-VagrantUser.ps1:
--------------------------------------------------------------------------------
1 | "==> Set Vagrant User"
2 |
3 | "Install vagrant public key"
4 |
5 | if (Test-Path "A:\vagrant.pub")
6 | {
7 | "Using A:\vagrant.pub"
8 | mkdir "c:\Users\vagrant\.ssh" -ea ignore
9 | cp "A:\vagrant.pub" "C:\Users\vagrant\.ssh\authorized_keys"
10 | }
11 | else {
12 | "Downloading vagrant.pub from github"
13 | $wc = new-object system.net.WebClient
14 | if ($Env:http_proxy) {
15 | $wc.proxy = [System.Net.WebRequest]::DefaultWebProxy
16 | "Proxy enabled, override is {0}" -f ($wc.proxy.GetProxy($URL).AbsoluteUri -ne "${Env:http_proxy}/")
17 | }
18 | $wc.DownloadFile('https://raw.githubusercontent.com/mitchellh/vagrant/master/keys/vagrant.pub', 'C:\Users\vagrant\.ssh\authorized_keys')
19 | if (!(Test-Path 'C:\Users\vagrant\.ssh\authorized_keys')) { "ERROR: Downloading public key failed"; exit 1 }
20 | }
21 |
22 | "Vagrant public key installed"
23 |
24 | "Disable password expiration for user vagrant"
25 | Get-WmiObject -Class Win32_UserAccount -Filter "name = 'vagrant'" | Set-WmiInstance -Argument @{PasswordExpires = 0} | Select Name, PasswordExpires
26 |
--------------------------------------------------------------------------------
/scripts/_provision.ps1:
--------------------------------------------------------------------------------
1 | "`n==| Powershell provision"
2 | # Packer vars:
3 | # $Env:PACKER_BUILDER_TYPE
4 | # $Env:PACKER_BUILDER_NAME
5 |
6 | $ErrorActionPreference = "Stop"
7 | trap { "!!! ERROR !!!"; $_; exit 1 }
8 |
9 | function i( $Option, [scriptblock] $Action) {
10 | $out = { $b = '-' * ($msg.Length+1); ". $b"; "==| $msg"; ". $b" }
11 | $var = Get-Variable $Option -ea ignore
12 | if ($var.Value) {
13 | $msg = "INSTALLING '$Option'"; & $out
14 | icm -ScriptBlock $Action
15 | } else { $msg = "OPTION '$Option' IS DISABLED!"; & $out }
16 | }
17 |
18 | cd c:\scripts; ls
19 |
20 | if (!(Test-Path ./__machine.ps1)) { throw "Machine variables are not present" }
21 | . ./__machine.ps1
22 |
23 | cat c:/packer.log; rm c:/packer.log
24 | ./Install-GuestAdditions.ps1
25 |
26 | #====================================
27 |
28 | i 'WINDOWS_FEATURE' { ./windows-features.ps1 $WINDOWS_FEATURE_LIST }
29 | i 'WINDOWS_TWEAKS' { ./windows-tweaks.ps1 $WINDOWS_TWEAKS_SCRIPT }
30 |
31 | i 'PROVISION' {
32 | if (!$PROVISION_LIST.Length) { "Nothing to provision, list is empty"; return; }
33 | else { "List contains $($PROVISION_LIST.Length) provisioners`n" }
34 |
35 | $PROVISION_LIST | % {$i=0} {
36 | "Executing provisioner {0}" -f $i++
37 | & $_
38 | }
39 | }
40 |
41 | i 'WINDOWS_UPDATE' { ./windows-update.ps1 $WINDOWS_UPDATE_CATEGORIES_LIST $WINDOWS_UPDATE_KB_LIST}
42 |
43 | $waitfile = 'c:\scripts\__waitfile'
44 | if ( Test-Path $waitfile ) {
45 | "Installation is over. Kill notepad to continue: ps notepad | kill"
46 | start -Wait notepad.exe
47 | }
48 |
49 | i 'FINALIZE' { ./finalize.ps1 }
50 |
51 | "==| Powershell provision finished"
52 |
--------------------------------------------------------------------------------
/scripts/_setup.ps1:
--------------------------------------------------------------------------------
1 | "`n==| Powershell Windows setup started at $(get-date)`n"
2 |
3 | $ErrorActionPreference = "Stop"
4 | trap { "!!! ERROR !!!"; $_; exit 1 }
5 |
6 | "==| Setting x64 && x32 powershell execution policy"
7 | Set-ExecutionPolicy -ExecutionPolicy Bypass -Force
8 | C:\Windows\SysWOW64\cmd.exe /c powershell -Command "Set-ExecutionPolicy -ExecutionPolicy Bypass -Force"
9 |
10 | cd A:; ls
11 |
12 | if (!(Test-Path ./__machine.ps1)) { throw "Machine variables are not present" }
13 | . ./__machine.ps1
14 |
15 | ./Set-Proxy.ps1 $PROXY_SERVER $PROXY_OVERRIDE
16 | ./Enable-RDP.ps1
17 | ./Enable-WinRM.ps1
18 |
19 | ./Set-VagrantUser.ps1
20 | ./Install-OpenSSH.ps1 -AutoStart -URL $INSTALL_OPENSSH_URL
21 |
22 | "`n==| Powershell Windows setup completed at $(get-date)"
23 |
--------------------------------------------------------------------------------
/scripts/enable-rdp.ps1:
--------------------------------------------------------------------------------
1 | "==| Enable RDP"
2 |
3 | Set-ItemProperty -Path 'HKLM:\System\CurrentControlSet\Control\Terminal Server\WinStations\RDP-Tcp' -name "UserAuthentication" -Value 0
4 | Set-ItemProperty -Path 'HKLM:\System\CurrentControlSet\Control\Terminal Server'-name "fDenyTSConnections" -Value 0
5 |
6 | Enable-NetFirewallRule -DisplayGroup "Remote Desktop"
7 | Get-NetFirewallRule -DisplayGroup "Remote Desktop*" | Select DisplayName, Enabled | ft -Autosize
8 |
--------------------------------------------------------------------------------
/scripts/enable-winrm.ps1:
--------------------------------------------------------------------------------
1 | "==| Enable and set WinRM"
2 |
3 | # For Vagrant see "Base Windows Machine" at https://docs.vagrantup.com/v2/boxes/base.html
4 |
5 | ## https://technet.microsoft.com/en-us/library/hh849694.aspx
6 | Enable-PSRemoting -Force #-SkipNetworkProfileCheck
7 |
8 | ## https://technet.microsoft.com/en-us/library/hh849872.aspx
9 | Enable-WSManCredSSP -Force -Role server
10 | Enable-WSManCredSSP -Force -Role client -DelegateComputer *
11 |
12 | # http://blogs.technet.com/b/heyscriptingguy/archive/2013/07/30/learn-how-to-configure-powershell-memory.aspx
13 | # https://technet.microsoft.com/en-us/library/hh847813.aspx
14 |
15 | Set-Item WSMan:\localhost\MaxTimeoutms 1800000 -force
16 | Set-Item WSMan:\localhost\Service\AllowUnencrypted $true -force
17 | Set-Item WSMan:\localhost\Service\Auth\Basic $true -force
18 | Set-Item WSMan:\localhost\Client\Auth\Basic $true -force
19 | Set-Item WSMan:\localhost\Listener\*\Port 5985 -force
20 |
21 |
22 | Get-Item -Path @(
23 | 'WSMan:\localhost\MaxTimeoutms'
24 | 'WSMan:\localhost\Service\AllowUnencrypted'
25 | 'WSMan:\localhost\Service\Auth\Basic'
26 | 'WSMan:\localhost\Client\Auth\Basic'
27 | 'WSMan:\localhost\Listener\*\Port'
28 | 'WSMan:\localhost\Shell\MaxMemoryPerShellMB'
29 | 'WSMan:\localhost\Plugin\Microsoft.PowerShell\Quotas\MaxMemoryPerShellMB'
30 | ) | select PSPath, Value | ft -Wrap -Autosize
31 |
32 | Test-WSMan
33 |
34 | #http://www.hurryupandwait.io/blog/in-search-of-a-light-weight-windows-vagrant-box
35 | #Set-NetFirewallRule -Name WINRM-HTTP-In-TCP-PUBLIC -RemoteAddress Any
36 |
37 | #Set-Item WSMAN:\localhost\client\auth\CredSSP $true -force
38 | #set-item wsman:localhost\client\trustedhosts "*" -force
39 |
40 | #Import-Module NetSecurity
41 | #New-NetFirewallRule -Direction Inbound -Protocol TCP -LocalPort 5985 -Action Allow -Name "WinRM-In" -DisplayName "WinRM-In" -Group "Windows Remote Management" -Description "Allow inbound tcp port 5985"
42 | #Get-NetFirewallRule -DisplayGroup "Remote Desktop"
43 | #Enable-NetFirewallRule -DisplayGroup "Remote Desktop"
44 |
45 | #netsh advfirewall firewall set rule group="remote administration" new enable=yes
46 | #if ($LastExitCode) { "ERROR: advfirewall set rule group 'remote administration'" }
47 |
48 | #netsh advfirewall firewall add rule name="winrm" dir=in action=allow protocol=TCP localport=5985
49 | #if ($LastExitCode) { "ERROR: advfirewall add rule name " }
50 |
--------------------------------------------------------------------------------
/scripts/finalize.ps1:
--------------------------------------------------------------------------------
1 | "`n`nFINALIZING SETUP`n`n"
2 |
3 | "Removing temporary files"
4 | rm $Env:Windir/TEMP/*,$Env:TMP/* -force -r -ea ignore
5 |
6 | #TODO: Mora windows restart
7 | #"Cleaning Windows updates artifacts"
8 | #dism.exe /online /Cleanup-Image /StartComponentCleanup /ResetBase
9 | #if ($LastExitCode) { restart_run { dism } }
10 |
11 | "Defragmenting drive C:"
12 | Optimize-Volume -DriveLetter C
13 |
14 | "Purge unallocated disk data"
15 | ./sdelete.exe /accepteula -z c:
16 |
--------------------------------------------------------------------------------
/scripts/oracle-cert.cer:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/majkinetor/posher/c38bd3b1ecb275dcd37e8a4904ad066917c476d2/scripts/oracle-cert.cer
--------------------------------------------------------------------------------
/scripts/proxy-module.psm1:
--------------------------------------------------------------------------------
1 | # Author: Miodrag Milic
2 | # Last Change: 2015-02-26.
3 |
4 | #requires -version 1.0
5 |
6 | <#
7 | .SYNOPSIS
8 | Get or set system proxy properties.
9 |
10 | .DESCRIPTION
11 | This function implements unified method to set proxy system wide settings.
12 | It sets both WinINET ("Internet Options" proxy) and WinHTTP proxy.
13 | Without any arguments function will return the current proxy properties.
14 | To change a proxy property pass adequate argument to the function.
15 |
16 | .EXAMPLE
17 | Update-Proxy -Server "myproxy.mydomain.com:8080" -Override "" -ShowGUI
18 |
19 | Set proxy server, clear overrides and show IE GUI.
20 |
21 | .EXAMPLE
22 | Update-Proxy | Export-CSV proxy; Import-CSV proxy | Update-Proxy -Verbose
23 |
24 | Save and reload proxy properties
25 |
26 | .NOTES
27 | The format of the parameters is the same as seen in Internet Options GUI.
28 | To bypass proxy for a local network specify keyword ";" at the end
29 | of the ProxyOveride values. Setting the proxy requires administrative prvilegies.
30 |
31 | .OUTPUTS
32 | [HashTable]
33 | #>
34 | function Update-Proxy() {
35 | [CmdletBinding()]
36 | param(
37 | # Proxy:Port
38 | [Parameter(ValueFromPipeline=$true, ValueFromPipelineByPropertyName=$true)]
39 | [string] $Server,
40 | # Semicollon delimited list of exlusions
41 | [Parameter(ValueFromPipelineByPropertyName=$true)]
42 | [string] $Override,
43 | # 0 to disable, anything else to enable proxy
44 | [Parameter(ValueFromPipelineByPropertyName=$true)]
45 | [string] $Enable,
46 | # Show Internet Options GUI
47 | [switch] $ShowGUI
48 | )
49 | $key = "HKCU:\Software\Microsoft\Windows\CurrentVersion\Internet Settings"
50 | $r = gp $key
51 | Write-Verbose "Reading proxy data from the registry"
52 | $proxy=@{
53 | Server = if ($PSBoundParameters.Keys -contains 'Server') {$Server} else { $r.ProxyServer }
54 | Override = if ($PSBoundParameters.Keys -contains 'Override') {$Override} else { $r.ProxyOverride }
55 | Enable = if ($PSBoundParameters.Keys -contains 'Enable') {$Enable} else { $r.ProxyEnable }
56 | }
57 |
58 | $set = "Server","Override","Enable" | ? {$PSBoundParameters.Keys -contains $_ }
59 | if ($set) {
60 | if (!(test-admin)) { throw "Setting proxy requires admin privileges" }
61 |
62 | Write-Verbose "Saving proxy data to registry"
63 |
64 | sp $key ProxyServer $proxy.Server
65 | sp $key ProxyOverride $proxy.Override
66 | sp $key ProxyEnable $proxy.Enable
67 | if (!(refresh-system)) { Write-Warning "Can not force system refresh after proxy change" }
68 |
69 | Write-Verbose "Importing winhttp proxy from IE settings"
70 | $OFS = "`n"
71 | [string]$res = netsh.exe winhttp import proxy source=ie
72 | Write-Verbose $res.Trim()
73 | }
74 |
75 | new-object PSCustomObject -Property $proxy
76 | if ($ShowGUI) { start control "inetcpl.cpl,,4" }
77 | }
78 |
79 | <#
80 | .SYNOPSIS
81 | Show or Update proxy environment variables from the system proxy settings.
82 | .DESCRIPTION
83 | The function updates Linux like HTTP_PROXY and related environment variables with the current system proxy settings.
84 | Without any parameters it will show current values.
85 | .OUTPUTS
86 | Returns string that is convenient to use as Powershell variable definition so that you can export the result of the
87 | function to be used elsewere: Update-CLIProxy | out-file proxy_vars.ps1
88 | .NOTES
89 | Linux doesn't support setting globs (*) for NO_PROXY variable like Windows. If the same exclusions should work both with Windows
90 | and Linux tools, simply mix definitions and each tool will understand what it can. Additionally, delimiter for proxy
91 | exclusions on Windows is `;` and on Linux `,` which this function automatically handles. Keep this in mind in case you need
92 | to load Windows proxy settings from NO_PROXY variable previously created with this function.
93 | If the system proxy is disabled, the function will clear all variables just the same as with parameter Clear.
94 | For more info see http://goo.gl/ZUD2tC.
95 | #>
96 | function Update-CLIProxy()
97 | {
98 | [CmdletBinding()]
99 | param (
100 | # Register enviornment variables in the system. Without this flag environment variables are local only.
101 | # Requires administrative rights. Must be used with Clear or FromSystem parameters.
102 | [switch] $Register,
103 | # Create environment variables from the system settings. If the system proxy properties are populated but
104 | # the proxy is disabled, this option will clear environment variables.
105 | [switch] $FromSystem,
106 | # Clear the environment variables for the current shell. Combine with the Register parameter, to unregister
107 | # envronment variables from the system.
108 | [switch] $Clear
109 | )
110 |
111 | if ($Register) {
112 | if (!(test-admin)) { throw "Setting system environment requires admin privileges" }
113 | else { Write-Verbose "Remembering changes in the system environment" }
114 | }
115 |
116 | $proxy_vars = "http_proxy", "https_proxy", "ftp_proxy"
117 |
118 | if ($FromSystem -and !$Clear) {
119 | Write-Verbose "Setting proxy environment variables."
120 |
121 | $proxy = Update-Proxy
122 | if ($proxy.ProxyEnable -eq 0) { $Clear = $true }
123 |
124 | if (!$Clear) {
125 | if ($proxy.Server) { $Env:http_proxy = "http://" + $proxy.Server }
126 | $proxy_vars | % {
127 | Set-Item Env:$_ $Env:http_proxy
128 | if ($Register) { [Environment]::SetEnvironmentVariable($_, $Env:http_proxy, "Machine") }
129 | }
130 |
131 | $Env:no_proxy = $proxy.Override.Replace(";",",") # linux format
132 | if ($Register) { [Environment]::SetEnvironmentVariable("no_proxy", $Env:no_proxy, "Machine") }
133 | }
134 | }
135 |
136 | if ($Clear) {
137 | Write-Verbose "Clearing proxy environment variables"
138 | $proxy_vars + "no_proxy" | % {
139 | Set-Item Env:$_ $null
140 | if ($Register) { [Environment]::SetEnvironmentVariable($_, $null, "Machine") }
141 | }
142 | }
143 |
144 | $env = @("Env:no_proxy")
145 | $proxy_vars | % { $env += "Env:$_" }
146 |
147 | $env | sort | % { "`${0,-15:0} = '{1}'" -f $_, (gi "$_" -ea SilentlyContinue).Value }
148 | }
149 |
150 | function test-admin() {
151 | $usercontext = [Security.Principal.WindowsPrincipal][Security.Principal.WindowsIdentity]::GetCurrent()
152 | $usercontext.IsInRole([Security.Principal.WindowsBuiltInRole] "Administrator")
153 | }
154 |
155 |
156 | # The registry changes aren't seen until system is notified about it.
157 | # Without this function you need to open Internet Settings window for changes to take effect. See http://goo.gl/OIQ4W4
158 | function refresh-system() {
159 | $signature = @'
160 | [DllImport("wininet.dll", SetLastError = true, CharSet=CharSet.Auto)]
161 | public static extern bool InternetSetOption(IntPtr hInternet, int dwOption, IntPtr lpBuffer, int dwBufferLength);
162 | '@
163 |
164 | $INTERNET_OPTION_SETTINGS_CHANGED = 39
165 | $INTERNET_OPTION_REFRESH = 37
166 | $type = Add-Type -MemberDefinition $signature -Name wininet -Namespace pinvoke -PassThru
167 | $a = $type::InternetSetOption(0, $INTERNET_OPTION_SETTINGS_CHANGED, 0, 0)
168 | $b = $type::InternetSetOption(0, $INTERNET_OPTION_REFRESH, 0, 0)
169 | return $a -and $b
170 | }
171 |
172 | Set-Alias proxy Update-Proxy
173 | Set-Alias proxyc Update-CLIProxy
174 | Export-ModuleMember -Function Update-Proxy, Update-CLIProxy -Alias *
175 |
--------------------------------------------------------------------------------
/scripts/sdelete.exe:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/majkinetor/posher/c38bd3b1ecb275dcd37e8a4904ad066917c476d2/scripts/sdelete.exe
--------------------------------------------------------------------------------
/scripts/set-proxy.ps1:
--------------------------------------------------------------------------------
1 | param ( $ProxyServer, $ProxyOverride )
2 |
3 | "==| Setting proxy"
4 |
5 | if (!$ProxyServer) { "No proxy server defined"; return; }
6 |
7 | # Packer bug
8 | if (Test-Path ./proxy.psm) { mv ./proxy.psm ./proxy.psm1 }
9 | Import-Module ./proxy-module.psm1
10 |
11 | proxy -Server $ProxyServer -Override $ProxyOverride -Enable 1
12 | proxyc -FromSystem -Register
13 |
--------------------------------------------------------------------------------
/scripts/vagrant.pub:
--------------------------------------------------------------------------------
1 | ssh-rsa AAAAB3NzaC1yc2EAAAABIwAAAQEA6NF8iallvQVp22WDkTkyrtvp9eWW6A8YVr+kz4TjGYe7gHzIw+niNltGEFHzD8+v1I2YJ6oXevct1YeS0o9HZyN1Q9qgCgzUFtdOKLv6IedplqoPkcmF0aYet2PkEDo3MlTBckFXPITAMzF8dJSIFo9D8HfdOV0IAdx4O7PtixWKn5y2hMNG0zQPyUecp4pzC6kivAIhyfHilFR61RGL+GPXQ2MWZWFYbAGjyiYJnAmCP3NOTd0jMZEnDkbUvxhMmBYSdETk1rRgm+R4LOzFUGaHqHDLKLX+FIPKcF96hrucXzcWyLbIbEgE98OHlnVYCzRdK8jlqm8tehUc9c9WhQ== vagrant insecure public key
2 |
--------------------------------------------------------------------------------
/scripts/windows-features.ps1:
--------------------------------------------------------------------------------
1 | param ([string[]] $Features)
2 |
3 | if (!$Features) { "No features specified"; exit; }
4 | "Features: $Features"
5 |
6 | $Features | % {
7 |
8 | if ($OS_ANSWER_FILE -eq "2012_r2") {
9 | "Installing: $_"
10 | Install-WindowsFeature -IncludeAllSubFeature -Name $_
11 | }
12 |
13 | if ($OS_ANSWER_FILE -eq "81") {
14 | "Installing: $_"
15 | Enable-WindowsOptionalFeature -All -Online -FeatureName $_
16 | }
17 | }
18 |
19 |
20 | if ($OS_ANSWER_FILE -eq "2012_r2") {
21 | if ($WINDOWS_FEATURE_PURGE) {
22 | "Removing unused features"
23 | Get-WindowsFeature | ? InstallState -eq 'Available' | Uninstall-WindowsFeature -Remove
24 | }
25 |
26 | "`nInstalled Features:`n"
27 | Get-WindowsFeature | ? {$_.Installed} | select Name, DisplayName
28 | }
29 | if ($OS_ANSWER_FILE -eq "81") {
30 | if ($WINDOWS_FEATURE_PURGE) {
31 | "Removing unused features"
32 | Get-WindowsOptionalFeature -Online | ? State -eq 'Disabled' | Disable-WindowsOptionalFeature -Online -Remove
33 | }
34 |
35 | "`nInstalled Features:`n"
36 | Get-WindowsOptionalFeature -Online | ? {$_.State -eq 'Enabled'} | select FeatureName
37 | }
38 |
--------------------------------------------------------------------------------
/scripts/windows-tweaks.ps1:
--------------------------------------------------------------------------------
1 | param ( [scriptblock] $Features )
2 |
3 | function show-args($Name) {
4 | " $Name"
5 | $ParameterList = $Name.Parameters
6 | foreach ($key in $ParameterList.keys)
7 | {
8 | $var = Get-Variable -Name $key -ErrorAction SilentlyContinue;
9 | if($var) { " $($var.name) : $($var.value)" }
10 | }
11 | }
12 |
13 | function Explorer-Feature {
14 | param(
15 | [switch]$ShowHidden,
16 | [switch]$ShowSupperHidden,
17 | [switch]$ShowFileExtensions,
18 | # Show full folder path in title and address bar
19 | [switch]$ShowFullPath,
20 | [switch]$ShowRun,
21 | [switch]$ShowAdminTools,
22 | # Add context menu to open Powershell in the folder
23 | [switch]$PSOpenHere,
24 | # Disable Windows start page
25 | [switch]$NoStartPage,
26 | # Disable automatic tray icon hiding for all profiles
27 | [switch]$NoAutoTray
28 | )
29 | show-args (Get-Command $MyInvocation.InvocationName)
30 |
31 | $key = 'HKCU:\Software\Microsoft\Windows\CurrentVersion\Explorer\Advanced'
32 |
33 | if ($ShowFullPath) {
34 | Set-ItemProperty $key FullPath 1
35 | Set-ItemProperty $key FullPathAddress 1
36 | }
37 | if ($ShowHidden) { Set-ItemProperty $key Hidden 1}
38 | if ($ShowSupperHidden) { Set-ItemProperty $key ShowSuperHidden 1}
39 | if ($ShowFileExtensions) { Set-ItemProperty $key HideFileExt 0 }
40 | if ($ShowRun) { Set-ItemProperty $key Start_ShowRun 1 }
41 | if ($ShowAdminTools) { Set-ItemProperty $key StartMenuAdminTools 1 }
42 | if ($PSOpenHere) {
43 | $pspath = "$PSHome\powershell.exe -Noexit -Nologo"
44 | $key = "HKLM:\SOFTWARE\Classes\Directory\shell\PSOpenHere"
45 | New-Item $key -Force | out-null
46 | Set-Item $key "PowerShell Here"
47 | New-item "$key\command" -force | out-null
48 | Set-item "$key\command" "$pspath -Command Set-Location '%L'"
49 | }
50 | if ($NoStartPage) { #http://goo.gl/MfzTj6
51 | $key = "HKCU:\Software\Microsoft\Windows\CurrentVersion\Explorer\StartPage"
52 | Set-ItemProperty $key OpenAtLogon 0
53 | }
54 | if ($NoAutoTray) {
55 | Set-ItemProperty HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\Explorer EnableAutoTray 0
56 | }
57 | }
58 |
59 | function CLI-Feature {
60 | param(
61 | [switch] $EnableQuickEdit
62 | )
63 | show-args (Get-Command $MyInvocation.InvocationName)
64 | if ($EnableQuickEdit) { Set-ItemProperty HKCU:\Console QuickEdit 1 }
65 | }
66 |
67 | function System-Feature {
68 | param(
69 | [switch]$NoHibernation,
70 | [switch]$NoUAC,
71 | [switch]$NoShutdownTracker,
72 | [switch]$NoAutoUpdate,
73 | [switch]$DisableFirewall,
74 | # Disable password expiration for all users
75 | [switch]$NoPasswordExpiration,
76 | # Use Powershell as default shell on Windows Core
77 | [switch]$SetPoshAsDefault
78 | )
79 | show-args (Get-Command $MyInvocation.InvocationName)
80 |
81 | if ($NoHibernation) {
82 | Set-ItemProperty HKLM:\SYSTEM\CurrentControlSet\Control\Power HiberFileSizePercent 0
83 | Set-ItemProperty HKLM:\SYSTEM\CurrentControlSet\Control\Power HibernateEnabled 0
84 | }
85 |
86 | if ($NoUAC) {
87 | New-ItemProperty HKLM:\Software\Microsoft\Windows\CurrentVersion\policies\system EnableLUA -PropertyType DWord -Value 0 -Force | out-null
88 | }
89 |
90 | if ($NoShutdownTracker) {
91 | New-Item -Path 'HKLM:\SOFTWARE\Policies\Microsoft\Windows NT' -Name Reliability -Force | out-null
92 | Set-ItemProperty 'HKLM:\SOFTWARE\Policies\Microsoft\Windows NT\Reliability' ShutdownReasonOn 0
93 | }
94 |
95 | if ($NoAutoUpdate) {
96 | $Updates = (New-Object -ComObject "Microsoft.Update.AutoUpdate").Settings
97 |
98 | if ($Updates.ReadOnly -eq $True) { Write-Error "Cannot update Windows Update settings due to GPO restrictions." }
99 | else {
100 | $Updates.NotificationLevel = 1 #Disabled
101 | $Updates.Save()
102 | $Updates.Refresh()
103 | }
104 | }
105 |
106 | if ($DisableFirewall) { Get-NetFirewallProfile | Set-NetFirewallProfile -Enabled false -PassThru | select Name,Enabled | ft -Autosize }
107 | if ($NoPasswordExpiration) { net accounts /maxpwage:unlimited }
108 |
109 | if ($SetPoshAsDefault) { ./Set-PoshAsDefault.ps1 }
110 | }
111 |
112 | &$Features
113 |
--------------------------------------------------------------------------------
/scripts/windows-update.ps1:
--------------------------------------------------------------------------------
1 | param(
2 | # http://support.microsoft.com/kb/824684
3 | # https://msdn.microsoft.com/en-us/library/ff357803(v=vs.85).aspx
4 | [AllowEmptyCollection()]
5 | [ValidateSet('Application', 'Connector', 'CriticalUpdates', 'DefinitionUpdates', 'DeveloperKits, ', 'FeaturePacks', 'Guidance', 'SecurityUpdates', 'ServicePacks', 'Tools', 'UpdateRollups', 'Updates')]
6 | [String[]]$Categories,
7 | [String[]]$KB
8 | )
9 |
10 | $cat=@()
11 | if ($Categories) {
12 | # Split categories on capitals
13 | $Categories | % { $cat += (($_ -csplit "(?<=.)(?=[A-Z])") -join ' ') }
14 | if ($cat.Length) { "Update categories ($($cat.Length)): $($cat -join ', ')" }
15 | }
16 | if ($KB.Length) { "Update KBs ($($KB.Length)): $($KB -join ', ')" }
17 |
18 | . ./Get-WUInstall.ps1
19 | Get-WUInstall -OutVariable result -IgnoreUserInput -KBArticleID $KB -Category $cat -AcceptAll -IgnoreReboot
20 | if (!$result) {"WARRNING: No updates installed"}
21 |
22 | # How Windows Update determines proxy to use
23 | #http://support.microsoft.com/kb/900935
24 |
25 | #The Microsoft Windows Update client program requires Microsoft Windows HTTP Services (WinHTTP) to scan for available updates. Additionally, the Windows Update client uses the Background Intelligent Transfer Service (BITS) to download these updates. Microsoft Windows HTTP Services and BITS run independently of Microsoft Internet Explorer. Both these services must be able to detect the proxy server or proxy servers that are available in your particular environment.
26 |
27 | # Get-wulist -Category ("critical updates", "security updates") -Title "Security"
28 | #Get-WUInstall -IgnoreUserInput -Category "Security Updates" -AcceptAll -IgnoreReboot
29 | #Get-WUInstall -IgnoreUserInput -KBArticleID "KB2931366" -AcceptAll -IgnoreReboot
30 | #Get-WUInstall -IgnoreUserInput -AcceptAll -IgnoreReboot
31 | #Get-WUInstall -IgnoreUserInput -Category ("Critical Updates", "Security Updates") -NotCategory "Language packs" -AcceptAll -IgnoreReboot
32 |
33 |
--------------------------------------------------------------------------------
/vagrant/Vagrantfile:
--------------------------------------------------------------------------------
1 | # -*- mode: ruby -*-
2 | # vi: set ft=ruby :
3 |
4 | Vagrant.require_version ">= 1.7.2"
5 |
6 | $store_remote = 'file:////itshare.mycompany.rs/_images/projectx'
7 | $store_local = '../output'
8 | def get_box_url( name ) $local ? "#{$store_local}/#{name}/#{name}-virtualbox.box" : "#{$store_remote}/#{name}/#{name}.json" end
9 | $machines = Dir["#{$store_local}/*/"].map { |a| File.basename(a) }
10 |
11 | $gui = !ENV['VAGRANT_GUI'].nil?
12 | $local = ENV['VAGRANT_LOCAL']
13 |
14 | Vagrant.configure("2") do |config|
15 |
16 | config.vm.communicator = "winrm"
17 | config.winrm.username = "vagrant"
18 | config.winrm.password = "vagrant"
19 |
20 | config.windows.halt_timeout = 15
21 | config.windows.set_work_network = true
22 |
23 | config.vm.guest = :windows
24 | config.vm.boot_timeout = 600
25 | config.vm.network :forwarded_port, guest: 3389, host: 33389, id: "rdp", auto_correct: true
26 | config.vm.network :forwarded_port, guest: 22, host: 2222, id: "ssh", auto_correct: true
27 | config.vm.synced_folder "..", "/vagrant_data"
28 |
29 | $machines.each do |m|
30 | config.vm.define m, autostart: false do |c|
31 | c.vm.box = m
32 | #c.vm.hostname = c.vm.box
33 | c.vm.box_url = get_box_url c.vm.box
34 | c.vm.network "private_network", ip: "192.168.0.10"
35 | c.vm.provider "virtualbox" do |v|
36 | v.name = c.vm.box
37 | end
38 | end
39 | end
40 |
41 | config.vm.provider "virtualbox" do |v|
42 | v.gui = $gui
43 | #v.memory = 4096
44 | #v.cpus = 4
45 | end
46 | end
47 |
--------------------------------------------------------------------------------
/vagrant_metadata.json:
--------------------------------------------------------------------------------
1 | {
2 | "description": "$BOX_DESCRIPTION",
3 | "short_description": "",
4 | "name": "$BOX_NAME",
5 | "versions": [{
6 | "version": "$BOX_VERSION",
7 | "status": "active",
8 | "description_html": "Repository revision: $BOX_REVISION",
9 | "description_markdown": "",
10 | "providers": [
11 | {
12 | "name": "virtualbox",
13 | "url": "$BOX_URL"
14 | }
15 | ]
16 | }]
17 | }
18 |
--------------------------------------------------------------------------------
/vagrantfile.template:
--------------------------------------------------------------------------------
1 | # -*- mode: ruby -*-
2 | # vi: set ft=ruby :
3 |
4 | Vagrant.require_version ">= 1.7.2"
5 |
6 | Vagrant.configure("2") do |config|
7 | #config.vm.define "vagrant-windows-2012-r2"
8 | config.vm.box = "base_virtualbox.box"
9 |
10 | # Admin user name and password
11 | config.vm.communicator = "winrm"
12 | config.winrm.username = "vagrant"
13 | config.winrm.password = "vagrant"
14 |
15 | config.vm.guest = :windows
16 | config.windows.halt_timeout = 15
17 |
18 | config.vm.network :forwarded_port, guest: 3389, host: 33389, id: "rdp", auto_correct: true
19 | config.vm.network :forwarded_port, guest: 22, host: 2222, id: "ssh", auto_correct: true
20 |
21 | config.vm.provider :virtualbox do |v, override|
22 | #v.gui = true
23 | #v.customize ["modifyvm", :id, "--memory", 2048]
24 | #v.customize ["modifyvm", :id, "--cpus", 2]
25 | #v.customize ["setextradata", "global", "GUI/SuppressMessages", "all" ]
26 | end
27 |
28 | config.vm.provider :vmware_fusion do |v, override|
29 | #v.gui = true
30 | v.vmx["memsize"] = "2048"
31 | v.vmx["numvcpus"] = "2"
32 | v.vmx["ethernet0.virtualDev"] = "vmxnet3"
33 | v.vmx["RemoteDisplay.vnc.enabled"] = "false"
34 | v.vmx["RemoteDisplay.vnc.port"] = "5900"
35 | v.vmx["scsi0.virtualDev"] = "lsisas1068"
36 | end
37 |
38 | config.vm.provider :vmware_workstation do |v, override|
39 | #v.gui = true
40 | v.vmx["memsize"] = "2048"
41 | v.vmx["numvcpus"] = "2"
42 | v.vmx["ethernet0.virtualDev"] = "vmxnet3"
43 | v.vmx["RemoteDisplay.vnc.enabled"] = "false"
44 | v.vmx["RemoteDisplay.vnc.port"] = "5900"
45 | v.vmx["scsi0.virtualDev"] = "lsisas1068"
46 | end
47 | end
48 |
--------------------------------------------------------------------------------