Remove-ADPrincipalGroupMembership script is not removing user - powershell-2.0

I have the following script that runs without error but it doesn't remove the user from the group. I am not sure what I am missing. I have tried running this without the username variable and with an actual name but that did not work either. Thanks in advance for the help.
$group = #(
'Aberdeen Refer Team','Air Force Refer Team','Coliseum Refer Team','Denbigh Refer Team','Warwick Refer Team','Wards Corner Refer Team',
'Eagle HarborRefer Team','Chesapeake Refer Team','Willow Oaks Refer Team','poquoson Refer Team','Oyster Point Refer Team','NASA ReferTeam',
"Contact Center Refer Team",'Yorktown Refer Team','WB New Town Refer Team','WB City Refer Team','Stoneybrook Refer Team',
'Hayes Refer Team','Hilltop Refer Team')
$user = Get-aduser "%username%" -Properties MemberOf
if ($user.MemberOf -match $group)
{
foreach ($group in $user)
{
Remove-ADPrincipalGroupMembership -identity $user -MemberOf $group -confirm:$False
}
}

Replace %username% with $env:USERNAME to get the username, and then find all the user's groups with Get-ADPrincipalGroupMembership:
$TeamNames = #('Aberdeen Refer Team','Hilltop Refer Team')
$User = Get-ADUser "$($env:USERNAME)"
# Find all the groups that the user is a member of, and filter down to just those in the $TeamNames list
$UserGroups = Get-ADPrincipalGroupMembership -Identity $user | Where-Object { $TeamNames -contains $_.Name }
# Iterate over the groups
foreach ($Group in $UserGroups)
{
# Remove each group membership from the user
Remove-ADPrincipalGroupMembership -Identity $User -MemberOf $Group -Confirm:$false
}

Related

How to get an ec2 instance id from instance name

