0

I am pretty new to PowerShell scripting so I wanted to write a script that helps our apprentices in setting up new laptops for our customers.

This script should rename the computer, then restart it and then proceed to install some software. Some of the software isnt available through winget because its our system software so I had to put in on a USB drive.

The PowerShell script should continue after the reboot but sadly it doesnt.

Set-ExecutionPolicy Unrestricted -force
Install-Module ThreadJob -Force
import-module ThreadJob
Install-Module PSWindowsUpdate -force
import-module pswindowsupdate
Import-Module ScheduledTasks
Install-Module -Name ScheduledJobTools -force
import-module ScheduledJobTools
function Install-SysInternalsTool{
    $targetDir = Join-Path $env:WinDir "System32\SysInternals"
    $tools = @{
        Autologon = "http://live.sysinternals.com/Autologon.exe"}
    Write-Verbose "Create Directory: $targetDir"
    New-Item -ItemType Directory -Path $targetDir -Force | Out-Null
    try{
        $wc = New-Object System.Net.WebClient
        foreach($tool in $tools.Values){          
            $filePath = Join-Path $targetDir ([IO.Path]::GetFileName($tool))
            Write-Verbose "Downloading $tool"
            $wc.DownloadFile($tool,$filePath)}}
    finally{
        $wc.Dispose()}}
function Enable-AutoLogon{
    param(
    [string] $UserName,
    [string] $Password)
    $exePath = Join-Path $env:WinDir "System32\SysInternals\AutoLogon.exe"
    if(!(Test-Path $exePath)){
        Write-Error "AutoLogon.exe is not found at $exePath"}
    $paths = $UserName.Split("\")
    $domain = $paths[0]
    $user   = $paths[1]
    Start-Process -FilePath  $exePath -ArgumentList "/accepteula", $user, $domain, $password -Wait}
Install-SysInternalsTool
Enable-AutoLogon -UserName ".\admin" -Password "#bs15081!"
$baseUri = 'https://github.com/microsoft/winget-cli/releases/download'
    $files = @(
        @{Uri = "$baseUri/v1.4.10173/Microsoft.DesktopAppInstaller_8wekyb3d8bbwe.msixbundle"
        OutFile = 'Microsoft.DesktopAppInstaller_8wekyb3d8bbwe.msixbundle'})
    $jobs = @()
    foreach ($file in $files) {
        $jobs += Start-ThreadJob -Name $file.OutFile -ScriptBlock {
            $params = $using:file
            Invoke-WebRequest @params}}
    Wait-Job -Job $jobs
    foreach ($job in $jobs) {
        Receive-Job -Job $job
        .\Microsoft.DesktopAppInstaller_8wekyb3d8bbwe.msixbundle}
workflow renamereboot {
    $oldname = hostname
    $name = [Microsoft.VisualBasic.Interaction]::InputBox("Neuen Computernamen eingeben:", "Computer Name")
    Add-Type -AssemblyName Microsoft.VisualBasic
    Rename-Computer -NewName $name
    Register-ScheduledJob -Name renamerebootresume `
                      -ScriptBlock {
                          Get-Job -Name NewSetup -State Suspended `
                          | Resume-Job}
    Restart-Computer -pscomputername $oldname -Wait -For PowerShell
    unregister-scheduledjob -name renamerebootresume}
$laufwerk = get-volume | where drivetype -eq removable | foreach driveletter
$punkt=$laufwerk + ":"
<#if (-not(test-path -path $punkt)) {
    echo "Kein USB Stick angeschlossen"}
else {$labtech = Get-ChildItem "$punkt\Labtech" | where {$_.extension -eq ".msi"} | ForEach-Object {$_.FullName}
    start $labtech -NoNewWindow
    $sophos = Get-ChildItem "$punkt\Sophos" | where {$_.extension -eq ".exe"} | ForEach-Object {$_.FullName}
    start $sophos -NoNewWindow
    .\SwyxIt!German64.msi
    .\SophosConnect_2.2.75.msi}#>
#winget import $punkt\winget.json --ignore-versions --accept-package-agreements --accept-source-agreements
winget upgrade Microsoft.DesktopAppInstaller_8wekyb3d8bbwe -h --force --disable-interactivity --accept-package-agreements --accept-source-agreements
winget install -e Mozilla.Firefox -h --force --disable-interactivity --accept-package-agreements --accept-source-agreements
winget install -e geeksoftwareGmbH.PDF24Creator -h --force --disable-interactivity --accept-package-agreements --accept-source-agreements
winget install -e 7zip.7zip -h --force --disable-interactivity --accept-package-agreements --accept-source-agreements
winget install -e Adobe.Acrobat.Reader.64-bit -h --force --disable-interactivity --accept-package-agreements --accept-source-agreements
Get-WindowsUpdate -AcceptAll -Install -autoreboot
renamereboot -JobName NewSetup 2> error.log
2
  • Recently I came across a similar situation and my solution is to first install software's which does not have any pre-requisites and install pre-requisites, add ```Set-ItemProperty "HKLM:\Software\Microsoft\Windows\CurrentVersion\RunOnce" -Name '!RunItOnce' -Value "C:\Windows\Temp\yourexeorpsScript", Restart and login with admin credentials. It was sufficient for my requirements, but not sure for your's. Commented Feb 20, 2023 at 15:24
  • Sadly that didnt work. But you for trying to help Commented Feb 21, 2023 at 10:28

1 Answer 1

0

Here is my sample script: script to execute(beforeRestart.ps1)

$DefaultUsername = "admin" # Admin account must be present
$DefaultPassword = "Password123"
$command="c:\windows\system32\windowspowershell\v1.0\powershell.exe -executionpolicy unrestricted -File C:\Windows\Temp\afterRestart.ps1"
$RegPath = "HKLM:\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Winlogon"
Set-ItemProperty "HKLM:\Software\Microsoft\Windows\CurrentVersion\RunOnce" -Name '!RunItOnce' -Value $command
Set-ItemProperty $RegPath "AutoAdminLogon" -Value "1" 
Set-ItemProperty $RegPath "DefaultUsername" -Value $DefaultUsername
Set-ItemProperty $RegPath "DefaultPassword" -Value $DefaultPassword 
Write-Output "This computer is rebooted at $(Get-Date)" | Out-File "C:\Windows\Temp\restsarttest.txt" -Append
Restart-Computer -Force

Second script stored in C:\Windows\Temp as afterRestart.ps1

Write-Output "$($env:COMPUTERNAME) is restarted and logged in with $($env:USERNAME) at $(Get-Date)" | Out-File "C:\Windows\Temp\secondrestart.txt" -Append
Start-Process "msiexec.exe" -wait -ArgumentList '/I C:\Windows\Temp\softToInstall.msi /quiet'
$RegPath = "HKLM:\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Winlogon"
Remove-ItemProperty  -path $RegPath -name "AutoAdminLogon"
Remove-ItemProperty -path  $RegPath -name "DefaultUsername" 
Remove-ItemProperty -path  $RegPath -name "DefaultPassword"
Restart-Computer -Force

Note: This may not be the direct answer to your question, but this is how I did. Also, this script stores password in plain text, but yes it can be modified.

Sign up to request clarification or add additional context in comments.

3 Comments

Hello, I just tried it on my test Laptop and now it is boot looping. So yeah.
The !Runonce in registry entry will be removed when the script successfully executed. Is your laptop continuously restarting now? Sorry for that. you may remove Restart-computer in the second script.
After a bit of figgling with it, it now works perfectly. Thank you very much.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.