powershell script
24 TopicsScript to take accounts in security group with a prefixt, strip prefix, and add accounts to DL
I have a security group with accounts that are formatted with a prefix, such as AB-(sAMAccountName). I need to query the group (easy enough), then remove the first 3 characters in the string. Then use the resulting string (which is now sAMAccountName) to populate a DL. I can do all 3 things separately, but I cannot do them together. I appreciate any help. $users = Get-ADGroupMember -Identiy "Security Group" | Select-Object Name Foreach ($user in $users) { $sAMAccountName = $user.SubString(3) Add-DistibutionGroupMember -Identity "group name" -Member $sAMAccountName } Am I close?552Views0likes1CommentHelp 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.9KViews0likes9CommentsWith 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.5KViews0likes10CommentsThis script doesn't work if you double-click it. However the command inside the script works perfect
I created a Powershell script with only one command. The command is the one I show below and it works perfectly if you run the command from the Powershell console. This is the command: [System.Net.ServicePointManager]::SecurityProtocol = [System.Net.SecurityProtocolType]::Tls12; However, I created a Powershell script (.ps1) with this only command inside and if I try to run it (double-click on this .ps1 file), I don't receive the expected results...It's like the command doesn't work. I wonder if I have to add any argument or character along with this command inside the script so the script can work when I double-click on the .ps1 file Note: Remember that the command works perfectly if you Please advise, Charles1.7KViews0likes2CommentsModifying 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!Solved26KViews0likes6Commentsrunning 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.2KViews0likes5CommentsInstantiating a class inherited from Forms
I created a user input GUI PS script based on the example in the MS doc https://docs.microsoft.com/en-us/powershell/scripting/samples/creating-a-custom-input-box?view=powershell-7.2, which worked fine. I then created a class that inherits from Forms, based on the same setup / config in a module. My issue is that when I instantiate my custom user input class what is displayed appears to be the base Forms class without any of the components I configured. If I include the $forms.showDialog inside the class constructor, my class displays correctly. My goals is to end up with a set of modularized PS scripts where a primary PS script instantiates the user input class, and runs the required logic from the primary, calling other classes / scripts as needed. I greatly appreciate any guidance that points me in the right direction. User input class, created in moduel (psm1) using namespace System.Windows.Forms using namespace System.Drawing [void] [System.Reflection.Assembly]::LoadWithPartialName("System.Drawing") [void] [System.Reflection.Assembly]::LoadWithPartialName("System.Windows.Forms") Class InputWindow:Form{ #InputWindow() { $form = [Form]::new() $form.Size = [Size]::new(400, 415) $form.MaximizeBox = $false $form.StartPosition = "CenterScreen" $form.FormBorderStyle = [System.Windows.Forms.FormBorderStyle]::FixedSingle # prevents screen sizing $form.Topmost = $true $form.text = "Profile Removal" #Label $toolStrpLabel = [System.Windows.Forms.ToolStripStatusLabel]::new() $toolStrpLabel.Size = [Size]::new(10,12) $toolStrpLabel.text ="Current Status" #StatusStrip $statusStrip = [System.Windows.Forms.StatusStrip]::new() $statusStrip.Size = [System.Drawing.size]::new(10, 12) $statusStrip.Dock = [System.Windows.Forms.DockStyle]::Bottom $statusStrip.SizingGrip = $false $statusStrip.Text = "Test" $statusStrip.Items.AddRange($toolStrpLabel) $form.Controls.Add($statusStrip) #Buttons $cancelButton = [System.Windows.Forms.Button]::new() $cancelButton.Margin = 5 $cancelButton.Anchor = 'right,bottom' $cancelButton.Location = [System.Drawing.Point]::new(190, 300 ) $cancelButton.Size = [System.Drawing.Size]::new(75,23) $cancelButton.Text = '&Cancel' $cancelButton.DialogResult = [System.Windows.Forms.DialogResult]::Cancel $form.CancelButton = $cancelButton $form.AcceptButton = $cancelButton #Sets the default active button $form.Controls.Add($cancelButton) $okButton = [System.Windows.Forms.Button]::new() $okButton.Margin = 5 $okButton.Anchor = 'right, bottom' $okButton.Location = [System.Drawing.Point]::new(275,300) $okButton.Size = [System.Drawing.Size]::new(75,23) $okButton.Text = '&OK' $okButton.DialogResult = [System.Windows.Forms.DialogResult]::OK $form.Controls.Add($okButton) #Message Banner $msgBanner = [System.Windows.Forms.Label]::new() $msgBanner.Location = [System.Drawing.Point]::new(10,20) $msgBanner.Size = [System.Drawing.Size]::new(300,20) $msgBanner.Text = 'Enter your MID information below:' $form.Controls.Add($msgBanner) #MID Label $midLabel = [System.Windows.Forms.Label]::new() $midLabel.Location = [System.Drawing.Point]::new(50,50) $midLabel.Size = [System.Drawing.Size]::new(35,15) $midLabel.Text = 'MID:' $form.Controls.Add($midLabel) #MID input box $midBox = [System.Windows.Forms.TextBox]::new() $midBox.Location = [System.Drawing.Point]::new(85,46) $midBox.Size = [System.Drawing.Size]::new(70,20) $midBox.Enabled = $true $midBox.TextAlign = "Left" $form.Controls.Add($midBox) #Password label $pswdLabel = [System.Windows.Forms.Label]::new() $pswdLabel.Location = [System.Drawing.Point]::new(190,50) $pswdLabel.Size = [System.Drawing.Size]::new(72,15) $pswdLabel.Text = 'Password:' $form.Controls.Add($pswdLabel) #Password input box $pswdBox = [System.Windows.Forms.TextBox]::new() $pswdBox.Location = [System.Drawing.Point]::new(260,46) $pswdBox.Size = [System.Drawing.Size]::new(70,20) $pswdBox.Enabled = $true $pswdBox.TextAlign = "Left" $form.Controls.Add($pswdBox) $form.Add_Shown({$midBox.Select()}) } # END of Constructor # } #END of Class InputWindow Function Get-InputWindow () { [InputWindow]::new() } Export-ModuleMember -Function Get-InputWindow1.4KViews0likes1CommentAdd 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.4KViews0likes7CommentsRun powershell script on Devops with paramter
We have created below script which is exporting send port details from binding file post deployment and then comparing the send port name from a csv lookup sheet we are exporting a new csv file having some interface details. so the script is working fine when we are running on the server but we are trying to run the same script in azure Devops pipeline mentioned the script path and argument then it failing with below error. Script running fine in server: $finalBinding = [xml](Get-Content 'D:\agent\BIZTALK_DEPLOY1\r17\a/_BOS.DMS.Parts.Master/drop/Binding.xml') $finalBinding.BindingInfo.SendPortCollection.SendPort.Name | out-file "C:\Script\test.csv" import-csv "C:\Script\test.csv" -Header SendPort | sort SendPort | export-csv "C:\Script\output.csv" -NoTypeInformation Remove-Item –path "C:\Script\test.csv" $BindingData = Import-Csv -Path "C:\Script\output.csv" $LookupData = Import-Csv -Path "C:\Script\Interfacedetails.csv" $UserOutput = @() ForEach ($name in $BindingData) { $userMatch = $LookupData | where {$_.SendPort -eq $name.SendPort} If($userMatch) { $UserOutput += New-Object PsObject -Property @{InterfaceName=$userMatch.InterfaceName;ApplicationTo=$userMatch.ApplicationTo;ApplicationFrom =$userMatch.ApplicationFrom;InterfaceID=$userMatch.InterfaceID;DataObject=$userMatch.DataObject} } } $UserOutput | export-csv "C:\Script\FILE.csv" -NoTypeInformation Import-CSV C:\Script\FILE.csv | Select-Object InterfaceName, InterfaceID, DataObject, ApplicationFrom, ApplicationTo | Export-CSV C:\Script\ExportedCSV\Final.csv -NoTypeInformation Remove-Item –path "C:\Script\FILE.csv" Remove-Item –path "C:\Script\output.csv" Running the same script with Argument: $finalBinding = [xml](Get-Content –path $bindingpath) $finalBinding.BindingInfo.SendPortCollection.SendPort.Name | out-file "C:\Script\test.csv" import-csv "C:\Script\test.csv" -Header SendPort | sort SendPort | export-csv "C:\Script\output.csv" -NoTypeInformation Remove-Item –path "C:\Script\test.csv" $BindingData = Import-Csv -Path "C:\Script\output.csv" $LookupData = Import-Csv -Path "C:\Script\Interfacedetails.csv" $UserOutput = @() ForEach ($name in $BindingData) { $userMatch = $LookupData | where {$_.SendPort -eq $name.SendPort} If($userMatch) { $UserOutput += New-Object PsObject -Property @{InterfaceName=$userMatch.InterfaceName;ApplicationTo=$userMatch.ApplicationTo;ApplicationFrom =$userMatch.ApplicationFrom;InterfaceID=$userMatch.InterfaceID;DataObject=$userMatch.DataObject} } } $UserOutput | export-csv "C:\Script\FILE.csv" -NoTypeInformation Import-CSV C:\Script\FILE.csv | Select-Object InterfaceName, InterfaceID, DataObject, ApplicationFrom, ApplicationTo | Export-CSV C:\Script\ExportedCSV\Final.csv -NoTypeInformation Remove-Item –path "C:\Script\FILE.csv" Remove-Item –path "C:\Script\output.csv" I have declared the variable for $bindingpath = $(System.DefaultWorkingDirectory)/_BOS.DMS.Parts.Master/drop/Binding.xml But its failing with below error: Formatted command: . 'C:\Script\powershellscript.ps1' System.DefaultWorkingDirectory/_BOS.DMS.Parts.Master/drop/Binding.xml 2022-07-05T11:09:43.7113613Z ========================== Starting Command Output =========================== 2022-07-05T11:09:43.7250585Z ##[command]"C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe" -NoLogo -NoProfile -NonInteractive -ExecutionPolicy Unrestricted -Command ". 'D:\agent\BIZTALK_DEPLOY1_temp\9b6ede3b-af5a-4813-9fc9-9d343c347be2.ps1'" 2022-07-05T11:09:44.0505059Z At C:\Script\powershellscript.ps1:24 char:15 2022-07-05T11:09:44.0505593Z + Remove-Item –path C:\Script\output.csv 2022-07-05T11:09:44.0505849Z + ~~~~~~~~~~~~~~~~~~~~~~~~~~ 2022-07-05T11:09:44.0506103Z The string is missing the terminator: ". 2022-07-05T11:09:44.0506460Z + CategoryInfo : ParserError: (:) [], ParentContainsErrorRecordException 2022-07-05T11:09:44.0507271Z + FullyQualifiedErrorId : TerminatorExpectedAtEndOfString please help me to resolve the issue.950Views0likes1CommentRemote powrrshell for skype for business 2015
Good morning all, I was wondering if anyone can help me or point me in right direct to how to create a remote session to skype for business management shell. Currently I am writing a script that creating Ad user, then remoting to exchange management shell to enable mailboxs and then skype management shell to enable Cs user but for some reason their nothing online about removing to skype management shell. Kind regards718Views0likes0Comments