Scripts/FilesAndFolders.ps1


[CmdletBinding()]
param (

)

if (!(Get-Module NTFSSecurity -ListAvailable)) {
    Install-Module -Name NTFSSecurity -Force
}

# Variables
$Root = "C:\"
$Dir = "TestShare"
$Path = Join-Path -Path $Root -ChildPath $Dir
$Owner = ".\Administrators"
$ShareFullAccess = "Everyone"

# Remove old stuff
# Remove-SmbShare -Name $Dir -Force
# Remove-Item $Path -Force -Recurse -ea 0
# Write-Host "SMB Share and directory $($Path) removed" -ForegroundColor Yellow
# Start-Sleep 2



# New directory
New-Item $Path -ItemType Directory -Force | Out-Null

# Create file and folder structure
foreach ($l in (1..10)) {
    $NewDir = Join-Path $Path $l
    New-Item $NewDir -ItemType Directory -ea 0 | Out-Null
    foreach ($i in (1..10)) {
        $NewFile = "$(Join-Path $NewDir $i).txt"
        New-Item $NewFile -ItemType File -Value $i -ea 0 | Out-Null
    }
}
Write-Host "Directory $($Path) and folder structure created" -ForegroundColor Yellow


# New share
if (Get-SmbShare $Dir -ea 0) {
    Write-Host "Share $Dir already exists" -ForegroundColor Yellow
} else {
    New-SmbShare -Name $Dir -Path $Path -FullAccess $ShareFullAccess | Out-Null
    Write-Host "SMB Share $($Path) created" -ForegroundColor Yellow
}


# Set NTFS Permissions

Set-NTFSOwner -Path $Path -Account $Owner
Write-Host "Owner for `"$($Path)`" set to $($Owner)" -ForegroundColor Yellow
Get-ChildItem $Path -Recurse | ForEach-Object {
    Set-NTFSOwner -Path $_.Fullname -Account $Owner
    # Write-Host "Owner for `"$($_.Fullname)`" set to $($Owner)" -ForegroundColor Yellow
}

Disable-NTFSAccessInheritance -Path $Path
Write-Host "NTFS inheritance disabled" -ForegroundColor Yellow
Add-NTFSAccess -Path $Path -Account $Owner -AccessRights FullControl -AccessType Allow
Add-NTFSAccess -Path $Path -Account "SYSTEM" -AccessRights FullControl -AccessType Allow
Write-Host "Added $Owner and SYSTEM accounts to ACL" -ForegroundColor Yellow


# Set Read-only property to false
# (Get-Item $Path).IsReadOnly = $false
foreach ($item in (Get-ChildItem $Path -Recurse)) {
    # Unset readonly
    $FileObj = Get-Item -Path $item.Fullname
    if ($FileObj.IsReadOnly) {
        $FileObj.IsReadOnly = $false
        Write-Host "Property read-only removed from: $($item.fullname)" -ForegroundColor Yellow
    }
}


# Open in Explorer
# explorer.exe $Path