Powershell Script to Add New Users in AD for HR Department - windows

I'm trying to come up with a powershell script to add new users in AD that our HR department can use instead of sending me emails about that.
My script will ask for which department they wanna add the new user, username and the full name:
# ##########################################
# Determine if we have Administrator rights
Write-Host 'Checking user permissions... '
$windowsID = [System.Security.Principal.WindowsIdentity]::GetCurrent()
$windowsSecurityPrincipal = New-Object System.Security.Principal.WindowsPrincipal($windowsID)
$adminRole = [System.Security.Principal.WindowsBuiltInRole]::Administrator
If (!($windowsSecurityPrincipal.IsInRole($adminRole))) {
Write-Warning 'Current user does not have Administrator rights'
Write-Host 'Attempting to copy files to temporary location and restarting script'
# Get random file name
Do {
$temp = [System.IO.Path]::GetTempPath() + [System.IO.Path]::GetRandomFileName()
} Until (!(Test-Path -LiteralPath "$temp"))
# Create directory
Write-Host 'Creating temp directory... ' -NoNewLine
New-Item -Path "$temp" -ItemType 'Directory' | Out-Null
Write-Host 'done.'
# Copy script to directory
Write-Host 'Copying script to temp directory... ' -NoNewLine
Copy-Item -LiteralPath "$($myInvocation.MyCommand.Path)" "$temp" | Out-Null
Write-Host 'done.'
$newScript = "$($temp)\$($myInvocation.MyCommand.Name)"
# Start new script elevated
Write-Host 'Starting script as administrator... ' -NoNewLine
$adminProcess = New-Object System.Diagnostics.ProcessStartInfo
$adminProcess.Filename = ([System.Diagnostics.Process]::GetCurrentProcess()).Path
$adminProcess.Arguments = " -File `"$newScript`""
$adminProcess.Verb = 'runas'
Try {
[System.Diagnostics.Process]::Start($adminProcess) | Out-Null
}
Catch {
Write-Error 'Could not start process'
Exit 1
}
Write-Host 'done.'
Exit 0
}
#Change the execution policy
Set-ExecutionPolicy bypass
#Import the AD module
Import-Module ActiveDirectory
#Set variables
$title = "Add Users To The Domain"
$message = "For which department do you wanna add this user to?"
$rn = New-Object System.Management.Automation.Host.ChoiceDescription "&RN", `
"RN"
$callcenter = New-Object System.Management.Automation.Host.ChoiceDescription "&Call Center", `
"Call Center"
$management = New-Object System.Management.Automation.Host.ChoiceDescription "&Management", `
"Management"
$billing = New-Object System.Management.Automation.Host.ChoiceDescription "&Billing", `
"Billing"
$options = [System.Management.Automation.Host.ChoiceDescription[]]($rn, $callcenter, $management, $billing)
$result = $host.ui.PromptForChoice($title, $message, $options, 0)
switch ($result)
{
0 {"You selected RN."}
1 {"You selected Call Center."}
2 {"You selected Management."}
3 {"You Selected Billing."}
}
$UName = Read-Host "What is the username you wanna give? Make sure it matches the username in the email."
$FName = Read-Host "What is the Full Name of the user?"
New-ADUser `
-Name $FName `
-Path "CN=Users,OU=$result,DC=Domain,DC=com" `
-SamAccountName $UName `
-DisplayName $FName `
-AccountPassword (ConvertTo-SecureString "password1" -AsPlainText -Force) `
-ChangePasswordAtLogon $true `
-Enabled $true
Add-ADGroupMember "Users" "$UName";
Each time I try I run it I get this error message:
New-ADUser : Directory object not found At
C:\Users\youssef\AppData\Local\Temp\ofit4gnq.1lp\AddUserHR.ps1:84
char:1
+ New-ADUser `
+ ~~~~~~~~~~~~
+ CategoryInfo : ObjectNotFound: (CN=TYoussef Tes...diatrics,DC=Com:String) [New-ADUser], ADIdentityNotFo
undException
+ FullyQualifiedErrorId : ActiveDirectoryCmdlet:Microsoft.ActiveDirectory.Management.ADIdentityNotFoundException,M
icrosoft.ActiveDirectory.Management.Commands.NewADUser
Add-ADGroupMember : Cannot find an object with identity: 'yousseft'
under: 'DC=TribecaPediatrics,DC=com'. At
C:\Users\youssef\AppData\Local\Temp\ofit4gnq.1lp\AddUserHR.ps1:92
char:1
+ Add-ADGroupMember "Users" "$UName";
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : ObjectNotFound: (yousseft:ADPrincipal) [Add-ADGroupMember], ADIdentityNotFoundException
+ FullyQualifiedErrorId : SetADGroupMember.ValidateMembersParameter,Microsoft.ActiveDirectory.Management.Commands.
AddADGroupMember

$result comes back as an integer so the path you're giving to New-ADUser looks like this:
"CN=Users,OU=0,DC=Domain,DC=com"
Which is why you're getting that error message, because more than likely there is no OU with the name "0" or any of the other options "1","2" or "3".
In your switch statement you should declare what each departments OU is called so you can put the new user into that OU.
you were very close, here's how i would modify your switch statement:
# ##########################################
# Determine if we have Administrator rights
Write-Host 'Checking user permissions... '
$windowsID = [System.Security.Principal.WindowsIdentity]::GetCurrent()
$windowsSecurityPrincipal = New-Object System.Security.Principal.WindowsPrincipal($windowsID)
$adminRole = [System.Security.Principal.WindowsBuiltInRole]::Administrator
If (!($windowsSecurityPrincipal.IsInRole($adminRole))) {
Write-Warning 'Current user does not have Administrator rights'
Write-Host 'Attempting to copy files to temporary location and restarting script'
# Get random file name
Do {
$temp = [System.IO.Path]::GetTempPath() + [System.IO.Path]::GetRandomFileName()
} Until (!(Test-Path -LiteralPath "$temp"))
# Create directory
Write-Host 'Creating temp directory... ' -NoNewLine
New-Item -Path "$temp" -ItemType 'Directory' | Out-Null
Write-Host 'done.'
# Copy script to directory
Write-Host 'Copying script to temp directory... ' -NoNewLine
Copy-Item -LiteralPath "$($myInvocation.MyCommand.Path)" "$temp" | Out-Null
Write-Host 'done.'
$newScript = "$($temp)\$($myInvocation.MyCommand.Name)"
# Start new script elevated
Write-Host 'Starting script as administrator... ' -NoNewLine
$adminProcess = New-Object System.Diagnostics.ProcessStartInfo
$adminProcess.Filename = ([System.Diagnostics.Process]::GetCurrentProcess()).Path
$adminProcess.Arguments = " -File `"$newScript`""
$adminProcess.Verb = 'runas'
Try {
[System.Diagnostics.Process]::Start($adminProcess) | Out-Null
}
Catch {
Write-Error 'Could not start process'
Exit 1
}
Write-Host 'done.'
Exit 0
}
#Change the execution policy
Set-ExecutionPolicy bypass
#Import the AD module
Import-Module ActiveDirectory
#Set variables
$title = "Add Users To The Domain"
$message = "For which department do you wanna add this user to?"
$rn = New-Object System.Management.Automation.Host.ChoiceDescription "&RN", `
"RN"
$callcenter = New-Object System.Management.Automation.Host.ChoiceDescription "&Call Center", `
"Call Center"
$management = New-Object System.Management.Automation.Host.ChoiceDescription "&Management", `
"Management"
$billing = New-Object System.Management.Automation.Host.ChoiceDescription "&Billing", `
"Billing"
$options = [System.Management.Automation.Host.ChoiceDescription[]]($rn, $callcenter, $management, $billing)
$result = $host.ui.PromptForChoice($title, $message, $options, 0)
switch ($result)
{
0
{
"You selected RN."
$OU = "RN"
}
1
{
"You selected Call Center."
$OU = "CallCenter"
}
2
{
"You selected Management."
$OU = "Management"
}
3
{
"You Selected Billing."
$OU = "Billing"
}
}
$UName = Read-Host "What is the username you wanna give? Make sure it matches the username in the email."
$FName = Read-Host "What is the Full Name of the user?"
New-ADUser `
-Name $FName `
-Path "CN=Users,OU=$OU,DC=Domain,DC=com" `
-SamAccountName $UName `
-DisplayName $FName `
-AccountPassword (ConvertTo-SecureString "password1" -AsPlainText -Force) `
-ChangePasswordAtLogon $true `
-Enabled $true
Add-ADGroupMember "Users" "$UName";

Related

How can I get results from Get-ADUser Filter in my Powershell script so I can validate if that user exists or not correctly?

FIXED: I did have to change if ($null -eq $FoundUser) and then if essentiall NULL -eq NULL, that user doesn't exist...
SORRY
I would really love some help as I've on/off been struggling with this logic with Get-ADUser for user creation.
I'm using Powershell 7.0 - 7.2.1 (latter currently) and having this problem with VSCode and running it in "console". We have a 2008 R2 forest but 2016 and 2019 DCs.
Essentially "Get-ADUser -Filter" doesn't return any value. I'm trying to use an if statement for if $null -ne $SamAccountName.
Any thoughts?
I thought I found the answer here but no luck for me.
$Users = Import-Csv -delimiter "`t" -Path "C:\Users\michel_m\Documents\Scripts\PowerShell\Staff\StaffData.txt"
#$sam = ""
#Generate data to use in creating user below
foreach ($User in $Users) {
$SAMAccount = $User.Username
$Filter = "sAmAccountname -eq '$SamAccount'
$FoundUser = Get-ADUser -Filter $Filter
Write-Host "HERE IS" $FoundUser
$results = $FoundUser.SamAccountName
#if ($null -ne $FoundUser)
if ($null -ne $results)
{
Write-Host $results "Are the results"
Write-Host $User "is the user"
Write-Host $SAMAccount "Is the SAM user"
Write-Host $FoundUser "Is the found user"
#NewUser_Function
($Dates + " - " + $user.username + " has been created") | out-file -filepath $OutputFile1 -append
#Write-Host "Pause 15 seconds"
Start-Sleep 15
Write-Host $user.username + " Has been created"
$Body = $user.username + " Has been created"
#schtasks.exe /run /s "OHDC01" /tn "GADS Sync - Users"
}
else
{
Write-Host $Filter
Write-Host $results "Are the results"
Write-Host $User "is the user"
Write-Host $SAMAccount "Is the SAM user"
Write-Host $FoundUser "Is the found user"
Write-Host $null is null
write-host $user.username + " already exists"
($Dates + " - " + $user.username + " already exists") | out-file -filepath $OutputFile2 -append
$Body = $user.username + " already exists",
"\\OHDC01\C$\Scripts\StaffCreation\NewStaff\",
"\\OHDC01\C$\Scripts\StaffCreation\NewStaff\"
}
}
Output
HERE IS
sAmAccountname -like 'mangold_m' | Select-object SamAccountName
Are the results
#{FirstName=Michelle; LastName=Mangold; BuildingName=OAK; Position=Aide; Username=mangold_m; Email=mangold_m#Wonderfullife.org} is the user
mangold_m Is the SAM user
Is the found user
is null
mangold_m + already exists
HERE IS
sAmAccountname -like 'metzner_m' | Select-object SamAccountName
Are the results
#{FirstName=Melissa; LastName=Metzner; BuildingName=OHHS; Position=Aide; Username=metzner_m; Email=metzner_m#Wonderfullife.org} is the user
metzner_m Is the SAM user
Is the found user
is null
metzner_m + already exists
Thank you for updating you got your solution.
Here I also have tried from my side you can also use this small PowerShell script for validating the user existance.
$Users = Import-Csv -Path "C:\Users\RahulShaw\test.csv"
Foreach ($User in $Users){
$Username = $User.Username
$FoundUser = Get-ADUser -Filter "sAmAccountName -eq '$Username'"
$results = $FoundUser.SamAccountName
Write-Host $results
if($null -eq $FoundUser){
write-host "Username '$Username' does not yet exist in active directory"
}
else{
write-host "Username '$Username' exist in active directory"
}
}