i want to retrieve an ec2 instance's ID from it's name which I have set as the value of it's tag. I have a VM with key as 'Name' and value as 'testvm1'. Is there something like
(get-ec2 instance id) | where-object {$_.(key.value) - eq "testvm1"}
this worked
$ec2Name = New-Object Amazon.EC2.Model.Filter -Property #{Name = "tag:Name"; Values = "testvm1"}
$instances = #(Get-EC2Tag -Filters $ec2Name)
$instances | Select-Object -ExpandProperty resourceid
You can further reduce this by passing a hashtable as your filter. This will map your input to a Amazon.EC2.Model.Filter[] type.
Example with one filter on tag:Name mapping multiple tag names:
(Get-EC2Tag -Filter #{Name="tag:Name";Values="Name1","Name2"}).ResourceId
Example output:
i-abcd1234
i-edfg5678

Find user by imported display name via powershell

I've checked code and examples from identical questions on this site, but I'm baffled, because I'm utilizing nearly the exact same code from Get-ADUser with display name as a value and it just pulls empty results for me. I don't know how to continue a conversation on an existing question, so I figured I had to make my own.
Here is what I have:
import-module activedirectory
$csv = Get-Content users.csv
foreach ($user in $csv) {
$user = $user.trim()
write-host $user #A line for testing to show me what name is being analyzed
$samName = Get-ADUser -Filter{displayName -like "$user*"} | select samaccountname
write-host $samName
}
cmd /c pause | out-null
The output I get is:
John Doe
Jane Doe
Billy Ray
But if I change
$samName = Get-ADUser -Filter{displayName -like "$user*"} | select samaccountname
to:
$samName = Get-ADUser -Filter{displayName -like "John Doe*"} | select samaccountname
It will correctly return John Doe's samaccountname.

Powershell: Must provide a value expression on the right-hand side of the '-' operator

#GET TEXT FILE WITH LIST OF "SAMACCOUNTNAME" TO LIST VARIABLE
$list = Get-Content C:\PSSCripts\listofusers.txt
#PULL INFORMATION FROM ACTIVE DIRECTORY TO USERRESULTS VARIABLE
$UserResults = Get-AdUser -filter * -searchbase "OU=THISOU,DC=THISDOMAIN,DC=int" -Properties displayname
#DETERMINE IF USER IS IN THE TXT LIST
foreach ($user in $UserResults)
{
if ($user.SamAccountName -in $list.SamAccountName)
{
#ECHO THEIR NAME TO VERIFY
write-host $user.displayName
}
}
#VERIFY USER TO BE OFFBOARDED VIA Y/N PROMPT - VISUALLY INSPECT LIST
$choice = ""
while ($choice -notmatch "[y|n]"){
$choice = read-host "The following user profiles have been loaded for offboarding. Do you want to continue? Please Verify the users before continuing. (Y/N)"
}
if ($choice -eq "y"){
# LOOP THROUGH USERS AND APPLY CHANGES
foreach ($user in $UserResults)
{
#DETERMINE IF USER IS IN TXT FILE
if ($user.SamAccountName -in $list.SamAccountName)
{
# DISABLE ACCOUNT
Disable-ADAccount -Identity $user
# CHANGE DISPLAYNAME AND DESCRIPTION TO DISPLAY TERMINATED - $USER
$newname = "Terminated - " + $user.displayName
Get-ADUser -Identity $user | Set-ADObject -Description $newname -DisplayName $newname
# CHANGE USER PASSWORD TO "Password1"
$password = "Password1" | ConvertTo-SecureString -AsPlainText -Force
Set-ADAccountPassword -NewPassword $password -Identity $user -Reset
# MOVE USER TO DIFFERENT LOCATION, Disabled Users organizational unit
Move-ADObject -Identity $user -TargetPath "OU=DisabledUsers,DC=THATDOMAIN,DC=int" -Confirm:$false
}
}
}
else {write-host "Script aborted!"}
Getting the following error:
*You must provide a value expression on the right-hand side of the '-' operator. At :11 char:29
if ($user.SamAccountName - <<<< in $list.SamAccountName)
Category Info : ParserError (:) [], ParseException
FullyQualifiedErrorID : ExpectedValueExpression
I have a list of users in a text file with the header SAMACCOUNTNAME. These users are being checked against the list of users in a particular OU. Powershell will echo the list of users in my text list to me (after having checked it against all the users in that OU in AD - to verify nothing is being offboarded / changed in error), prompt to verify (y|n) before moving forward and executing a script I wrote with the help of some redditors from /r/powershell earlier.
I'm not understanding why I'm getting this error, is
-in $list.SamAccountName
Not correct?
Thanks for the help, stackoverflow! First time posting, looking forward to getting better with Powershell and giving back to the community.
You should use "-eq" or "-contains" (I am not sure what is a scalar value and what is an array in your program).

How can I handle multiple options for parameters in powershell?

I want to be able to have multiple forms of the same parameter like so:
param(
[string]$p or $path = "C:\",
[string]$f or $filter = "*.txt",
[switch]$o or $overwrite
)
but I'm not sure how to do this. Most times, you would only be able to choose one (e.g. only $p or only $path). Is it possible to use multiple names for the same variable/parameter?
Like this:
param(
[Alias('p')]
[string]$path = "C:\",
[Alias('f')]
[string]$filter = "*.txt",
[Alias('o')]
[switch]$overwrite
)
Note you can have multiple aliases too: [Alias('p','thepath')]
PowerShell partial parameter name matching may be what your looking for.
# test.ps1
param($path)
write-host $path
Calling .\test.ps1 with either .\test.ps1 -path "c:\windows" or .\test.ps1 -p "c:\windows" will both match, and populate, the $path parameter.

JIRA: Generating per-user time report?

Sorry if SO is not the best place, but I have time-tracking enabled in JIRA and want to be able to generate a time-report for each user over a given date range. The only time-tracking report option I have is very limited and doesn't do what I want, is it possible through standard functionality or a free plugin perhaps?
You might want to check out Tempo Plugin for JIRA timetracking. It offers timesheets, reports and gadgets on user, team, project, and customer levels.
how about this one:
https://plugins.atlassian.com/plugin/details/294
If you don't want to pay a lot of money for a simple action like getting a summary of time per user.
I found this flow useful:
Create a filter that you like to measure (I measure time only by sub tasks)
Export it to excel
Copy and paste it into a google docs spreadsheet
In google docs you have an option to create a Pivot Table, so just create one that the rows are the assignees and the values are the time
You can also create a calculated column to get the time in hours (just divide it by 3600)
Hope it helps
Using the Better Excel Plugin you can take advantage of all reporting features in Microsoft Excel.
This plugin exports any sort of JIRA data (including issue fields and worklogs) to custom Excel templates. The templates can use filtering to the date range, and can display your report in an Excel pivot table. If you need further dimensions (like additional grouping by project, by component, by week, by month, etc.), these are super simple to add. You can also visualize the output in a pivot chart.
Tip: there is a default template included in the plugin, called worklog-report.xlsx, which can be used as is, or as starting point for further customization. It looks like this (there is a time-by-project pivot chart in the first worksheet, but I don't have a screenshot about that):
After the template is created, you can merge that with the most current JIRA data any time by a single click, or even generate it and email it to you automatically.
Disclaimer: I'm a developer working on this paid add-on.
You can easily do it with Everhour add-on for JIRA. It allows receiving a comprehensive report for each user over a given date range. And you are absolutely free to build any other layout of your reports and add as many data columns as you need.
Jira Sample Report - Everhour
If you're on Windows you can run the following powershell script to extract the data to CSV file.
## Instructions ##
Open Powershell ISE (It's installed to all windows 7 and later PCs)
Create a new PowerShell script (ctrl+n)
Paste the text from the following code block into the new file
##################################################################
# Variables
##################################################################
$username = "myname#asdf.com"
$password = Read-host "What's your Jira password?" -AsSecureString
#$password = ""
$jiraDomain = "asdf.atlassian.net"
$projectKey = "ABC"
$startDate = [datetime]::ParseExact('2017-05-08', 'yyyy-MM-dd', $null)
$endDate = Get-Date
#Get-Date = today
$csvFileName =c:\temp\Worklog.csv
##################################################################
# Functions
##################################################################
function get-jiraData {
param( [string]$restRequest)
Invoke-RestMethod -Headers #{Authorization=("Basic {0}" -f $base64AuthInfo)} -Uri $restRequest
}
function get-issues {
param( [string]$projectName)
$uri = "https://${jiraDomain}/rest/api/2/search?jql=project=${projectName}"
$issuesPage = get-jiraData -RestRequest $uri
#write first batch of issues
$issuesPage.issues
#do next batches
do {
$startAt = $issuesPage.maxResults + 1
$uri = "https://${jiraDomain}/rest/api/2/search?jql=project=${projectName}&startAt=$startAt"
$issuesPage = get-jiraData -RestRequest $uri
#write next batch of issues
$issuesPage.issues
} while (($issuesPage.startAt + $issuesPage.maxResults) -lt $issuesPage.total)
}
filter convert-worklog {
$worklog = New-Object System.Object
$worklog | Add-Member –type NoteProperty –Name Person –Value $_.author.name
$worklog | Add-Member –type NoteProperty –Name IssueKey –Value $key
$startDate = [datetime]::ParseExact($_.started.Substring(0,16), 'yyyy-MM-ddTHH:mm', $null)
$worklog | Add-Member –type NoteProperty –Name DateLogged –Value $startDate
$TimeMinutes = $_.timeSpentSeconds / 60
$worklog | Add-Member –type NoteProperty –Name TimeSpent –Value $TimeMinutes
$worklog | Add-Member –type NoteProperty –Name Comment –Value $_.comment
$worklog
}
filter extract-worklogs {
#$key = "WL-22"
$key = $_.key
$uri = "https://${jiraDomain}/rest/api/2/issue/${key}/worklog"
$worklogsPage = get-jiraData -RestRequest $uri
#write first batch of worklogs
$worklogsPage.worklogs | convert-worklog
#Check for another batch of worklogs
do {
$startAt = $worklogsPage.maxResults + 1
$uri = "https://${jiraDomain}/rest/api/2/issue/${key}/worklog?startAt=$startAt"
$worklogsPage = get-jiraData -RestRequest $uri
#write next batch of worklogs
$worklogsPage.worklogs | convert-worklog
} while (($worklogsPage.startAt + $worklogsPage.maxResults) -lt $worklogsPage.total)
}
##################################################################
# Execution
##################################################################
#Setup Authentication variable
$base64AuthInfo = [Convert]::ToBase64String([Text.Encoding]::ASCII.GetBytes(("{0}:{1}" -f $username,$password)))
#This grabs all the worklogs for a project, then filters them by
$WorkLogs = get-issues -projectName $projectKey | extract-worklogs | ?{ $_.DateLogged -gt $startDate -and $_.DateLogged -lt $endDate } | sort DateLogged
$WorkLogs | export-csv $csvFileName -NoTypeInformation
Modify the variables at the start of the file
Save as a powershell script somewhere on your PC
Run the script by double clicking it

Resources