Skip to main content

Create shared folder

This is a script specifically for creating a shared folder called C:\acronis and then making a local user called acronis and giving it full access to C:\acronis:

# Define the folder path
$folderPath = "C:\acronis"

# Check if the folder exists; if not, create it
if (-not (Test-Path -Path $folderPath)) {
try {
New-Item -ItemType Directory -Path $folderPath -Force
Write-Host "Folder '$folderPath' created successfully."
} catch {
Write-Host "Error creating folder '$folderPath': $_"
exit 1
}
} else {
Write-Host "Folder '$folderPath' already exists."
}

# Define the local user details
$username = "acronis"
$password = "Acronis123!"

# Check if the user already exists
if (-not (Get-LocalUser -Name $username -ErrorAction SilentlyContinue)) {
try {
# Create the user if it doesn't exist
$securePassword = ConvertTo-SecureString $password -AsPlainText -Force
New-LocalUser -Name $username -Password $securePassword -AccountNeverExpires -UserMayNotChangePassword
Write-Host "User '$username' created successfully."
} catch {
Write-Host "Error creating user '$username': $_"
exit 1
}

# Wait for the user to be fully recognized by the system
Start-Sleep -Seconds 5

# Retry adding the user to the 'Users' group
try {
Add-LocalGroupMember -Group "Users" -Member $username
Write-Host "User '$username' added to the 'Users' group successfully."
} catch {
Write-Host "Error adding user '$username' to the 'Users' group: $_"
exit 1
}
} else {
Write-Host "User '$username' already exists."
}

# Set the folder permissions to allow full control for the 'acronis' user
try {
$userNTAccount = [System.Security.Principal.NTAccount]::new($username)
$acl = Get-Acl $folderPath
$accessRule = New-Object System.Security.AccessControl.FileSystemAccessRule($userNTAccount, "FullControl", "ContainerInherit,ObjectInherit", "None", "Allow")
$acl.SetAccessRule($accessRule)
Set-Acl $folderPath $acl
Write-Host "Folder permissions set successfully for user '$username', including write access."
} catch {
Write-Host "Error setting folder permissions for user '$username': $_"
exit 1
}

Write-Host "The folder '$folderPath' has been created, and user '$username' has full control, including write access."