delete windows.old remotely with powershell

at the moment in our company we are upgrading our windows 10 to the newest built. after the upgrade we have the windows.old folder directly under c: sometimes this folder is extremly big. how can i delete this folder remotely with powershell.
if i try to delete this folder with the explorer with \pc-name\c$ i don't have the permissions. now i want to get the acl for the folder and all subfolders with powershell but i only get the acl for the top folder. how can i get it working for the complete directory. is there any other way to delete windows.old remotly?
$computername = read-host "enter pc"
$script = {
# set ErrorAction to 'Stop' in order to catch errors
$oldErrorAction = $ErrorActionPreference
$ErrorActionPreference = 'Stop'
# you're now running this on the remote pc, so use local path
$path = Get-ChildItem -Directory -Path "C:\windows.old\" -recurse
try {
$acl = Get-Acl -path $path.FullName
$accessrule = [System.Security.AccessControl.FileSystemAccessRule]::new('username', 'FullControl', 'ContainerInherit,ObjectInherit', 'None', 'Allow')
$acl.SetAccessRule($accessRule)
$acl | Set-Acl -path $path.FullName
# output the message
"{0}`t{1} success" -f (Get-Date).ToString(), $env:COMPUTERNAME
}
catch {
"{0}`t{1} failed" -f (Get-Date).ToString(), $env:COMPUTERNAME
}
# restore previous ErrorAction
$ErrorActionPreference = $oldErrorAction
}
$result = Invoke-Command -ComputerName $computername -ScriptBlock $script
if ($result -ne $null)
{
write-host "sucess" -ForegroundColor "green"
}
else
{
write-host "no success" -ForegroundColor "red"
}

