Script to Create Home Drives - powershell

I am trying to create a small script that creates a folder on our file server, creates the share, sets the ACLs on the share, then maps the share to their U: drive via Home Folder in Active Directory.
The server is running 2012 R2, the Active Directory PowerShell Module is installed.
This is what I have thus far:
$session = new-pssession -ComputerName fileserver
Enter-PSSession $session
$user = read-host 'Input username'
import-module activedirectory
new-item -name $user -itemtype Directory -path "\\fileserver\G$" | out-null
new-smbshare -name "$user$" -path "G:\$user" -ContinuouslyAvailable $true -FullAccess "domain\domain admins" -changeaccess "domain\$user"
Set-ADuser $user -homedirectory "\\fileserver\$user$" -homedrive U:
I read using the Enter-PSSession command doesn't allow remote commands to pass through, and that instead you needed to use Invoke-Command -ScriptBatch.
It is telling me the share is already created, even though it is not. Any ideas?

You don't need a remote session for any of your commands, provided the RSAT are installed on your client (so that Set-ADUser is available locally). New-SmbShare can be run against a remote host using the -CimSession parameter.
However, I would strongly recommend against sharing each userhome individually. Instead share just the folder containing the userhomes (e.g. \\fileserver\userhomes$) and set the home directory to the user folder below that share:
$user = Read-Host 'Input username'
$userhome = New-Item -Name $user -Type Directory -Path "\\fileserver\userhomes$"
$acl = Get-Acl -Path $userhome.FullName
$acl.SetAccessRuleProtection($true, $true)
$perm = $user,'FullControl','ContainerInherit','ObjectInherit','None','Allow'
$ace = New-Object Security.AccessControl.FileSystemAccessRule $perm
$acl.SetAccessRule($ace)
$acl | Set-Acl -Path $userhome.FullName
Import-Module ActiveDirectory
Set-ADuser $user -HomeDirectory $userhome.FullName -HomeDrive 'U:'
Enable access-based enumeration on the share to present users with only those folders they can actually access.

Related

Home Drive Creation Issue

I have PowerShell a script to create a new user's home drive and I am using below command:
Set-ADUser $User -HomeDrive $driveLetter -HomeDirectory $fullPath
It's creating the home drive for the user but the user isn't able to access it.
One more thing, I can copying the created home drive manually from AD console and again pasting it and clicking on apply then it works fine.
Set-ADUser will only modify the user object in ActiveDirectory; security permissions on the folder itself is an additional step.
FileSystemRights Enumeration: MSDN
It is not sufficient to simply use Set-ADUser, expecting full end to end creation of a fully functioning home directory; we must set permissions on the folder in question, including any inheritance flags.
There's a few steps to accomplish this, but simply stated:
We need to get the current access control list (ACL)
We need to add our desired permissions to said ACL
We need to write the new ACL, combining both the pre-existing and new permissions.
As you may have guessed:
Get-ACL
Set-ACL
We can so something like this:
Set-ADUser $User -HomeDrive $driveLetter -HomeDirectory $fullPath -ea Stop
$homeShare = New-Item -path $fullPath -ItemType Directory -force -ea Stop
$acl = Get-Acl $homeShare
$FileSystemRights = [System.Security.AccessControl.FileSystemRights]"Modify"
$AccessControlType = [System.Security.AccessControl.AccessControlType]::Allow
$InheritanceFlags = [System.Security.AccessControl.InheritanceFlags]"ContainerInherit, ObjectInherit"
$PropagationFlags = [System.Security.AccessControl.PropagationFlags]"InheritOnly"
$AccessRule = New-Object System.Security.AccessControl.FileSystemAccessRule ($User.SID, $FileSystemRights, $InheritanceFlags, $PropagationFlags, $AccessControlType)
$acl.AddAccessRule($AccessRule)
Set-Acl -Path $homeShare -AclObject $acl -ea Stop
If you're feeling creative, you can also combine some of the flags into an array:
$InheritanceFlag = #('ContainerInherit','ObjectInherit')
Please note this code is NOT tested and to validate before executing in any environment.

Applying NTFS permissions for groups on a trusted domain

I'm trying to write a script to repermission some data on our file servers to add groups from a trusted domain. At the moment I have:
$dc="domaincontroller.organization.com"
creds=get-credential
New-PSDrive -Name TRUSTEDDOM -PSProvider ActiveDirectory -Server $dc -root "//RootDSE/" -Credential $creds
$folder="\\testserver\testshare\testfolder"
$Group = Get-ADgroup -identity "AD_Group" -Server $dc -credential $creds
$acl = Get-ACL -Path $folder
$rule = New-Object System.Security.AccessControl.FileSystemAccessRule($group,"FullControl","ContainerInherit,ObjectInherit","None","Allow")
$acl.setaccessrule($rule)
set-acl $folder $acl
I keep getting
Exception calling "SetAccessRule" with "1" argument(s): "Some or all identity references could not be translated."
This is my first time trying to work on cross domain permissioning on Powershell so I may be getting something fundamentally wrong. Is anybody able to assist?

