I would use a transcript, like this.
$Folder = "C:\ps_script_logs"
$ScriptName = "MyScript"
try {
if (Test-Path $Folder) {
$msg = "Unable to write to folder $folder" # use this msg if we crash
New-Item -Path $Folder\test.xyz -ItemType File -ErrorAction Stop
Remove-Item -Path $Folder\test.xyz -ErrorAction Stop
$msg = "$Folder exists and is writable." # we didn't crash
} else {
$msg = "Unable to create the folder $folder" # use this msg if we crash
New-Item -Path $Folder -ItemType Directory -ErrorAction Stop
$msg = "$Folder was created." # we didn't crash
}
} catch {
"We crashed which means that we don't have a way to generate a log file."
"Do something here to get someone's attention."
$msg
return
}
# if we get here, our folder exists, and we have verified that we can write to it.
$logfile = "{0}\{1}-{2}.log" -f $Folder, $ScriptName, (get-date).tostring("yyyyMMdd-hhmmss")
Start-Transcript $logfile
$msg
# This script is intended to create a custom local administrator for offline use on Entra ID joined computers.
# Define the username and password
$Username = "Admin"
$Password = "Mster@dmin"
# Check if the user already exists
$ExistingUser = Get-LocalUser -Name $Username -ErrorAction SilentlyContinue
if ($ExistingUser) {
"The user exists."
# If the user exists, update the password and set it to never expire
Set-LocalUser -Name $Username -Password (ConvertTo-SecureString -AsPlainText $Password -Force) -PasswordNeverExpires $true
} else {
"Adding the user."
# If the user doesn't exist, create the local user and set the password to never expire
New-LocalUser -Name $Username -Password (ConvertTo-SecureString -AsPlainText $Password -Force) -PasswordNeverExpires
# Then add the new user to the local administrators group
$AdminGroup = Get-LocalGroup -Name "Administrators"
$AdminUser = Get-LocalUser -Name $Username
Add-LocalGroupMember -Group $AdminGroup -Member $AdminUser
}
Stop-Transcript