Powershell Get-Service report wrong information

I've created a powershell script to list all domain controllers under current trusted forest, and than check each individual server for specific services if it's running or not and send an email with report.
I found 2 issues so far.
Get-Service -name "MyService" -ComputerName $myComputer "will say no service is found with that name, but if I list all the services : Get-Service -ComputerName $myComputer it will say "This operation might require other privileges." This is a problem because I'm reporting that the service doesn't exist but it is actually there.
For some reason if I just run the powershell script from command line manually it lists way more servers and most of the info is correct. But I schedule the powershell script from windows task manager with that same account the information is all wrong and it reports way less servers.
Script:
#$domain = [system.directoryservices.activedirectory.domain]::GetCurrentDomain().Name
#$numerOfDomainControlers= nslookup $domain
Clear-Content .\log.txt
$startTime = Get-Date
$allDCs = ((Get-ADForest).Domains | %{ Get-ADDomainController -Filter * -Server $_ } | Where-Object { $_.hostname -notlike '*root*' }).hostname
foreach( $allDC in $allDCs){
$testConnection = Test-Connection $allDC -Quiet -Count 1 -ErrorAction SilentlyContinue
Write-Host
if($testConnection -like "true") {
$SyncStatus = Get-Service -name "MyServicesName" -ComputerName $allDC -ErrorAction SilentlyContinue
if($SyncStatus.length -eq 0) {
Write-Host "MyServicesName doesn't exists on:"$allDC
$SyncStatus = "MyServicesName doesn't exists on:" + $allDC
$logs = $SyncStatus |Out-File .\log.txt -Append
}
else{
write-host "MyServicesName on "$allDC "is: " $SyncStatus.status
$SyncStatus = "MyServicesName on " + $allDC + "is: " + $SyncStatus.status
$logs = $SyncStatus |Out-File .\log.txt -Append
}
}
else
{
Write-Host "Test Connection to Server failed:"$allDC
$SyncStatus = "Test Connection to Server failed:" + $allDC
$logs = $SyncStatus |Out-File .\log.txt -Append
}
}
$endTime = Get-Date
$totalTime = New-TimeSpan -start $startTime -end $endTime
Write-Host $totalTime
$logs = "Total Time in Seconds:" + $totalTime |Out-File .\log.txt -Append
#send Email
$logs = Get-Content .\log.txt
$serverName = $env:computername
$LogTime = Get-Date -Format "MM/dd/yyyy hh:mm:ss"
$FromAddress = "email.com"
$ToAddress = "email.com"
foreach($log in $logs)
{
$Messagebody = $messagebody + $log + "`r`n" |Out-String
}
[string] $MessageSubject ="Status Report runing on " + $serverName +" " + $endTime
$SendingServer = "server"
Send-MailMessage -to $ToAddress -from $FromAddress -subject $MessageSubject -smtpServer $SendingServer -body $Messagebody -Attachments .\log.txt

