NotesWhat is notes.io?

Notes brand slogan

Notes - notes.io

# Powershell script to install package with Chocolatey
# ProbaYes 2017 @ Nicolas Drufin <[email protected]>

<#
.SYNOPSIS
Initialisation de poste Windows Probayes


.DESCRIPTION
Ce script instale l'utilitaire chocolatey afin de pouvoir installer des
applications sur la machine tel que firefox, thunderbird, libreoffice, etc.


.EXAMPLE
il faut preciser la politique d'execution avant de pouvoir lancer ce script.
Le script ne conporte pas de parametre d'entree.
Set-ExecutionPolicy Bypass -Scope Process -Force; ./insall_windows_client.ps1

#>

# functions
function Get-InstalledApps
{
if ([IntPtr]::Size -eq 4) {
$regpath = 'HKLM:SoftwareMicrosoftWindowsCurrentVersionUninstall*'
}
else {
$regpath = @(
'HKLM:SoftwareMicrosoftWindowsCurrentVersionUninstall*'
'HKLM:SoftwareWow6432NodeMicrosoftWindowsCurrentVersionUninstall*'
)
}
Get-ItemProperty $regpath | .{process{if($_.DisplayName -and $_.UninstallString) { $_ } }} | Select DisplayName, Publisher, InstallDate, DisplayVersion, UninstallString |Sort DisplayName
}

# change hostname
$computerName = Get-WmiObject Win32_ComputerSystem
$name = Read-Host -Prompt "Please Enter Hostname [ENTER to ignore]"
if ($name) {
$computername.Rename($name)
}

# Allow ICMP
$resultfw = Get-NetFirewallRule -DisplayName 'Allow inbound ICMPv4' 2> $null;
if ($resultfw) {
write-host "ICMP already allowed"
}
else {
write-host "Allow ICMP"
New-NetFirewallRule -DisplayName "Allow inbound ICMPv4" -Direction Inbound -Protocol ICMPv4 -IcmpType 8 -Action Allow
New-NetFirewallRule -DisplayName "Allow inbound ICMPv6" -Direction Inbound -Protocol ICMPv6 -IcmpType 8 -Action Allow
}

# install chocolatey
if (Get-Command choco -errorAction SilentlyContinue) {
Write-Host "Chocolatey package manager already installed"
} else {
Write-Host "Install chocolatey package manager"
Set-ExecutionPolicy Bypass -Scope Process -Force; iex ((New-Object System.Net.WebClient).DownloadString('https://chocolatey.org/install.ps1'))
}

# install and upgrade packages
choco install firefox thunderbird libreoffice 7zip sumatrapdf wireguard bulk-crap-uninstaller bleachbit gajim -y
choco upgrade all -y

# disable Fast startup
Write-Host "Disable fast boot (patch on NTFS dual boot)"
Set-ItemProperty -Path "HKLM:SYSTEMCurrentControlSetControlSession ManagerPower" -Name HiberbootEnabled -Value 0

# install ssh client and server (only Windows 10)
if ([System.Environment]::OSVersion.Version.Major -eq 10) {
Write-Host "Install OpenSSH for Windows"
foreach ($package in (Get-WindowsCapability -Online | ? Name -like 'OpenSSH*')) {
Add-WindowsCapability -Online -Name $package.Name
}
# set config
Get-Content "C:WINDOWSSystem32OpenSSHsshd_config_default" | % { $_ -replace "#PasswordAuthentication yes","PasswordAuthentication no"} | Out-File "C:WINDOWSSystem32OpenSSHsshd_config"
# enable ssh server
Set-Service sshd -StartupType Automatic
# Copy ssh key
Write-Host "Add SSH key for boss"
New-Item -Name ".ssh" -path "$Env:USERPROFILE" -itemType Directory -Force
Add-Content "${Env:USERPROFILE}.sshauthorized_keys" "ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABAQC1ALswB4viJF1oB+TEJTY0OoktCUoILwzUnW9kCpskW2BaZn9hoHohne32yF+Ie9LawbRpamyrNyzwLv8OIKg6DJcYPVaiQteWnLP6suGepRnbp6legV69KMnGQ4sMlhCPySfJCXnaIeHzFMyZSVwfEiuSPxzxDPYCdn6TH9HuXUco7NI6qVCemXN7J0P/lhuCgLQFBhGAbP5PovJB8HR1YqsN/Bh1iPw61AueV8NmGObmzqV0OEgIdPx6yuYEjh6IwJFKTOppTv8BdUnT4VvvJgOIx6wMQeertyIrRdsUEhdiGTZ9oofhK5WBjVOOUcSOkGYPLpBK8k3aEVOf8X51 root@ansible"
}

