Power Shell
27 TopicsAdding AD users to a specific security group
Hi Everyone, Sorry if this question has already been asked as I couldn't find an answer. I’m trying to write a PowerShell script that runs as a scheduled task to add AD users to a specific AD security group. The goal is for this to run daily. The script will first check the users' OU to determine if they are already members of the security group. If they are, it will skip them; if they are not members, it will add them to the group. I have created the following script, but I’m unsure if it's the best approach. Additionally, can this script be executed on a server that doesn’t have Active Directory installed? If AD must be installed, would it be ideal to run it on a Domain Controller? # Check if Active Directory module is already imported, import only if necessary if (-not (Get-Module -Name ActiveDirectory)) { Import-Module ActiveDirectory } # Define the base OU and security group $BaseOU = "OU=W11_USERS,DC=W11,DC=NET" $SecurityGroup = "HR" # Get all users from W11_USERS and its sub-OUs $Users = Get-ADUser -SearchBase $BaseOU -SearchScope Subtree -Filter * # Loop through each user and check group membership before adding foreach ($User in $Users) { $UserDN = $User.DistinguishedName # Check if user is already a member of HR $IsMember = Get-ADGroupMember -Identity $SecurityGroup | Where-Object { $_.DistinguishedName -eq $UserDN } if (-not $IsMember) { Try { Add-ADGroupMember -Identity $SecurityGroup -Members $User -ErrorAction Stop Write-Host "Added $($User.SamAccountName) to $SecurityGroup" -ForegroundColor Green } Catch { Write-Host "Failed to add $($User.SamAccountName): $_" -ForegroundColor Red } } else { Write-Host "$($User.SamAccountName) is already a member of $SecurityGroup" -ForegroundColor Yellow } } Write-Host "User addition process completed."216Views0likes1CommentAzure PowerShell find LastOwnershipUpdateTime on disk
Hello: I wondering if it's possible to find LastOwnershipUpdateTime on the disk via PowerShell. I can see this info in the portal, but cannot figure out how to find it via script (PowerShell). Looks like MSFT recently released it, but even updating my Az.Compute module to the latest (9.0.0) version I still do not see it. Any help would be really appreciated. Thank you!Solved251Views0likes3CommentsWarning PowerShell ID 300
HI. Warning PowerShell ID 300 - Device not ready occurs at every start or starting W.P.S 5.1. - <Event xmlns="http://schemas.microsoft.com/win/2004/08/events/event"> - <System> <Provider Name="PowerShell" /> <EventID Qualifiers="0">300</EventID> <Version>0</Version> <Level>3</Level> <Task>3</Task> <Opcode>0</Opcode> <Keywords>0x80000000000000</Keywords> <TimeCreated SystemTime="2023-02-09T13:24:44.9356909Z" /> <EventRecordID>657</EventRecordID> <Correlation /> <Execution ProcessID="7524" ThreadID="0" /> <Channel>Windows PowerShell</Channel> <Computer>Windows-11</Computer> <Security /> </System> - <EventData> <Data>Dispositivo non pronto.</Data> <Data>ProviderName=Microsoft.PowerShell.Core\FileSystem ExceptionClass=IOException ErrorCategory= ErrorId= ErrorMessage=Dispositivo non pronto. Severity=Warning SequenceNumber=13 HostName=ConsoleHost HostVersion=5.1.22621.963 HostId=f904787d-5901-4255-b784-310a76225a8b HostApplication=powershell.exe -ExecutionPolicy Restricted -Command Write-Host 'Final result: 1'; EngineVersion= RunspaceId= PipelineId= CommandName= CommandType= ScriptName= CommandPath= CommandLine=</Data> </EventData> </Event> and the following warning appears: And if I open the link I get version 7 which I already have installed. Is there a solution to avoid this warning? Thank youSolved5.3KViews0likes13CommentsUnable to Execute PowerShell Script Commands in Microsoft Teams Session Established via Script
I encountered an issue while attempting to execute PowerShell script commands within a Microsoft Teams session established via a script. The script includes commands to connect to Microsoft Teams using the Connect-MicrosoftTeams cmdlet and subsequently execute other Teams-related commands. While the script executes without errors, the session does not seem to be fully established, resulting in the following error when attempting to execute subsequent commands: powershell : Get-CsTeamsClientConfiguration : Session is not established, run Connect-MicrosoftTeams before requesting access token At line:1 char:1 + powershell -File 'C:\Users\***********************\script.p ... + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + CategoryInfo : NotSpecified: (Get-CsTeamsClie...ng access token:String) [], RemoteException + FullyQualifiedErrorId : NativeCommandError At C:\Users\****************************\script.ps1:8 char:1 + Get-CsTeamsClientConfiguration + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + CategoryInfo : NotSpecified: (:) [Get-CsTeamsClientConfiguration], UnauthorizedAccessException + FullyQualifiedErrorId : System.UnauthorizedAccessException,Microsoft.Teams.ConfigApi.Cmdlets.GetCsTeamsClientCon figuration This issue is inconsistent, as the commands execute successfully when executed manually. Additionally, I've attempted to introduce delays in the script to allow for the session to fully establish, but the issue persists. This issue impacts the ability to automate tasks in Microsoft Teams using PowerShell scripts. Please let me know if there are any additional steps or information needed to address this issue effectively.1.3KViews0likes2CommentsLicenseType parameter when you scale your Azure SQL Managed Instance
When you try to scale your Azure SQL Managed Instance and you face the following error message: "Configured pricing tier and vCore values require greater number of licenses than previous instance configuration. Please submit operation again with specified value for licenseType property." you have to review your License type.1.8KViews0likes0CommentsPowershell script to find out Teams policies by users
Hey everyone, do you know if there is a way to run a script to find what Teams policies are assigned to what user? We have a private channel policy in place- I would like to find out a list of users that policy is assigned to. Also, if you delete a user from a custom policy does that user get the default policy? Thanks!109KViews2likes16CommentsGetting all virtual machines in a Hyper-V cluster using Python and WinRM
Hello, I am trying to use Python and WinRM to retrieve a list of all virtual machines in a Hyper-V cluster. I have a PowerShell script that works to retrieve the virtual machines owned by the current node, but I am having trouble modifying it to retrieve all virtual machines in the cluster. Here's the current script that retrieves the virtual machines owned by the current node: # Create a PowerShell session on the host machine session = winrm.Session(host, auth=(username, password),transport='ntlm') # Define the PowerShell command to retrieve the list of virtual machines in the cluster ps_script = """ $nodes = Get-ClusterNode Write-Output $nodes $vm_list = Get-ClusterGroup -Cluster $env:computername | Where-Object {$_.GroupType -eq 'VirtualMachine' -and $_.OwnerNode.Name -in $nodes.Name} | Get-VM $vm_names = $vm_list.Name Write-Output $vm_names """ # Execute the PowerShell command and retrieve the output result = session.run_ps(ps_script) if result.status_code == 0: # Parse the output to get the list of virtual machines vm_info = result.std_out.decode('utf-8').strip() # Print the list of virtual machines print(vm_info) else: # Print the full error message print("Error message: " + result.std_err.decode('utf-8').strip()) Can anyone help me modify this script to retrieve all virtual machines in the cluster, regardless of which node owns them? Thank you in advance for your help!2.2KViews0likes2CommentsHow to add a new set of key & values in json file.
Problem Statement: I want to add a set of new key & value in existing parsed Json after specific index. or position. For example: I have imported Json in $Json variable and then I wanted to add new sets of property right after property name 'Service1'. I able to make the script working out for me. However, not able to add new sets of key & value or property after specific position in file. PowerShell Code: function Get-EnvironmentManifest([string]$Filename) { $Settings = Get-Content -Path $Filename -Encoding UTF8 | ConvertFrom-Json -ErrorAction STOP return $Settings } if (([System.Net.Dns]::GetHostByName($env:computerName)).HostName.Split('.')[0] -notmatch "UAT*") { $EnvironmentString = (([System.Net.Dns]::GetHostByName($env:computerName)).HostName.Split('.')[0].Split('-')[1]).ToUpper() for ($i = 1; $i -lt 5; $i++) { $ServiceName = 'Service' + [char](65 + $i) $HastTable = [ordered] @{"Name" = "Service1"; "ProfileType" = "Windows"; "ServiceName" = "$ServiceName";} $Settings = Get-EnvironmentManifest -Filename $TargetJSON $Asset = New-Object -TypeName PSObject $Asset | Add-Member -NotePropertyMembers $HastTable -TypeName 'Asset' $Settings.Profiles.Services += $Asset $Settings | ConvertTo-Json -Depth 3| Set-Content -Path $TargetJSON } } I Was Able to Create Following JSON Using Above PowerShell Code: { "Environment": {}, "Profiles": { "Services": [ { "Name": "A" }, { "Name": "B" }, { "Name": "C" }, { "Name": "D" }, { "Name": "Service1", "ProfileType": "Windows", "ServiceName": "ServiceA" }, { "Name": "E" }, { "Name": "F" }, { "Name": "Service1", "ProfileType": "Windows", "ServiceName": "ServiceB" }, { "Name": "Service1", "ProfileType": "Windows", "ServiceName": "ServiceC" }, { "Name": "Service1", "ProfileType": "Windows", "ServiceName": "ServiceD" }, { "Name": "Service1", "ProfileType": "Windows", "ServiceName": "ServiceE" } ] } } But I Want to Have Following Json: { "Environment": {}, "Profiles": { "Services": [ { "Name": "A" }, { "Name": "B" }, { "Name": "C" }, { "Name": "D" }, { "Name": "Service1", "ProfileType": "Windows", "ServiceName": "ServiceA" }, { "Name": "Service1", "ProfileType": "Windows", "ServiceName": "ServiceB" }, { "Name": "Service1", "ProfileType": "Windows", "ServiceName": "ServiceC" }, { "Name": "Service1", "ProfileType": "Windows", "ServiceName": "ServiceD" }, { "Name": "Service1", "ProfileType": "Windows", "ServiceName": "ServiceE" }, { "Name": "E" }, { "Name": "F" } ] } }Solved30KViews0likes3CommentsGet-CSOnlineUser command incorrect output
Hi, We are working in a migration from Skype onprem to Teams. We check an user with the command "Get-CSOnlineUser", in Teams the user seems to be correctly provisioned, but the output of the command is not correct. Which is the problem? I send attached the output command. Thank you!! David LozanoSolved1.8KViews0likes3CommentsCreating Powerplans
Hello, I want to create a script using Powershell to set a default power plan. I already found something for the good old CMD but nothing yet for Powershell, so maybe you guys can help?! The Settings: Powerbutton: When I press Powerbutton: Shutdown - Shutdown When I press Sleepbutton: Nothing - Nothing When i close the lid: -Nothing -nothing Plan-Settings: Turn off Display: 15min - never Put it to sleep: Never - Never I would appreciate if you could give me some advice on how to use Powershell creating "Power-Plans". Greetings Yannik SchulzSolved8.6KViews1like7Comments