Applying NTFS permissions for groups on a trusted domain - powershell

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?

Related

Connecting to remote machine from PowerShell

I am trying to copy files from one domain to a remote machine in another domain. I want to use constant credentials. No matter what I tried, it doesn't work. I can ping to the remote machine only via IP and not by hostname.
$labname='L1681'
$remoteComputer = "10.32.22.157"
$username = "$labname\Administrator"
$password = ConvertTo-SecureString "password" -AsPlainText -Force
$creds = new-object -typename System.Management.Automation.PSCredential -argumentlist $username, $password
$session = New-PSSession -ComputerName $remoteComputer -Credential $creds
$Source = "\\...\folder"
$Destination = "\\$remoteComputer\c$\Users\Administrator\Desktop"
New-Item -ItemType Directory -Path $Destination -Force
Copy-Item -Path $Source -Recurse -Destination $Destination -Force -ToSession $session
I tried to replace the $labname with $remoteComputer. Each time I get a different error:
Enter-PSSession : Connecting to remote server 10.32.22.157 failed with the following error message : The WinRM client cannot process the request. Default authentication may be used with an IP address under the following conditions:
the transport is HTTPS or the destination is in the TrustedHosts list, and explicit credentials are provided. Use winrm.cmd to configure TrustedHosts. Note that computers in the TrustedHosts list might not be authenticated. For more
information on how to set TrustedHosts run the following command: winrm help config. For more information, see the about_Remote_Troubleshooting Help topic.
At line:1 char:1
+ Enter-PSSession -ComputerName $remoteComputer -Credential $creds
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidArgument: (10.32.22.157:String) [Enter-PSSession], PSRemotingTransportException
+ FullyQualifiedErrorId : CreateRemoteRunspaceFailed
I hope someone can help me with that, is there a way to know when the copy if finished, once it works? Also, how can I run a .bat file in a remote machine?
You can try this script which establishes a remote connection to a VM and copy a text file from the Local directory to that Remote VM.
#Provide the Remote VM Username and Password
$myPwd="Your VM Password"
$username="VM Username"
$password = ConvertTo-SecureString $myPwd -AsPlainText -Force
$credentials= New-Object System.Management.Automation.PSCredential ($username, $password)
#Create a remote session to that VM
$Session = New-PSSession -ComputerName FQDN/IP -Credential $credentials
#Check the content to the Local File that will be copied to Remote
Get-Content -Path "C:\LocalFolder\File.txt"
#Create a folder named *RemoteFolder* then copy the local file to that Folder
Invoke-Command -Session $Session -ScriptBlock {cd C:\; mkdir RemoteFolder}
Copy-Item –Path "C:\LocalFolder\File.txt" –Destination "C:\RemoteFolder\" –ToSession $Session
#Check the content of the copied file
Invoke-Command -ScriptBlock { Get-Content -Path "C:\RemoteFolder\File.txt" } -Session $Session
The screenshot of the output after running this script:

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

Powershell get current DOMAIN OR COMPUTER NAME\USER and the difference between the two

I'm making a script for registering my API as a windows service. I followed this guide here and filled it to the best of my ability since i'm new to PS:
$acl = Get-Acl "$PSScriptRoot"
$aclRuleArgs = {DOMAIN OR COMPUTER NAME\USER}, "Read,Write,ReadAndExecute", "ContainerInherit,ObjectInherit", "None", "Allow"
$accessRule = New-Object System.Security.AccessControl.FileSystemAccessRule($aclRuleArgs)
$acl.SetAccessRule($accessRule)
$acl | Set-Acl "$PSScriptRoot"
New-Service -Name MyAPIService -BinaryPathName $PSScriptRoot\MyAPIService.exe -Credential {DOMAIN OR COMPUTER NAME\USER} -Description "API" -DisplayName "API Service" -StartupType Automatic
What I would like to know is how would i get the current domain or computer name, like i get the current directory with $PSScriptRoot. The service would be running on Windows 10. I also don't know whether i should use the domain or computer name\user? In what situation would i need one or the other?
EDIT: With #Patrick help I made it work, here is the working script:
$acl = Get-Acl "$PSScriptRoot"
$aclRuleArgs = "$env:COMPUTERNAME\$env:USERNAME", "Read,Write,ReadAndExecute", "ContainerInherit,ObjectInherit", "None", "Allow"
$accessRule = New-Object System.Security.AccessControl.FileSystemAccessRule($aclRuleArgs)
$acl.SetAccessRule($accessRule)
$acl | Set-Acl "$PSScriptRoot"
New-Service -Name MyAPIService -BinaryPathName $PSScriptRoot\MyAPIService.exe Description "API" -DisplayName "API Service" -StartupType Automatic
Take a look here:
About Environment Variables
$env:COMPUTERNAME
$env:USERNAME
$env:USERDNSDOMAIN
About the user:
Is it a local or a domain user? If local, use 'COMPUTERNAME\USERNAME'. Otherwiese 'DOMAIN\USERNAME'
[System.Security.Principal.WindowsIdentity]::GetCurrent().Name
It should include computer or domain name - so no need to build these yourself.
This is for the currently logged in user however - just like the environmental variables you've been advised to use in other places.
Furthermore - it can't be edited by simply overwriting the environmental variable.

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

Script to Create Home Drives

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.