# create a local administrator
$confirmUserCreation = Read-Host "Add an administrator user (Y/n)?"
if (!$confirmUserCreation) { $confirmUserCreation = "y" }
if ($confirmUserCreation -match '[Yy]') {
$username = Read-Host "Enter user name (LDAP login)"
$computer = [ADSI]"WinNT://$Env:COMPUTERNAME,Computer"

# test if user exist
if ($Computer.children | where {$_.schemaclassname -eq "user" -and $_.name -eq $username}) {
Write-Host "User $username already exist"
} else {
# enter password and convert to plain text
Do {
$SecurePassword = Read-Host -Prompt "Enter password" -AsSecureString
$ReSecurePassword = Read-Host -Prompt "Retype password" -AsSecureString
$BSTR = [System.Runtime.InteropServices.Marshal]::SecureStringToBSTR($SecurePassword)
$ReBSTR = [System.Runtime.InteropServices.Marshal]::SecureStringToBSTR($ReSecurePassword)
$PlainPassword = [System.Runtime.InteropServices.Marshal]::PtrToStringAuto($BSTR)
$RePlainPassword = [System.Runtime.InteropServices.Marshal]::PtrToStringAuto($ReBSTR)
# test password
$retry = $FALSE
if ($PlainPassword -ne $RePlainPassword) {
$confirmPwdRetry = Read-Host "Passwords not match, retry (Y/n)?"
if (!$confirmPwdRetry) { $confirmPwdRetry = "y" }
if ($confirmPwdRetry -match '[Yy]') {
$retry = $TRUE
}
}
} Until(-Not $retry)

if ($PlainPassword -eq $RePlainPassword) {
# set full name
$fullname = Read-Host "Enter full name"

# create user
$User = $Computer.Create("User", $username)
$User.SetPassword("$PlainPassword")
$User.SetInfo()
$User.FullName = "$fullname"
$User.SetInfo()
$user.passwordExpired = 1; # Password need change at next logon
$user.setinfo();
$User.UserFlags = 65536 # PASSWD_NEVER_EXPIRE
$User.SetInfo()
$GroupAdmin = [ADSI]("WinNT://$Env:COMPUTERNAME/Administrateurs,Group")
if ($GroupAdmin.Path -eq $null) {
$GroupAdmin = [ADSI]("WinNT://$Env:COMPUTERNAME/Administrators,Group")
}
$GroupAdmin.add("WinNT://$Env:COMPUTERNAME/$UserName")
$GroupUser = [ADSI]("WinNT://$Env:COMPUTERNAME/Utilisateurs,Group")
if ($GroupUser.Path -eq $null) {
$GroupUser = [ADSI]("WinNT://$Env:COMPUTERNAME/Users,Group")
}
$GroupUser.add("WinNT://$Env:COMPUTERNAME/$UserName")
Write-Host "User $username successfully created"

# init user home directory
Write-Host "Init user home directory (a temporary powershell window may appears)"
$credential = New-Object System.Management.Automation.PSCredential $username,$securePassword
Start-Process powershell.exe -ArgumentList "echo 'Init user in progress... This window will be closed automaticaly.'" -Credential $credential

# request ldap user
Write-Host "Load user $username from ldap"
[System.Reflection.Assembly]::LoadWithPartialName("System.DirectoryServices.Protocols")
[System.Reflection.Assembly]::LoadWithPartialName("System.Net")
$ldapargs = New-Object -TypeName System.DirectoryServices.Protocols.LdapDirectoryIdentifier -ArgumentList "ldap.probayes.net",636,$TRUE,$FALSE
$c = New-Object System.DirectoryServices.Protocols.LdapConnection $ldapargs
$c.SessionOptions.ProtocolVersion = 3
$c.AuthType = [System.DirectoryServices.Protocols.AuthType]::Anonymous
$scope = [System.DirectoryServices.Protocols.SearchScope]::OneLevel
[String[]] $fields = "mail","cn","sshPublicKey"
$r = New-Object System.DirectoryServices.Protocols.SearchRequest -ArgumentList "ou=users,dc=probayes,dc=com","(uid=$username)",$scope,$fields
$res = $c.SendRequest($r)
if ($res.Entries.Count -eq 1) {
$userattrs = $res.Entries[0].Attributes
$usercn = $userattrs.cn[0]
$usermail = $userattrs.mail[0]
$sshpublickeys = ""
for($i=0; $i -lt $userattrs.sshpublickey.Count; $i++) {
$sshpublickeys += $userattrs.sshpublickey[$i]+"`r`n"
}

# install developpers tools
$confirmDevUser = Read-Host "Install developper tools (Y/n)?"
if (!$confirmDevUser) { $confirmDevUser = "y" }
if ($confirmDevUser -match '[Yy]') {
# install git
choco install git -y
# get path of user
$sid = (Get-WmiObject -Class Win32_UserAccount | where {$_.name -eq $username}).SID
$userhome = (Get-WmiObject -Class Win32_UserProfile | where {$_.SID -eq $sid}).LocalPath
# configure git
Add-Content "${userhome}.gitconfig" "[name]`r`n`tname = $usercn`r`n`temail = $usermail"
# Copy ssh key (Windows 10 only)
if ([System.Environment]::OSVersion.Version.Major -eq 10) {
New-Item -Name ".ssh" -path "$userhome" -itemType Directory
Add-Content "${userhome}.sshauthorized_keys" "$sshpublickeys"
}
}
}
} else {
Write-Host "Abort user $username creation"
}
}
}