How to write all PowerShell screen output to .csv report file

Fig1 Fig2 While I know this is a similar to many other questions regarding this, however, I have been having a difficult time figuring out how to make what I see on the screen go to the output file. I'm using PowerShell Version 5.1.16299.1146. Fig1 image is what I see on the PS screen. I want the script to see if a particular file is present and if it is TRUE or FALSE, write the information to the .csv file. Fig2 image is what actually gets written to the .csv report. I want the computer Name, Results (TRUE/FALSE), and Users + LastWriteTime written to the .csv file if it is found in the user's AppDate location for each user on a particular machine.
Set-ExecutionPolicy Bypass
$javausers = #()
$env:COMPUTERNAME = HostName
$TestPath = "$env:userprofile\AppData\LocalLow\Sun\Java\Deployment\deployment.properties"
$TestResult = if ( $(Try { Test-Path $TestPath.trim() } Catch { $false }) ) { Write-Output "True - deployment.properties" } Else { Write-Output "False - Path not found" }
$users = Get-ChildItem c:\users
foreach ($user in $users)
{
$folder = "C:\users\" + $user + "$env:userprofile\AppData\LocalLow\Sun\Java\Deployment\deployment.properties"
if ( $(Try { Test-Path $TestPath.trim() } Catch { $false }) ) { Write-Output "True - deployment.properties" $users -join ','} Else { Write-Output "False - Path not found" $users-join ','}
}
$javauser = New-Object System.Object
$javauser | Add-Member -MemberType NoteProperty -Name "Computer Name" -Value $env:COMPUTERNAME
#$javauser | Add-Member -MemberType NoteProperty -Name "Java User" -Value $TestPath
$javauser | Add-Member -MemberType NoteProperty -Name "Results" -Value $TestResult
$javauser | Add-Member -MemberType NoteProperty -Name "Users" -Value $folder
#$javauser | Add-Member -MemberType NoteProperty -Name "Users" -Value $users
$javausers += $javauser
$javausers | Export-Csv -NoTypeInformation -Path "C:\Temp\JavaUsersList.csv" -Append
To read other users folders you'll need to RunsAsAdmin.
#Requires -RunAsAdministrator
## Q:\Test\2019\08\29\SO_57714265.ps1
Set-ExecutionPolicy Bypass
$env:COMPUTERNAME = HostName
$DeplPath = "AppData\LocalLow\Sun\Java\Deployment\deployment.properties"
$javausers = foreach ($User in Get-ChildItem C:\Users -Directory){
$folder = Join-Path $User.FullName $DeplPath
if (Test-Path $folder) {
$TestResult = "True - deployment.properties"
} Else {
$TestResult = "False - Path not found"
}
[PSCustomObject]#{
"Computer Name" = $env:COMPUTERNAME
"Results" = $TestResult
"Users" = $user.Name
}
}
$javausers
#$javausers | Export-Csv -NoTypeInformation -Path "C:\Temp\JavaUsersList.csv" -Append
Sample output:
Computer Name Results Users
------------- ------- -----
VBoxWin10 False - Path not found SomeOne
VBoxWin10 False - Path not found Public
VBoxWin10 True - deployment.properties LotPings

