powershell script
20 TopicsModifying NTFS Permissions Using the NTFSSecurity Module
Hi All, I am hoping someone can help me crack this issue. I have been tasked with changing the Access Rights on millions of files and folders for each user/group that has access to them currently. These will be set to Read,Execute,Delete as the highest access permissions granted. Anything less than that like List or Traverse will left as is. This I can do ok with 'where-object' etc. I am using the NTFSSecurity PowerShell module. My biggest issue is that when I use Get-NTFSAccess -Path \\Folder\I\am\Checking and output to the console or OGV, I get the following headers. Account Access Rights Applies to Type IsInherited InheritedFrom Contoso\TestAccount1 FullControl ThisFolderSubfoldersAndFiles Allow False Contoso\TestAccount2 Modify, Synchronize ThisFolderOnly Allow False Contoso\TestAccount3 Traverse ThisFolderAndFiles Allow False However, if I export to csv, I get the following headers. AccountType, Name, FullName, InheritanceEnabled, InheritedFrom, AccessControlType, AccessRights, Account, InheritanceFlags, IsInherited, PropagationFlags I know the InheritanceFlags refer to the Access Rights, but is it possible when using Add-NTFSAccess to read the InheritanceFlags values as I am doing with the other values and set them so that the “applies to this folder only, this folder and files, List”, etc are not changed from their current settings. So, this: AccessControlType AccessRights Account InheritanceFlags IsInherited PropagationFlags Allow FullControl Contoso\TestAccount1 ContainerInherit, ObjectInherit FALSE None Allow Modify, Synchronize Contoso\TestAccount2 ObjectInherit FALSE None Allow Traverse Contoso\TestAccount3 ContainerInherit FALSE None Would become this: AccessControlType AccessRights Account InheritanceFlags IsInherited PropagationFlags Allow Delete, ReadAndExecute, Synchronize Contoso\TestAccount1 ContainerInherit, ObjectInherit FALSE None Allow Delete, ReadAndExecute, Synchronize Contoso\TestAccount2 ObjectInherit FALSE None Allow Traverse Contoso\TestAccount3 ContainerInherit FALSE None Or This: Account Access Rights Applies to Type IsInherited InheritedFrom Contoso\TestAccount1 Delete, ReadAndExecute, Synchronize ThisFolderSubfoldersAndFiles Allow False Contoso\TestAccount2 Delete, ReadAndExecute, Synchronize ThisFolderOnly Allow False Contoso\TestAccount3 Traverse ThisFolderAndFiles Allow False And the "Applies to" settings would not change. If I create variables from the csv for each value required At the moment when I run the script that includes Add-NTFSAccess -Path $Fullname -Account $Account -AccessRights 'ReadAndExecute,Delete' -AccessType Allow -InheritanceFlags $InheritanceFlags Everything is set to ThisFolderSubFoldersAndFiles. If I could use the -AppliesTo instead of -InheritanceFlags and feed in exactly what is already present when displaying get-NTFSAccess in the console or OGV, I think this would resolve 99% of my issues. I have looked at apps like NTFS Permission Reporter, but I am sure this should be achievable with PS. I know there must be a simple solution, (Arrays, iCacls?) but I just cannot see how to do it. Any help would be awesome!Solved26KViews0likes6CommentsWARNING: The provided service principal secret will be included in the 'AzureRmContext.json' file
How do I fix the below? Thsi is windows server 2019 and I added everyone with full control permissions to .\Azure. VERBOSE: Loading module from path 'C:\Program Files\WindowsPowerShell\Modules\PackageManagement\1.0.0.1\PackageManagement.psd1'. VERBOSE: Loading 'FormatsToProcess' from path 'C:\Program Files\WindowsPowerShell\Modules\PackageManagement\1.0.0.1\PackageManagement.format.ps1xml'. VERBOSE: Loading module from path 'C:\Program Files\WindowsPowerShell\Modules\PackageManagement\1.0.0.1\Microsoft.PowerShell.PackageManagement.dll'. VERBOSE: Exporting cmdlet 'Find-Package'. VERBOSE: Exporting cmdlet 'Get-Package'. VERBOSE: Exporting cmdlet 'Get-PackageProvider'. VERBOSE: Exporting cmdlet 'Get-PackageSource'. VERBOSE: Exporting cmdlet 'Install-Package'. VERBOSE: Exporting cmdlet 'Import-PackageProvider'. VERBOSE: Exporting cmdlet 'Find-PackageProvider'. VERBOSE: Exporting cmdlet 'Install-PackageProvider'. VERBOSE: Exporting cmdlet 'Register-PackageSource'. VERBOSE: Exporting cmdlet 'Save-Package'. VERBOSE: Exporting cmdlet 'Set-PackageSource'. VERBOSE: Exporting cmdlet 'Uninstall-Package'. VERBOSE: Exporting cmdlet 'Unregister-PackageSource'. VERBOSE: Importing cmdlet 'Find-Package'. VERBOSE: Importing cmdlet 'Find-PackageProvider'. VERBOSE: Importing cmdlet 'Get-Package'. VERBOSE: Importing cmdlet 'Get-PackageProvider'. VERBOSE: Importing cmdlet 'Get-PackageSource'. VERBOSE: Importing cmdlet 'Import-PackageProvider'. VERBOSE: Importing cmdlet 'Install-Package'. VERBOSE: Importing cmdlet 'Install-PackageProvider'. VERBOSE: Importing cmdlet 'Register-PackageSource'. VERBOSE: Importing cmdlet 'Save-Package'. VERBOSE: Importing cmdlet 'Set-PackageSource'. VERBOSE: Importing cmdlet 'Uninstall-Package'. VERBOSE: Importing cmdlet 'Unregister-PackageSource'. WARNING: The provided service principal secret will be included in the 'AzureRmContext.json' file found in the user profile ( C:\Users\username01\.Azure ). Please ensure that this directory has appropriate protections. Connect-AzAccount : The provided account XXXXXXXXXXXXXXXXXXX does not have access to subscription ID "XXXXXXXXXXXXXXXXXXXXXXX". Please try logging in with different credentials or a different subscription ID. At C:\Packages\Application01\Publish-Application01.ps1:577 char:9 + if (Connect-AzAccount -Environment AzureXXXXXXXXX -ServicePrin ... + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + CategoryInfo : CloseError: (:) [Connect-AzAccount], PSInvalidOperationException + FullyQualifiedErrorId : Microsoft.Azure.Commands.Profile.ConnectAzureRmAccountCommand dsk11KViews0likes1CommentWith Graph API we are only getting 1000 devices
HI Team, We are using the below PowerShell script to change the Primary user of a device by checking the last logged in userid. Below is the github repo link which holds this PowerShell script and also the link of an article about the explanation of this script - https://raw.githubusercontent.com/svdbusse/IntuneScripts/master/PrimaryUser/Set-PrimaryUserfromLastLogIn.ps1 https://svdbusse.github.io/SemiAnnualChat/2020/03/21/Changing-Intune-Primary-User-To-Last-Logged-On-User.html The problem now is that we are only able to get 1000 devices in the $Devices variable in the above mentioned script and we have around 2000 devices so 1000 more devices are not getting fetched by this script. Also this script always get the device in the same pattern i.e.. if I run the script today and tomorrow then the devices will show the same pattern that is also the reason the rest 1000 devices are not getting fetched. Any solution to this issue will be a great help for me. Regards, Ashish AryaSolved9.5KViews0likes10CommentsHow to list azure resources which have inheriting access and direct access using powershell
Hi, Is it really possible to list azure resources which have inherited access and direct access using Powershell? I couldn't find any azure PowerShell command which shows at least any column which has this information. Can anyone help me here, please?Solved7.4KViews0likes5Commentsrunning an exe file from a sub folder of LocalAppData
I need to create a script that will run an .exe file to uninstall software on a users machine. I have created what I believe to be a simple code to do this, but as the .exe is in a sub folder of the users LOCALAPPDATA, my code only seems to go to the LOCALAPPDATA location and no further. Can anyone assist in where it is failing? This is what I have Start-Process -FilePath $env:LocalAppData +"\**Redact**\update.exe --uninstall -s"Solved5.2KViews0likes5CommentsHelp to troubleshoot script - Move files from subfolders to the newly created folder
Hello Everyone, I'm hoping someone here can review my script and provide insights into what might be causing it not to function correctly. Objective: The purpose of this script is as follows: Define the working folder. Inquire whether a new folder needs to be created. Create the specified folder and set it as the working directory. Perform a manual process where I move multiple folders into the newly created folder. Each of these folders contains files, and some may even have subfolders with additional files. Upon pressing Enter, I want the script to move all files from the subfolders to the root of the newly created folder (which is now the working directory). I have successfully implemented steps 1 to 4, but step 5 is not working as expected, and I'm seeking assistance in understanding why. What Actually happens: One of the files from the first director where the script running from and the script itself moves to the root of the newly created folder. Example of structure. Example.txt Example 2.txt -- Folder 1 -- Folder 2 -- Folder 3 | | --> New folder created | --> Folder 1 | --> Folder 2 | --> Folder 3 Additionally, if there's a more efficient way to achieve this goal, I am open to suggestions and improvements. I am pretty sure this is simple to solve. Your help and suggestions are greatly appreciated. Thank you. # Prompt the user to enter the working directory $workingDirectory = Read-Host "Enter the path of the working directory" # Check if the working directory exists if (Test-Path -Path $workingDirectory -PathType Container) { # Prompt the user if they want to create a new folder $createNewFolder = Read-Host "Do you want to create a new folder for the files? (Y/N)" if ($createNewFolder -eq 'Y' -or $createNewFolder -eq 'y') { # Prompt the user to enter the name of the new folder $newFolderName = Read-Host "Enter the name of the new folder" # Create the new folder under the working directory $newFolderPath = Join-Path -Path $workingDirectory -ChildPath $newFolderName New-Item -Path $newFolderPath -ItemType Directory -Force # Change the current working directory to the new folder Set-Location -Path $newFolderPath Write-Host "New folder '$newFolderName' created and set as the working directory." # Pause and wait for Enter key press Read-Host "Press Enter to continue..." # Move all files from subfolders to the new folder Get-ChildItem -Path $workingDirectory -File -Recurse | ForEach-Object { $destinationPath = Join-Path -Path $newFolderPath -ChildPath $_.Name Move-Item -Path $_.FullName -Destination $destinationPath -Force } Write-Host "Files moved to '$newFolderName' successfully." } else { Write-Host "No new folder created. Operation canceled." } } else { Write-Host "The working directory does not exist."Solved4.8KViews0likes9CommentsAdd a line to skip or continue loop execution
Hi I have a PS script which is terminating workflows in SharePoint. I don't want to run this script in one go rather I want to add user intervention as well. Below is my script portion. In line 44, I added a read host command to see which instance is being terminated. What I want is when I press yes then it executes the next command and terminate the workflow but if I press No then it skips the execution of next command and loop to next instance. How can I achieve that? Thanks Try{ #Setup the context $Ctx = New-Object Microsoft.SharePoint.Client.ClientContext($SiteURL) $Ctx.Credentials = New-Object Microsoft.SharePoint.Client.SharePointOnlineCredentials($Cred.Username, $Cred.Password) #Get the Web, List and List Item Objects $Web = $Ctx.Web $Ctx.Load($Web) $List = $Web.Lists.GetByTitle($ListName) $ListItems = $List.GetItems([Microsoft.SharePoint.Client.CamlQuery]::CreateAllItemsQuery()) $Ctx.Load($List) $Ctx.Load($ListItems) $Ctx.ExecuteQuery() #Initialize Workflow Manager and other related objects $WorkflowServicesManager = New-Object Microsoft.SharePoint.Client.WorkflowServices.WorkflowServicesManager($Ctx, $Web) $WorkflowSubscriptionService = $workflowServicesManager.GetWorkflowSubscriptionService() $WorkflowInstanceService = $WorkflowServicesManager.GetWorkflowInstanceService() $WorkflowAssociations = $WorkflowSubscriptionService.EnumerateSubscriptionsByList($List.Id) $Ctx.Load($WorkflowAssociations) $Ctx.ExecuteQuery() #Loop through each List Item ForEach($ListItem in $ListItems) { #Get Workflow Instances of the List Item $WorkflowInstanceCollection = $WorkflowInstanceService.EnumerateInstancesForListItem($List.Id, $ListItem.Id) $Ctx.Load($WorkflowInstanceCollection) $Ctx.ExecuteQuery() #Get all Workflow Instances in progress ForEach ($WorkflowInstance in $WorkflowInstanceCollection | Where {$_.Status -eq "Suspended"}) { [PSCustomObject] @{ ItemID = $ListItem.ID Status = $WorkflowInstance.Status WorkflowStarted = $WorkflowInstance.InstanceCreated WorkflowAssociation = $WorkflowAssociations | where {$_.ID -eq $WorkflowInstance.WorkflowSubscriptionId} | Select -ExpandProperty Name ItemUrl = "$($Web.Context.Web.Url)/$($workflowInstance.Properties["Microsoft.SharePoint.ActivationProperties.CurrentItemUrl"])" StartedBy = $workflowInstance.Properties["Microsoft.SharePoint.ActivationProperties.InitiatorUserId"] } $WorkflowInstanceService.TerminateWorkflow($WorkflowInstance) Read-Host -Prompt "Do you want to Terminate this instance:" $Ctx.ExecuteQuery() Write-host -f Green "'$($WorkflowAssociations | where {$_.ID -eq $WorkflowInstance.WorkflowSubscriptionId} | Select -ExpandProperty Name)'is Terminated" } } } Catch { Write-host -f Red "Error:" $_.Exception.Message }Solved4.4KViews0likes7CommentsAlternative to invoke-expression
I am looking for alternate way to extract the value of the below powershell object without using invoke-expression invoke-expression "`$abc.properties.$subprop" or invoke-expression "`$abc.$subprop1" Where $abc is a powershell object in JSON format $subprop is having one of the Noteproperties of '$abc.properties'3.9KViews0likes1Commentpowershell script to copy duplicate rows in one excel file to another excel file
How find duplicate Values In Excel and Export Rows to another sheet using PowerShell. I had an excel sheet with multiple rows and column lets say from A to K. I need to find duplicate rows only if values in all the columns in a row are unique. And the script should ignore D,E,F columns even though those column's values are same. The script should also copy all those duplicate rows and should paste in a new excel file. Also attaching a sample image of input file. Can any one help me on this. Thanks in advance. Note: I don't need unique rows I need only duplicate rows as an output and the output should also contain source duplicated row.i need output as 2 to 7 in this scenario(picture attached). the original file has 1lac rows like this. This attached one is just reference file3.3KViews0likes1CommentThe term <function-name> is not recognized as the name of a cmdlet, function, ...
This is my code. I'm trying to unzip files, edit them, and zip them back. For some reason functions DeGZip-File and GZip-File are not being recognized. Could anyone point out what could be wrong here? Function DeGZip-File { [CmdletBinding()] param($infile) $infile $outfile = ($infile -replace '\.gz$','') try { $input = New-Object System.IO.FileStream $inFile, ([IO.FileMode]::Open), ([IO.FileAccess]::Read), ([IO.FileShare]::Read) $output = New-Object System.IO.FileStream $outFile, ([IO.FileMode]::Create), ([IO.FileAccess]::Write), ([IO.FileShare]::None) $gzipStream = New-Object System.IO.Compression.GzipStream $input, ([IO.Compression.CompressionMode]::Decompress) $buffer = New-Object byte[](1024) while($true){ $read = $gzipstream.Read($buffer, 0, 1024) if ($read -le 0){break} $output.Write($buffer, 0, $read) } return $outfile } catch { Write-Host "$_.Exception.Message" -ForegroundColor Red } finally { $gzipStream.Close() $output.Close() $input.Close() } } #Zip them back after adding the headers Function Gzip-File { [CmdletBinding()] param($outfile) $srcFile = Get-Item -Path $outfile $newFileName = "$($srcFile.FullName).gz" try { $srcFileStream = New-Object System.IO.FileStream($srcFile.FullName,([IO.FileMode]::Open),([IO.FileAccess]::Read),([IO.FileShare]::Read)) $dstFileStream = New-Object System.IO.FileStream($newFileName,([IO.FileMode]::Create),([IO.FileAccess]::Write),([IO.FileShare]::None)) $gzip = New-Object System.IO.Compression.GZipStream($dstFileStream,[System.IO.Compression.CompressionMode]::Compress) $srcFileStream.CopyTo($gzip) } catch { Write-Host "$_.Exception.Message" -ForegroundColor Red } finally { $gzip.Dispose() $srcFileStream.Dispose() $dstFileStream.Dispose() } } $headerProcess = { #param($file,$headerArray) $file = $folder + "\" + $file $unZippedFile = DeGZip-File($file) $unZippedFile[1] $unZippedFile = $unZippedFile[1] $filedata = import-csv $unZippedFile -Header $headerArray $filedata | export-csv $unZippedFile -NoTypeInformation GZip-File $unZippedFile } function Add-Headers([string]$folder, [string]$schemaFilePath){ if($schemaFilePath -eq 'TallOptionsSchema.txt') { $tallOptionsSchema = Get-Content $schemaFilePath $strArray = [string[]]$tallOptionsSchema $headerArray = $strArray -join "`t" } else { $JSONFromFile = Get-Content -Raw -Path $schemaFilePath | ConvertFrom-Json $header = $JSONFromFile.schema.name $strArray = [string[]]$header $headerArray = $strArray -join "`t" } $filesToModify = Get-ChildItem $folder -Recurse -File foreach ($file in $filesToModify) { Start-Job -Name $file.Name -ScriptBlock $headerProcess -ArgumentList ($file,$headerArray) } } $folderPath = 'D:\Working\options' $schemafile = 'D:\Working\options\schema.json' Add-Headers $folderPath $schemafile Get-Job # Wait for it all to complete While (Get-Job -State "Running") { Start-Sleep 10 } # Getting the information back from the jobs Get-Job | Receive-Job Get-Job | remove-job -ForceSolved2.1KViews0likes1Comment