# download and unzip OCSInventory
if (Get-InstalledApps | where {$_.DisplayName -like "OCS Inventory NG Agent 2.0.5.0"}) {
Write-Host "OCS Inventory is already installed"
} else {
Invoke-WebRequest "http://files.probayes.net/files/wiki/it/ocs-inventory/OCSNG-Windows-Agent-2.0.5.zip" -UseBasicParsing -OutFile "$env:USERPROFILEDesktopOCSInventory.zip"
Expand-Archive "$env:USERPROFILEDesktopOCSInventory.zip" -DestinationPath "$env:USERPROFILEDesktopOCSInventory" -Force
Write-Host "OCS Inventory has been copied on desktop, please execute it after restart"
# $confirmRestart = Read-Host "Do you want to restart now (Y/n)?"
# if (!$confirmRestart) { $confirmRestart = "y" }
# if ($confirmRestart -match '[Yy]') {
# Restart-Computer
# }
}

# Auto updating windows
# creates a '.cmd' script in "C:Users<user_name>AppDataRoamingMicrosoftWindowsStart MenuProgramsStartup"
# so it runs at startup to continues updating windows after restart
# the cmd script invoke a PowerShell process that runs the actual update scripts
# it then delete itself if there is no more updates to install.

'PowerShell -Command "Set-ExecutionPolicy Bypass -Scope Process -Force"
PowerShell C:Usersbossupdate_windows_client.ps1' | Out-File -FilePath "C:UsersbossAppDataRoamingMicrosoftWindowsStart MenuProgramsStartupauto_update.cmd"

'#check de presence de PSWindowsUpdate
Import-Module -Name PSWindowsUpdate 2>5
if (!$?) {
#Si pas present alors on le telecharge + import
Install-Module -Name PSWindowsUpdate -Force
Import-Module -Name PSWindowsUpdate
}

write-output "Recuperation des mises a jours disponibles ..."
$updates = Get-WUList
$updates

If ($updates) {
write-output "Windows est a jour !"
write-output "Suppression des scripts de mise a jour auto ..."
rm "C:UsersbossAppDataRoamingMicrosoftWindowsStart MenuProgramsStartupauto_update.cmd"
rm "C:Usersbossupdate_windows_client.ps1"
}

write-warning "Lancement des mises a jours en automatique !"
write-warning ""
write-warning "votre ordinateur vas redemarer un fois les mises a jours installes"
write-output ""
Install-WindowsUpdate -AcceptAll -AutoReboot' | Out-File -FilePath "C:Usersbossupdate_windows_client.ps1"
     
 
what is notes.io
 

Notes is a web-based application for online taking notes. You can take your notes and share with others people. If you like taking long notes, notes.io is designed for you. To date, over 8,000,000,000+ notes created and continuing...

With notes.io;

  • * You can take a note from anywhere and any device with internet connection.
  • * You can share the notes in social platforms (YouTube, Facebook, Twitter, instagram etc.).
  • * You can quickly share your contents without website, blog and e-mail.
  • * You don't need to create any Account to share a note. As you wish you can use quick, easy and best shortened notes with sms, websites, e-mail, or messaging services (WhatsApp, iMessage, Telegram, Signal).
  • * Notes.io has fabulous infrastructure design for a short link and allows you to share the note as an easy and understandable link.

Fast: Notes.io is built for speed and performance. You can take a notes quickly and browse your archive.

Easy: Notes.io doesn’t require installation. Just write and share note!

Short: Notes.io’s url just 8 character. You’ll get shorten link of your note when you want to share. (Ex: notes.io/q )

Free: Notes.io works for 14 years and has been free since the day it was started.


You immediately create your first note and start sharing with the ones you wish. If you want to contact us, you can use the following communication channels;


Email: [email protected]

Twitter: http://twitter.com/notesio

Instagram: http://instagram.com/notes.io

Facebook: http://facebook.com/notesio



Regards;
Notes.io Team

     
 
Shortened Note Link
 
 
Looding Image
 
     
 
Long File
 
 

For written notes was greater than 18KB Unable to shorten.

To be smaller than 18KB, please organize your notes, or sign in.