Run powershell script with elevated command

I have an autologon Powershell script that I'd like to run as admin when I double click on it. I tried to use different scripts but I'm out of luck.
For example:
Start-Process PowerShell –Verb RunAs
Would open another Powershell screen as administrator but without the original script that I wanna run which is:
net accounts /minpwlen:0
net user TPUser /add
Set-ItemProperty -Path 'HKLM:\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Winlogon' -Name AutoAdminLogon -Value 1
Set-ItemProperty -Path 'HKLM:\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Winlogon' -Name DefaultUserName -Value "TPUser"
Set-ItemProperty -Path 'HKLM:\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Winlogon' -Name DefaultPassword -Value ""
Set-ItemProperty -Path 'HKLM:\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Winlogon' -Name DefautDomainName -Value ""
copy c:\temp\OP.rdp c:\Users\Public\Desktop
pause
Any idea how can I get this to work ?
You are in luck because I was fighting with this issue for some time, what you need to do is make it take note of where it is at and when it starts back up the shell as an admin it needs to execute the script.
Function Test-IsAdmin {
[cmdletbinding()]
Param()
Write-Verbose "Checking to see if current user context is Administrator"
If (-NOT ([Security.Principal.WindowsPrincipal] [Security.Principal.WindowsIdentity]::GetCurrent()).IsInRole([Security.Principal.NTAccount] "[WriteGroupHere]"))
{
Write-Warning "You are not currently running this under an Administrator account! `nThere is potential that this command could fail if not running under an Administrator account."
Write-Verbose "Presenting option for user to pick whether to continue as current user or use alternate credentials"
#Determine Values for Choice
$choice = [System.Management.Automation.Host.ChoiceDescription[]] #("Use &Alternate Credentials","&Continue with current Credentials")
#Determine Default Selection
[int]$default = 0
#Present choice option to user
$userchoice = $host.ui.PromptforChoice("Warning","Please select to use Alternate Credentials or current credentials to run command",$choice,$default)
#$workingDir = $PSCommandPath
#$PSCommandPath
Write-Debug "Selection: $userchoice"
#Determine action to take
Switch ($Userchoice)
{
0
{
#Prompt for alternate credentials
Write-Verbose "Prompting for Alternate Credentials"
$Credential = Get-Credential
#Write-Output $Credential
#We are not running "as Administrator" - so relaunch as administrator
Start-Process powershell.exe -ArgumentList "$PSCommandPath" -Credential $Credential
#-WorkingDirectory $workingDir
exit
}
1
{
#Continue using current credentials
Write-Verbose "Using current credentials"
Write-Output "CurrentUser"
}
}
}
Else
{
Write-Verbose "Passed Administrator check"
#$Host.UI.RawUI.WindowTitle = "Custom Powershell Environment" +
#$Host.UI.RawUI.BackgroundColor = "DarkBlue"
}
}
with this just put it in the top of your script and call the function, and you will need to change the group that it checks to know if you are an admin or not, I was using an AD group to check since it was a more functional way for me.
I have used the following before to re-launch as script as admin but there is not stopping the UAC prompt:
function IsAdministrator
{
$Identity = [System.Security.Principal.WindowsIdentity]::GetCurrent()
$Principal = New-Object System.Security.Principal.WindowsPrincipal($Identity)
$Principal.IsInRole([System.Security.Principal.WindowsBuiltInRole]::Administrator)
}
function IsUacEnabled
{
(Get-ItemProperty HKLM:\Software\Microsoft\Windows\CurrentVersion\Policies\System).EnableLua -ne 0
}
#
# Main script
#
if (!(IsAdministrator))
{
if (IsUacEnabled)
{
[string[]]$argList = #('-NoProfile', '-NoExit', '-File', $MyInvocation.MyCommand.Path)
$argList += $MyInvocation.BoundParameters.GetEnumerator() | Foreach {"-$($_.Key)", "$($_.Value)"}
$argList += $MyInvocation.UnboundArguments
Start-Process PowerShell.exe -Verb Runas -WorkingDirectory $pwd -ArgumentList $argList
return
}
else
{
throw "You must be administrator to run this script"
}
}
I actually used this script on top of mine and it worked perfectly.
# ##########################################
# Determine if we have Administrator rights
Write-Host 'Checking user permissions... '
$windowsID = [System.Security.Principal.WindowsIdentity]::GetCurrent()
$windowsSecurityPrincipal = New-Object System.Security.Principal.WindowsPrincipal($windowsID)
$adminRole = [System.Security.Principal.WindowsBuiltInRole]::Administrator
If (!($windowsSecurityPrincipal.IsInRole($adminRole))) {
Write-Warning 'Current user does not have Administrator rights'
Write-Host 'Attempting to copy files to temporary location and restarting script'
# Get random file name
Do {
$temp = [System.IO.Path]::GetTempPath() + [System.IO.Path]::GetRandomFileName()
} Until (!(Test-Path -LiteralPath "$temp"))
# Create directory
Write-Host 'Creating temp directory... ' -NoNewLine
New-Item -Path "$temp" -ItemType 'Directory' | Out-Null
Write-Host 'done.'
# Copy script to directory
Write-Host 'Copying script to temp directory... ' -NoNewLine
Copy-Item -LiteralPath "$($myInvocation.MyCommand.Path)" "$temp" | Out-Null
Write-Host 'done.'
$newScript = "$($temp)\$($myInvocation.MyCommand.Name)"
# Start new script elevated
Write-Host 'Starting script as administrator... ' -NoNewLine
$adminProcess = New-Object System.Diagnostics.ProcessStartInfo
$adminProcess.Filename = ([System.Diagnostics.Process]::GetCurrentProcess()).Path
$adminProcess.Arguments = " -File `"$newScript`""
$adminProcess.Verb = 'runas'
Try {
[System.Diagnostics.Process]::Start($adminProcess) | Out-Null
}
Catch {
Write-Error 'Could not start process'
Exit 1
}
Write-Host 'done.'
Exit 0
}

Resources