I have an issue with setting an ACL to a folder using PowerShell. It seems I was able to get through my code without any errors, but the folder still does not appear in the Security properties of the folder. The other articles I looked at seemed to have answers, but then comments, if any, that it didn't work, and after trying what the answers suggested, it did not result in the group appearing in the System properties of the folder.
My script so far is as follows:
$domain="DOMAIN"
$tldn="net"
$pathArr=#()
$pathArr+=$path1=Read-Host -Prompt "Enter first path"
$pathArr+=$path2=Read-Host -Prompt "Enter second path"
[int]$projectNumber=try { Read-Host -Prompt "Enter project number" } catch { Write-Host "Not a numeric value. Please try again."; exit }
[string]$mainFolder=[string]${projectNumber}+"_"+(Read-Host -Prompt "Please give the main folder name")
$projectNumberString=[string]$projectNumber
$projectName=Read-Host -Prompt "Please give the project name"
$fullProjectName="${projectNumberString}_${projectName}"
$pathArr+=$path3="$path1\$mainFolder"
$pathArr+=$path4="$path2\$mainFolder"
$pathArr+=$path5="$path3\$fullProjectName"
$pathArr+=$path6="$path4\$fullProjectName"
# Region: Create organizational units in Active Directory
# Names
$ouN1="XYZOU"
$ouN2="ABCOU"
# Paths
$ouP0="DC=$domain,DC=$tldn"
$ouP1="OU=$ouN1,$ouP0"
$ouP2="OU=$ouN2,$ouP1"
Write-Host "Checking for required origanization units..."
try
{
New-ADOrganizationalUnit -Name $ouN1 -Path $ouP1
New-ADOrganizationalUnit -Name $ouN2 -Path $ouP2
}
catch
{
Out-Null
}
EDIT
As per Mickey's comment, I added this code to test the path of $path6'
if ( Test-Path -Path "$path6" )
{
Write-Host "$path6"
Write-Host "Path exists."
}
else
{
Write-Host "Path does not exist."
}
The result was that the path wrote to the host and said Path exists..
Write-Host "Creating AD Group..."
[string]$group="BEST_${projectNumberString}"
$groupdomain="$domain\$group"
$ADGroupParams= #{
'Name' = "$group"
'SamAccountName' = "$group"
'GroupCategory' = "Security"
'GroupScope' = "Global"
'DisplayName' = "$group"
'Path' = "OU=MyBusinessOU,DC=$domain,DC=$tldn"
'Description' = "Test share"
}
$secgroup=New-ADGroup #ADGroupParams
# Region: Set permissions
Write-Host "Setting permissions..."
# get permissions
$acl = Get-Acl -Path $path6
# add a new permission
$InheritanceFlags=[System.Security.AccessControl.InheritanceFlags]”ContainerInherit, ObjectInherit”
$FileSystemAccessRights=[System.Security.AccessControl.FileSystemRights]"Traverse","Executefile","ListDirectory","ReadData", "ReadAttributes", "ReadExtendedAttributes","CreateFiles","WriteData", 'ContainerInherit, ObjectInherit', "CreateDirectories","AppendData", "WriteAttributes", "WriteExtendedAttributes", "DeleteSubdirectoriesAndFiles", "ReadPermissions"
$InheritanceFlags=[System.Security.AccessControl.InheritanceFlags]”ContainerInherit, ObjectInherit”
$PropagationFlags=[System.Security.AccessControl.PropagationFlags]”None”
$AccessControl=[System.Security.AccessControl.AccessControlType]”Allow”
$permission = "$groupdomain", "$InheritanceFlags", "$PropagationFlags", "$AccessControl"
$rule = New-Object -TypeName System.Security.AccessControl.FileSystemAccessRule -ArgumentList $permission
$acl.SetAccessRule($rule)
# set new permissions
$acl | Set-Acl -Path $path6
I tried Set-Acl -ACLObject:$acl -Path:$path6 and that didn't work either.
Again, I am not getting any errors at all.
I am running PowerShell 4.0 in PowerShell ISE on Windows Server 2012 R2. I am logged in as Administrator.
If you have any ideas, I am open to them. To be clear, my goal is to add the $groupdomain to a folder called path6, and have the ACLs outlined here applied to that group.
Thank you for your help in advance.
Related
I am writing a script to check if each site/subsite has unique or inherited permissions. I am having an issue where HasUniqueRole is not doing what it is supposed to do, it just returns true or false but when I write it to host, nothing is printed. Any ideas why this isn't functioning properly or does it need to be loaded in first? If I put it into an if else statement, it prints that any website has inherited permissions.
$site = Read-Host -Prompt "Enter website URL"
Connect-PnPOnline -Url $site -UseWebLogin
$currentSubwebs = Get-PnPSubwebs -Recurse
foreach ($currentSubweb in $currentSubWebs) {
$subWebTitle = $currentSubWeb.Title
Write-Host $subWebTitle -ForegroundColor Red
$subSiteURL = $currentSubweb.Url
Write-Host $subSiteURL -ForegroundColor Green
Write-Host $currentSubweb.HasUniqueRoleAssignments
}
Change
$currentSubwebs = Get-PnPSubwebs -Recurse
to
$currentSubwebs = Get-PnpSubwebs -Recurse -Includes HasUniqueRoleAssignments
I am trying to write something that will prompt for a PC name and then remotely perform a folder permission change. Everything is chaotic looking but I am struggling with changing the execution policy after the Enter-PSSession - it seems it just gets stuck and won't proceed further to my function.
This is the rough draft of what I have thus far. Any help is appreciated.
$PromptedPC = Read-Host -Prompt "`n `n Enter PC Number"
Enter-PSSession -ComputerName $PromptedPC
Write-Host `n"Do you want to change folder permissions?" -ForegroundColor Green
$ReadAnswer = Read-Host " ( y / n ) "
PowerShell.exe -noprofile -ExecutionPolicy Bypass
switch ($ReadAnswer)
{
Y {
function Grant-userFullRights {
[cmdletbinding()]
param(
[Parameter(Mandatory=$true)]
[string[]]$Files,
[Parameter(Mandatory=$true)]
[string]$UserName
)
$rule=new-object System.Security.AccessControl.FileSystemAccessRule ($UserName,"FullControl","Allow")
foreach($File in $Files) {
if(Test-Path $File) {
try {
$acl = Get-ACL -Path $File -ErrorAction stop
$acl.SetAccessRule($rule)
Set-ACL -Path $File -ACLObject $acl -ErrorAction stop
Write-Host "Successfully set permissions on $File"
} catch {
Write-Warning "$File : Failed to set perms. Details : $_"
Continue
}
} else {
Write-Warning "$File : No such file found"
Continue
}
}
}
}
}
Grant-userFullRights -Files 'C:\ProgramData\New World Systems\' -UserName "BUILTIN\Users"
I did get the function information from: http://techibee.com/powershell/grant-fullcontrol-permission-to-usergroup-on-filefolder-using-powershell/2158
I am just trying to put something together that will work for a programdata folder our users need full control of that keeps reverting permissions to something lower than full access.
You start a new PowerShell with the ExecutionPolicy Bypass.
Sine you are already in PowerShell, the proper way to configure the Execution Polcy is Set-ExecutionPolicy.
However, since you don't invoke any script file, there is no need to change the Execution Policy.
I've used the following sites to help me get this far and to troubleshoot.
Download file from SharePoint
How to download newest file from SharePoint using PowerShell
Mike Smith's Tech Training Notes SharePoint, PowerShell and .Net!
Upload file to a SharePoint doc library via PowerShell
Download latest file from SharePoint Document Library
How to iterate each folders in each of the SharePoint websites using PowerShell
PowerShell's Get-ChildItem on SharePoint Library
I am trying to download random files from SharePoint folder, and I have it working for when I actually know the file name and extension.
Working code with name and extension:
$SharePoint = "https://Share.MyCompany.com/MyCustomer/WorkLoad.docx"
$Path = "$ScriptPath\$($CustomerName)_WorkLoad.docx"
#Get User Information
$user = Read-Host "Enter your username"
$username = "$user#MyCompany"
$password = Read-Host "Enter your password" -AsSecureString
#Download Files
$WebClient = New-Object System.Net.WebClient
$WebClient.Credentials = New-Object System.Net.Networkcredential($UserName, $Password)
$WebClient.DownloadFile($SharePoint, $Path)
However, I don't seem to be able to figure out how to do it with multiple files of unknown names or extensions.
I have tried mapping a drive, only to end up with "drive mapping failed" & "The network path was not found." errors:
$SharePoint = Read-Host 'Enter the full path to Delivery Site'
$LocalDrive = 'P:'
$Credentials = Get-Credential
if (!(Test-Path $LocalDrive -PathType Container)) {
$retrycount = 0; $completed = $false
while (-not $completed) {
Try {
if (!(Test-Path $LocalDrive -PathType Container)) {
(New-Object -ComObject WScript.Network).MapNetworkDrive($LocalDrive,$SharePoint,$false,$($Credentials.username),$($Credentials.GetNetworkCredential().password))
}
$Completed = $true
}
Catch {
if ($retrycount -ge '5') {
Write-Verbose "Mapping SharePoint drive failed the maximum number of times"
throw "SharePoint drive mapping failed for '$($SharePoint)': $($Global:Error[0].Exception.Message)"
} else {
Write-Verbose "Mapping SharePoint drive failed, retrying in 5 seconds."
Start-Sleep '5'
$retrycount++
}
}
}
}
I've also used the following code with similar results or no results at all.
#Get User Information
$user = Read-Host "Enter your username"
$username = "$user#MyCompany"
$password = Read-Host "Enter your password" -AsSecureString
#Gathering the location of the Card Formats and Destination folder
$Customer = "$SharePoint\MyCustomer"
$Products = "$Path\$($CustomerName)\Products\"
#Get Documents from SharePoint
$credential = New-Object System.Management.Automation.PSCredential($UserName, $Password)
New-PSDrive -Credential $credential -Name "A" -PSProvider "FileSystem" -Root "$SharePoint"
net use $spPath #$password /USER:$user#corporate
#Get PMDeliverables file objects recursively
Get-ChildItem -Path "$Customer" | Where-Object { $_.name -like 'MS*' } | Copy-Item -Destination $Products -Force -Verbose
Without defined "input parameters", it's not exactly clear the full solution you need so I'll provide a few snippets of PowerShell that should be of use based on what you've described.
I'll spare you the basics of the various OOTB functions (i.e. Get-SPWeb, etc) though can provide those details as well if needed. I've also been overly explicit in the scripting, though know some of these lines could be chained, piped, etc to be made shorter & more efficient.
This example will iterate over the contents of a SharePoint Library and download them to your local machine:
$Destination = "C:\YourDestinationFolder\ForFilesFromSP"
$Web = Get-SPWeb "https://YourServerRoot/sites/YourSiteCollection/YourSPWebURL"
$DocLib = $Web.Lists["Your Doc Library Name"]
$DocLibItems = $DocLib.Items
foreach ($DocLibItem in $DocLibItems) {
if($DocLibItem.Url -Like "*.docx") {
$File = $Web.GetFile($DocLibItem.Url)
$Binary = $File.OpenBinary()
$Stream = New-Object System.IO.FileStream($Destination + "\" + $File.Name), Create
$Writer = New-Object System.IO.BinaryWriter($Stream)
$Writer.write($Binary)
$Writer.Close()
}
}
This is pretty basic; the variables up top are where on your local machine you wish to store the download files ($Destination), the URL of your SharePoint Site/Web ($Web) and the name of the Document Library (Your Doc Library Name).
The script then iterates through the items in the Library (foreach ($DocLibItem in $DocLibItems) {}), optionally filters for say items with a .docx file extension and downloads each to your local machine.
You could customize this further by targeting a specific sub-folder within the Doc Library, filter by metadata or properties of the Docs or even iterate over multiple Sites, Webs and/or Libraries in one script, optionally filtering those based on similar properties.
Hi all I got the below script to download a file from TFS, using powershell script, but I need to download entire solution how can I achieve that
cls
$tfsCollectionUrl = New-Object System.URI("http://localhost:8080/tfs/defaultcollection");
[Microsoft.TeamFoundation.Client.TfsTeamProjectCollection] $tfsCollection = Get-TfsServer $tfsCollectionUrl
$VersionControl = $tfsCollection.GetService([Microsoft.TeamFoundation.VersionControl.Client.VersionControlServer])
$DestinationFile = [IO.Path]::GetTempFileName()
$VersionControl.DownloadFileByUrl('$/MyFirstProject/WebApplication1/WebApplication1/WebForm1.aspx.cs', $DestinationFile)
Invoke-Item $DestinationFile
Also this is not checking whether he is having permission to download , I would like to prompt for username and password instead of downloading directly. Can I achieve the same for bitbucket too if so how can I
The same code converted to powershell
connect to tfs and download the files present in it VS2010
For credential use the above logic
Write-Host "Enter source location "
$sourceLocation = Read-Host
$tfsCollectionUrl = New-Object System.URI($sourceLocation);
Write-Host "Enter server path "
$serverPath = Read-Host
Write-Host "Enter local path to download"
$localPath = Read-Host
[Microsoft.TeamFoundation.Client.TfsTeamProjectCollection] $tfsCollection = Get-TfsServer $tfsCollectionUrl
$VersionControl = $tfsCollection.GetService([Microsoft.TeamFoundation.VersionControl.Client.VersionControlServer])
$latest = [Microsoft.TeamFoundation.VersionControl.Client.VersionSpec]::Latest
$recursionType = [Microsoft.TeamFoundation.VersionControl.Client.RecursionType]::Full
try
{
foreach ($item in $VersionControl.GetItems($serverPath, $latest,$recursionType).Items)
{
$target = [io.path]::Combine($localPath,$item.ServerItem.Substring(2))
$exists=[System.IO.Directory]::Exists($target)
if($item.ItemType -eq "Folder" -and !$exists)
{
New-Item $target -Type Directory
}
if($item.ItemType -eq "File")
{
$item.DownloadFile($target)
}
}
Write-Host "`n Successfully downloaded all the files to the target folder: " $localPath -ForegroundColor Green
}
catch
{
$ErrorMessage = $_.Exception.Message
$FailedItem = $_.Exception.ItemName
Break
}
An easy way is to have a workspace mapping multiple projects and run the tf get command from Powershell.
You can also manage workspace with tf workspace command line.
The simple way is that:
Create a workspace
Map a workspace
Get all files.
Sample code:
$tfsCollectionUrl = New-Object System.URI("[team project collection url");
$username="[user name]"
$password="[password]"
$domain="[domain]"
$cret = new-object System.Net.NetworkCredential($username, $password, $domain)
$teamProjectCollection=new-object Microsoft.TeamFoundation.Client.TfsTeamProjectCollection($tfsCollectionUrl,$cret)
$teamProjectCollection.EnsureAuthenticated()
$VersionControl = $teamProjectCollection.GetService([Microsoft.TeamFoundation.VersionControl.Client.VersionControlServer])
$workspace = $VersionControl.CreateWorkspace("BasicSccExamplePS", $VersionControl.AuthorizedUser);
$workspace.Map("[file or folder server path, for example:$/TestTeam/FolderA]", "[local path]")
$workspace.Get()
You can find that it lets you to provide the credential, so you could let user to provide username, password, then connect to TFS with that account.
Regards
I have a question about Get-Acl in Powershell. I keep getting the error message, "Access to the path is denied". I want to change the owner of the folder to myself and then give myself full permissions to the folder using Powershell. Here's the line of code giving me the error:
$acl = Get-Acl "C:\SomeFolder"
I am using Windows Explorer to set the permissions on "SomeFolder" before running the script. They are as follows:
no entries in the access control list
owner is not myself
I do not receive the error message if I make myself the owner using the Windows Explorer GUI before running the Powershell script. I don't understand why I am allowed to change the owner with Windows Explorer but not using Powershell? I have full admin rights on this machine. Windows 7, Powershell 2.0, .NET 3.5.
I'm assuming the only way to change the owner is to use Get-Acl, set owner on the ACL, then use Set-Acl to write it back to the folder. If there is another way, please let me know? How can I change the owner of the folder using Powershell?
Windows Vista and up include a command-line tool named takeown.exe which can be used from an elevated command prompt (or elevated powershell console) to change the ownership of a file system object.
takeown /F "C:\SomeFolder" /R /D Y
should give you ownership on C:\SomeFolder and the file system objects it contains.
I have some system configuration scripts from our build guy and I recall a note about the Get-Acl command "not working well on certain paths".
# NOTE: This method does not work well?
#$acl = Get-Acl -Path $Path
The kinds of paths we were setting permissions on were empty folders created by an administrator user later captured in a disk image. This is the PowerShell command that we used instead.
$acl = (Get-Item $path).GetAccessControl("Access")
Oh, and it gets real obscure once you have an ACL object. I don't know if this is the best way to do it, but it's a snippet from the same script I refer to above.
$acl = (Get-Item $path).GetAccessControl("Access")
# Setup the access rule.
$allInherit = [System.Security.AccessControl.InheritanceFlags]"ContainerInherit", "ObjectInherit"
$allPropagation = [System.Security.AccessControl.PropagationFlags]"None"
$AR = New-Object System.Security.AccessControl.FileSystemAccessRule $user, $permissions, $allInherit, $allPropagation, "Allow"
# Check if Access already exists.
if ($acl.Access | Where { $_.IdentityReference -eq $User})
{
$accessModification = New-Object System.Security.AccessControl.AccessControlModification
$accessModification.value__ = 2
$modification = $false
$acl.ModifyAccessRule($accessModification, $AR, [ref]$modification) | Out-Null
}
else
{
$acl.AddAccessRule($AR)
}
Set-Acl -AclObject $acl -Path $Path
the above code worked great. wanted to post a tweak for recursively going through directory and filling in some "missing"
$HomeFolders = Get-ChildItem "put your directory root here" -Directory -recurse
foreach ($HomeFolder in $HomeFolders) {
$Path = $HomeFolder.FullName
$acl = (Get-Item $Path).GetAccessControl('Access')
$allInherit = [System.Security.AccessControl.InheritanceFlags]"ContainerInherit", "ObjectInherit"
$allPropagation = [System.Security.AccessControl.PropagationFlags]"None"
$permissions = "FullControl"
$Username = "<put your name here>"
$AR = New-Object System.Security.AccessControl.FileSystemAccessRule($Username, $permissions, $allInherit, $allPropagation, "Allow")
if ($acl.Access | Where { $_.IdentityReference -eq $Username})
{
$accessModification = New-Object System.Security.AccessControl.AccessControlModification
$accessModification.value__ = 2
$modification = $false
$acl.ModifyAccessRule($accessModification, $AR, [ref]$modification) | Out-Null
}
else
{
$acl.AddAccessRule($AR)
}
Set-Acl -path $Path -AclObject $Acl
}