PowerShell Access Network Share In Script As Different User

I am trying to access a domain network share in my PowerShell script that is currently running as NETWORK SERVICE. I have a domain user credential configured below.
$secStringPassword = ConvertTo-SecureString "password" -AsPlainText -Force
$shareCredential = New-Object System.Management.Automation.PSCredential ("DOMAIN\Username", $secStringPassword)
I would like to be able to run the following commands in the PowerShell script as the user specified above.
New-Item -Path "\\SERVER\Share\Folder" -ItemType Directory
Get-ChildItem "\\SERVER\Share\Folder"
Running the below is showing as not supported:
New-Item -Path "\\SERVER\Share\Folder" -ItemType Directory -Credential $shareCredential
"The New-Item cmdlet creates a new item and sets its value" If you're trying to connect to a share as a different user I suggest using new-psdrive first to create a mount as that user. This mounts that share as a drive so that it behaves more like a local location than a UNC path
New-PSDrive -Name "ShareNAME" -PSProvider "FileSystem" -Root "\\Server\Share" -Credential $shareCredential
New-Item -Path ShareNAME:\Folder -ItemType Directory -Credential $shareCredential
Get-ChildItem ShareNAME:\Folder -Credential $shareCredential

Move-Item Failure, move doesnt appear in destination directory no error

I have written the below script for a WebDav share on a public website. The intention is to list all PDF from a internal network share and move files to the WebDAV share on the website. I can confirm both New-PSDrive mapping are successful. I then move files and the file are removed from source but do not appear in destination.
I am trying to find fault when no error presented. As WebDAV share and not used this before is there something I am missing in logic here ?.
In move Item I have also tried adding the $Path1 then -Destination and $Path but fails. I modify script for local session path like C:\Temp and works fine. Suspect something different for WebDAV Shares.
$user = "webdav"
$pass = convertto-securestring -String 'WebDAV Password' -AsPlainText -Force
$cred = New-Object -typename System.Management.Automation.PSCredential($user,$pass)
$user1 = "Domain Account"
$pass1 = convertto-securestring -String 'DOMAIN PASSWORD HERE' -AsPlainText -Force
$cred1 = New-Object -typename System.Management.Automation.PSCredential($user1,$pass1)
[String]$path = '\\constoso.com#SSL/Dav/PDF'
[String]$path1 = '\\Domain\corpdata\PDF'
New-PSDrive -Name WebSite -PSProvider FileSystem -Root $path -Credential $cred
New-PSDrive -Name FilePath -PSProvider FileSystem -Root $path1 -Credential $cred1
Get-ChildItem -Path FilePath: -Include *.pdf -Recurse | Move-Item -Destination $path
No error reported files are not in destination when using WebDAV share can confirm in Get-PSDrive they are successfully mapped and accessible. Move appears to remove from source but not present in destination.
As you are working with PSDrive cmdlets you'll have to specify the 'Provider' info. In your case the UNC paths belong to the 'Filesystem' provider. So, try changing your 'path' variables like the below,
[String]$path = 'Filesystem::\\constoso.com#SSL\Dav\PDF'
[String]$path1 = 'Filesystem::\\Domain\corpdata\PDF'
Cheers!
~K

Powershell Remote file copy is not working

I am trying to copy files remotely on several IIS servers from one source server.
sourcepath is a UNC path like \\server\c$\path\ and destinationpath is a local folder c:\data\destination\
The strange thing is when I run this on the local server this will work perfectly.
$cmd = $sqlConnection.CreateCommand()
$cmd.CommandText ="SELECT * from infrastructure"
$Serverinfo = $cmd.ExecuteReader()
try
{
while ($Serverinfo.Read())
{
$servername = $Serverinfo.GetValue(1)
$location = $Serverinfo.GetValue(2)
#Invoke-Command -ComputerName $servername { new-item -Path $Using:destinationpath -name $Using:versionnumber -Itemtype directory }
Invoke-Command -ComputerName $servername { Copy-Item -Path $Using:sourcepath -destination $Using:destinationpath }
#Invoke-Command -ComputerName $servername {Import-Module WebAdministration ; New-WebApplication -force -Site "Default Web Site" -Name $Using:versionnumber -PhysicalPath $Using:destinationpath$Using:versionnumber }
}
}
What you have posted is incomplete without a catch block and source and destination path defined as others said.
But what I can see here as a possible cause even if you mention all above three constrains.
You will face issues with credential delegation . You are remoting to one server using PSRP and copying one file to that machine and you are taking your source file from a UNC path which requires some authentication.
I could give you two better alternatives, of course 1st once could be the proper solution.
If you are in PS 5.o or later, you can use -ToSession parameter of Copy-Item cmdlet.
$Session = New-PSSession -ComputerName $ServerName
Copy-Item -SourcePath \\\Server\c$\path -Destination c:\data\Destination-ToSession $Session
For more info Get-Help Copy-Item
Edit:
The second one:
Copy-Item -Path <Sourcepath> -DestinationPath \\destinataionserver\c$\folder
from source to the destination by accessing the shared folder of the destination system.