Office 365 - how to manage many users - security

I have 200 unsorted users in office 365. I want to find an easy way to manage who they are and what security group each user belongs to.
Is there an easy way to export username and what groups each user belongs to?
Iam quite new to poweshell...
But i want to export a CSV file with user and gruops.
Is this possible?
Or do you recommend any other way to quick get an overview of all users and what grups they belong to.
Some users need to be in multiple groups and i suspect some users are missing in groups they should be in..
Thanks for any tips i can get.

################################################################################################################################################################
# Script accepts 2 parameters from the command line
#
# Office365Username - Optional - Administrator login ID for the tenant we are querying
# Office365Password - Optional - Administrator login password for the tenant we are querying
#
#
# To run the script
#
# .\Get-DistributionGroupMembers.ps1 [-Office365Username admin#xxxxxx.onmicrosoft.com] [-Office365Password Password123]
#
#
# Author: Alan Byrne
# Version: 2.0
# Last Modified Date: 16/08/2014
# Last Modified By: Alan Byrne alan#cogmotive.com
################################################################################################################################################################
#Accept input parameters
Param(
[Parameter(Position=0, Mandatory=$false, ValueFromPipeline=$true)]
[string] $Office365Username,
[Parameter(Position=1, Mandatory=$false, ValueFromPipeline=$true)]
[string] $Office365Password
)
#Constant Variables
$OutputFile = "DistributionGroupMembers.csv" #The CSV Output file that is created, change for your purposes
$arrDLMembers = #{}
#Remove all existing Powershell sessions
Get-PSSession | Remove-PSSession
#Did they provide creds? If not, ask them for it.
if (([string]::IsNullOrEmpty($Office365Username) -eq $false) -and ([string]::IsNullOrEmpty($Office365Password) -eq $false))
{
$SecureOffice365Password = ConvertTo-SecureString -AsPlainText $Office365Password -Force
#Build credentials object
$Office365Credentials = New-Object System.Management.Automation.PSCredential $Office365Username, $SecureOffice365Password
}
else
{
#Build credentials object
$Office365Credentials = Get-Credential
}
#Create remote Powershell session
$Session = New-PSSession -ConfigurationName Microsoft.Exchange -ConnectionUri https://ps.outlook.com/powershell -Credential $Office365credentials -Authentication Basic –AllowRedirection
#Import the session
Import-PSSession $Session -AllowClobber | Out-Null
#Prepare Output file with headers
Out-File -FilePath $OutputFile -InputObject "Distribution Group DisplayName,Distribution Group Email,Member DisplayName, Member Email, Member Type" -Encoding UTF8
#Get all Distribution Groups from Office 365
$objDistributionGroups = Get-DistributionGroup -ResultSize Unlimited
#Iterate through all groups, one at a time
Foreach ($objDistributionGroup in $objDistributionGroups)
{
write-host "Processing $($objDistributionGroup.DisplayName)..."
#Get members of this group
$objDGMembers = Get-DistributionGroupMember -Identity $($objDistributionGroup.PrimarySmtpAddress)
write-host "Found $($objDGMembers.Count) members..."
#Iterate through each member
Foreach ($objMember in $objDGMembers)
{
Out-File -FilePath $OutputFile -InputObject "$($objDistributionGroup.DisplayName),$($objDistributionGroup.PrimarySMTPAddress),$($objMember.DisplayName),$($objMember.PrimarySMTPAddress),$($objMember.RecipientType)" -Encoding UTF8 -append
write-host "`t$($objDistributionGroup.DisplayName),$($objDistributionGroup.PrimarySMTPAddress),$($objMember.DisplayName),$($objMember.PrimarySMTPAddress),$($objMember.RecipientType)"
}
}
#Clean up session
Get-PSSession | Remove-PSSession

Related

list all vendors in azure ad who had logged/never logged in the past 24 hours

I wrote a script to list all vendors in the azure ad to check if they are working or not. the script find the logged in users for the past day and if there is a record it should print, if there is no record and the vendor did not logged in or work it should print no login records. but my script is not working well any one can help?
###########################Here is the code ##################
#get azure ad users
$AzADUsers = get-azureaduser
#start for loop
foreach ($user in $AzADUsers){
#list attributes
$dp = $user.DisplayName
$company = $user.CompanyName
# list of contractors/vendors who didn't log in during the day.
if ($company -eq "Vendor Resource - companyname1" -or $company -eq "Vendor Resource - companyname2" -or $company -eq "Vendor Resource - companyname3") {
#check if they logged in the past 24 hours
$SetDate = (Get-Date).AddDays(-1);
$SetDate = Get-Date($SetDate) -format yyyy-MM-dd
$AllSiginLogs = Get-AzureADAuditSignInLogs -Filter "createdDateTime gt $SetDate"
$LoginRecord = $AllSiginLogs | Sort-Object CreatedDateTime -Descending
if($LoginRecord.Count -gt 0){
$lastLogin = $LoginRecord[0].CreatedDateTime
}
else{
$lastLogin = 'no login record | Sick'
}
Write-Host "Last logon time : " $lastLogin $dp $company
Write-Host " "
}
}
in addition to our discussion:
Currently you loop through the $AzAdUsers and query foreach the SignInLogs. But you do not filter the SignInLogs for the specific user, you query all the time the same information and select the latest entry from that log, but it has no relation to the current user.
You have to filter the SignInLog for the specific user, e.g.:
$AllSiginLogs = Get-AzureADAuditSignInLogs -filter "Id eq '$($user.Id)' and createdDateTime gt $SetDate"
After that you could do:
$attrsht = #{
userId=$User.id
DisplayName=$user.displayname
LastSignIn=$LoginRecord.CreatedDateTime
}
new-object -typename psobject -property $attrsht
Btw. the AzModule will be replaced by the microsoft.graph modules. So it might be the right time to do the switch, which you have to do in any case until 2024.
If you do so, you can directly get the lastSignInDateTime from the user object:
#Switch to beta API
select-mgprofile -name beta
$lastSignIn = get-mguser -userId $user.id -Property signinactivity
$lastSignIn.LastSignInDateTime
In regards to you latest comment:
once again, if you want to know the last signInDateTime for a specific user you have to filter for that user id. if you filter by companyname you will probably get several users back and then you have to loop over this array of users and query the signInLog foreach user. the problem you are facing is that you miss to specify consistensylevel and countvariable, e.g.:
$company = "MyCompanyName"
$users = Get-MgUser -filter "companyname eq '$company'" -ConsistencyLevel eventual -CountVariable $null -property Id,CompanyName,DisplayName
select-mgprofile -Name beta
$lastSignInDateTime = #(
foreach ($user in $users){
$LoginRecord = get-mguser -userId $user.id -Property signinactivity
$attrsht = #{
userId=$User.id
DisplayName=$user.displayname
CompanyName=$user.CompanyName
LastSignIn=$LoginRecord.signinactivity.LastSignInDateTime
}
new-object -typename psobject -property $attrsht
}
)
You need to have the MgGraph module installed to run the above mentioned cmdlets -> install-module microsoft.graph
More information in regards to consistensylevel:
https://devblogs.microsoft.com/microsoft365dev/build-advanced-queries-with-count-filter-search-and-orderby/

Query ObjectId of ConditionalAccessLocationCondition

I am writing a script to write to Azure, I basically want to find a user, create a network location, create a conditional access policy. This is what I have so far. The trouble is that the $secmon_guid and $location_policy_guid do not work. If I manually put the values in, it works.
# Run these commands first to connect and install without the #
Install-Module -Name AzureAD -AllowClobber -Force # Answer Y to install NuGet. Run once on workstation running script.
Install-Module -Name Microsoft.Graph.Identity.SignIns -Force # Install this to allow us to setup a trusted location. Run once on workstation running script.
Install-Module MSOnline -Force #Allow us to edit users. Run once on workstation running script.
Set-ExecutionPolicy -ExecutionPolicy RemoteSigned -Scope LocalMachine #Set execution policy to allow our script to do things.
Import-Module -Name AzureAD #The following 3 commands are ran for each client.
Connect-AzureAD # Use GA credentials from Glue
Connect-MsolService #Reauthenticate if necessary.
Get-AzureADMSConditionalAccessPolicy #This will list out all of the existing CA policies. This is a good opportunity to get them into documentation.
Connect-MgGraph #This enabled graph, you will need to approve the request in the popup window.
#Set variable for account name
Set-Variable -name "account" -Value "secmon"
#Create named location for the IP address
$ipRanges = New-Object -TypeName Microsoft.Open.MSGraph.Model.IpRange
$ipRanges.cidrAddress = "IP ADDR"
New-AzureADMSNamedLocationPolicy -OdataType "#microsoft.graph.ipNamedLocation" -DisplayName "Blackpoint IP Address for SecMon" -IsTrusted $true -IpRanges $ipRanges
#Disable MFA for secmon
Get-MsolUser -SearchString "secmon" | Set-MsolUser -StrongAuthenticationRequirements #()
#Get the Azure AD GUID for use later
$secmon_guid = Get-MsolUser -SearchString "secmon" | Select ObjectID
#Name the policy
$name = "Allow Secmon Only from Blackpoint IP"
#Enable the policy. Set to Disabled to test.
$state = "Enabled"
#Get location GUID and save to variable
$location_policy_guid = Get-AzureADMSNamedLocationPolicy | Where-Object -Property DisplayName -Contains 'Blackpoint IP Address for SecMon' | Select-Object -Property Id
#Working on this
#Create the overarching condition set for CA, this is the container.
$conditions = New-Object -TypeName Microsoft.Open.MSGraph.Model.ConditionalAccessConditionSet
#Include all applications - This might be able to be removed?
$conditions.Applications = New-Object -TypeName Microsoft.Open.MSGraph.Model.ConditionalAccessApplicationCondition
$conditions.Applications.IncludeApplications = 'All'
#Create the user condition and include secmon
$conditions.Users = New-Object -TypeName Microsoft.Open.MSGraph.Model.ConditionalAccessUserCondition
$conditions.Users.IncludeUsers = $secmon_guid
#Add new location policy to CA policy
$conditions.Locations = New-Object -TypeName Microsoft.Open.MSGraph.Model.ConditionalAccessLocationCondition
$conditions.Locations.IncludeLocations = $location_policy_guid
#Grant access control to CA policy
$controls = New-Object -TypeName Microsoft.Open.MSGraph.Model.ConditionalAccessGrantControls
$controls._Operator = "OR"
$controls.BuiltInControls = "block"
#End work
New-AzureADMSConditionalAccessPolicy `
-DisplayName $name `
-State $state `
-Conditions $conditions `
-GrantControls $controls
The error I get is due to poorly formatted GUID's, the values I am pulling are not correct. How can I fix this? Any help is greatly appreciated!
New-AzureADMSConditionalAccessPolicy : Error occurred while executing NewAzureADMSConditionalAccessPolicy
Code: BadRequest
Message: 1054: Invalid location value: #{Id=1234GUID}.
InnerError:
RequestId: 5678GUID
Where you define the variables, you need to use -ExpandProperty on the select-object statement e.g:
$secmon_guid = Get-MsolUser -SearchString "secmon" | Select -ExpandProperty ObjectID
Otherwise, you would have to access your current variable like so:
$conditions.Users.IncludeUsers = $secmon_guid.ObjectID

How to export the Certificate details related to the particular IIS site using Powershell script

I wrote a script where in it will export all the SSL certificate details from my machine to an Excel sheet, but I need to export the Certificates which are mapped to the particular site in IIS and then I need to export those details with Site name and the Certificate details to an Excel sheet.
Code
#Clearing the Console host in PS
Clear-Host
#Installing the Excel module to the Powershell
Install-Module -Name ImportExcel
#List of Servers
$computers = Get-Content "C:\TEMP\servers.txt"
#Number of days to look for expiring certificates
$threshold = 300
#Set deadline date
$deadline = (Get-Date).AddDays($threshold)
Invoke-Command -ComputerName $computers {
Get-ChildItem -Path 'Cert:\LocalMachine\My' -Recurse |
Select-Object -Property #{n='ServerName';e={$env:COMPUTERNAME}},Issuer, Subject, NotAfter,
##{Label = 'ServerName';Expression = {$env:COMPUTERNAME}}
#{Label='Expires In (Days)';Expression = {(New-TimeSpan -Start (Get-Date) -End $PSitem.NotAfter).Days}}
} | Export-Excel -Path C:\users\$env:username\documents\MultipleServer_Certificate_Expiry_Details.xlsx`
This is a very common thing, with many articles and samples all over the web on this IIS use case. This is what the web administration module is used for.
<#
Get all IIS bindings and SSL certificates
On a local or remote IIS PowerShell Session
#>
Import-Module -Name WebAdministration
Get-ChildItem -Path IIS:SSLBindings |
ForEach-Object -Process {
if ($_.Sites)
{
$certificate = Get-ChildItem -Path CERT:LocalMachine/My |
Where-Object -Property Thumbprint -EQ -Value $_.Thumbprint
[PsCustomObject]#{
Sites = $_.Sites.Value
CertificateFriendlyName = $certificate.FriendlyName
CertificateDnsNameList = $certificate.DnsNameList
CertificateNotAfter = $certificate.NotAfter
CertificateIssuer = $certificate.Issuer
}
}
}
Customize the above to fit your output needs.
Note if you happen to be on a legacy version of PowerShell:
[PsCustomObject]#{} will not work in PS 2.0 but you may replace it by New-Object -TypeName PSObject
Update
You've asked for a sample script to run on multiple servers. However, you already have the code in your post. Just put that Invoke-Command inside a ForEach loop and pass in a list of computers.
$Computers |
ForEach {
Invoke-Command -ComputerName $PSItem -ScriptBlock {
Get-ChildItem -Path 'Cert:\LocalMachine\My' -Recurse |
Select-Object -Property #{n='ServerName';e={$env:COMPUTERNAME}},Issuer, Subject, NotAfter,
#{Label='Expires In (Days)';Expression = {(New-TimeSpan -Start (Get-Date) -End $PSitem.NotAfter).Days}}
} | Export-Excel -Path "C:\users\$env:username\documents\MultipleServer_Certificate_Expiry_Details.xlsx"
}
Of course, you'll need to add in that sample for the Web Admin block to your cert data points

How to extract all PowerBI users and workspace access using the PowerBI API or Azure Portal?

New to Power BI. Trying to get a report of the Users who have access for each Dashboards. Any pointers would be helpful.
Thanks in advance!
Below is the script I created. First change the username and password for your PowerBI credentials. The script collects the results and then opens two Out Grid windows (Workspaces and Workspace Users). You can then copy/paste the grid results into excel. This doesn't export shared reports and dashboards.
I have two PBI powershell modules installed. I think this script uses only the MicrosoftPowerBIMgmt.
Check if you have the PBI modules.
get-module -ListAvailable | where {$_.Name -like '*BI*'}
And to check for the cmdlets available.
get-command -module MicrosoftPowerBIMgmt.Admin | sort CommandType, name
get-command -module MicrosoftPowerBIMgmt.Capacities | sort CommandType, name
get-command -module MicrosoftPowerBIMgmt.Data | sort CommandType, name
get-command -module MicrosoftPowerBIMgmt.Profile | sort CommandType, name
get-command -module MicrosoftPowerBIMgmt.Reports | sort CommandType, name
get-command -module MicrosoftPowerBIMgmt.Workspaces | sort CommandType, name
get-command -module PowerBIPS | sort CommandType, name
PBI WORKSPACES & PERMISSIONS
#****************
#------------------------------------------------------
# --> PBI WORKSPACES & PERMISSIONS
#
# Export PBI results to grid for copy/paste to Excel table
# * All groups (Active/Deleted)
# * All workspaces (Active)
# * All workspace permissions
#
# RestAPI call for each workspace (Group Users)
# * https://learn.microsoft.com/en-us/rest/api/power-bi/groups/getgroupusers
#
#------------------------------------------------------
#****************
#------------------------------------------------------
# --> PBI Connection
#------------------------------------------------------
Write-Host " PBI credentials ..." -ForegroundColor Yellow -BackgroundColor DarkGreen
## PBI credentials
$password = "myPassword" | ConvertTo-SecureString -asPlainText -Force
$username = "myemail#domain.com"
$credential = New-Object System.Management.Automation.PSCredential($username, $password)
## PBI connect
Connect-PowerBIServiceAccount -Credential $credential
# Login-PowerBI
#****************
#------------------------------------------------------
# --> Workspace info
#
# * Get-PowerBIWorkspace > "WARNING: Defaulted to show top 100 workspaces. Use -First & -Skip or -All to retrieve more results."
# * Grid exported for workspaces
#------------------------------------------------------
Write-Host " Workspace info ..." -ForegroundColor Yellow -BackgroundColor DarkGreen
## List all groups, Select ID desired for Variables section
## PBIWorkspace properties values are NULL if Scope is not set to Organization
# Get-PowerBIWorkspace -Scope Organization -Filter "tolower(name) eq 'BI Team POC - DEV'"
# SET
$Groups = Get-PowerBIWorkspace -Scope Organization -All | SORT #{Expression="Type"; Descending=$True}, Name
$Groups_deleted = $Groups | SELECT Id, Name, Type, State | WHERE State -EQ 'Deleted'
$Groups = $Groups | SELECT Id, Name, Type, State | WHERE State -NE 'Deleted'
$GroupWorkspaces = $Groups | WHERE Type -eq 'Workspace'
# PRINT
$Groups_deleted | Select Id, Name, Type, State | ft –auto
$Groups | Select Id, Name, Type, State | ft –auto
$GroupWorkspaces | Select Id, Name, Type | ft –auto
Get-PowerBIWorkspace -Scope Organization -Name "BI Team Sandbox" | Select Id, Name, Type | ft –auto
# OUT GRID
$GroupsWorkspaces | Select Id, Name, Type | Out-GridView
$Groups | Select Id, Name, Type | Out-GridView
$Groups_deleted | Select Id, Name, Type, State | Out-GridView
#------------------------------------------------------
## LOOP FOLDERS ##################
# * RestAPI call for each workspace (Group Users)
# * Grid exported for workspace user access
#------------------------------------------------------
# Clear variable before loop to reseat array data collector
clear-variable -name WorkspaceUsers
Write-Host " Looping ..." -ForegroundColor Yellow -BackgroundColor DarkGreen
foreach ($GroupWorkspaceId in $GroupWorkspaces.Id) {
$WorkspaceObject = Get-PowerBIWorkspace -Scope Organization -Id $GroupWorkspaceId
$pbiURL = "https://api.powerbi.com/v1.0/myorg/groups/$GroupWorkspaceId/users"
$WorkspaceObject | Select Id, Name, Type | ft –auto
Write-Host ($WorkspaceObject.Name +" | "+ $WorkspaceObject.Type) -ForegroundColor White -BackgroundColor Blue
Write-Host $GroupWorkspaceId -ForegroundColor White -BackgroundColor Blue
Write-Host $pbiURL -ForegroundColor White -BackgroundColor Blue
#****************
#------------------------------------------------------
# --> 1. API Call for WORKSPACE USERS
#------------------------------------------------------
Write-Host " API Call ..." -ForegroundColor Yellow -BackgroundColor DarkGreen
## API call
$resultJson = Invoke-PowerBIRestMethod –Url $pbiURL –Method GET
$resultObject = ConvertFrom-Json -InputObject $resultJson
## Collect data fields for each loop
$WorkspaceUsers += $resultObject.Value |
SELECT #{n='WorkspaceId';e={$GroupWorkspaceId}},
#{n='Workspace';e={$WorkspaceObject.Name}},
displayName,
emailAddress,
#{n='UserRole';e={$_.groupUserAccessRight}},
#{n='Principle';e={$_.principalType}} |
SELECT Workspace, displayName, UserRole, Principle, emailAddress |
SORT UserRole, displayName
## Print loop results
$WorkspaceUsers | ft -auto | Where{$_.WorkspaceId -eq $GroupWorkspaceId}
clear-variable -name resultJson
clear-variable -name resultObject
}
## END LOOP ##################
#------------------------------------------------------
## Export user access for all workspaces
$WorkspaceUsers | SORT Workspace, UserRole, displayName | Out-GridView
You can use Get-PowerBIWorkspace from Microsoft Power BI Cmdlets to get list of workspaces and then list the members of the underlying Office 365 group (unless you are using the new preview workspaces, which has no underlying Office 365 group) using Get-UnifiedGroup cmdlet. To be able to use it, you need to Connect to Exchange Online PowerShell. Then enumerate the groups, enumerate current group members, and export them to a CSV (or process the result the way you want). If you have rights, provide -Scope Organization parameter, or omit it to get a list of your workspaces.
Import-Module MicrosoftPowerBIMgmt
$password = "xxxxxxxx" | ConvertTo-SecureString -asPlainText -Force
$username = "xxxxxxxx#example.com"
$credential = New-Object System.Management.Automation.PSCredential($username, $password)
Connect-PowerBIServiceAccount -Credential $credential
$Session = New-PSSession -ConfigurationName Microsoft.Exchange `
-ConnectionUri https://outlook.office365.com/powershell-liveid/ `
-Credential $credential `
-Authentication Basic `
-AllowRedirection
Import-PSSession $Session
$Groups = Get-PowerBIWorkspace #-Scope Organization
$Groups | ForEach-Object {
$group = $_
Get-UnifiedGroupLinks -Identity $group.Name -LinkType Members -ResultSize Unlimited | ForEach-Object {
$member = $_
New-Object -TypeName PSObject -Property #{
Member = $member.Name
Group = $group.Name
}
}
} | Export-CSV "D:\\PowerBIGroupMembers.csv" -NoTypeInformation -Encoding UTF8
Remove-PSSession $Session
Disconnect-PowerBIServiceAccount

Change List Field with Powershell in SharePoint Online

I'm attempting to change the field contents for multiple entries in a list. So far I've gotten to the point that I can edit the list, add columns really, but can't find anything on how to edit the field text. Here is what I have currently:
EDIT:
I've found a bunch of info for 2010 which isn't applicable but I've updated the code to almost get there. I'm getting 'null array' errors when I connect to the list now. I'm hopeful because I'm able to connect, but still can't get the field to change. I've updated my if statement as well to what is I believe a better format.
#Load necessary module to connect to SPOService
[System.Reflection.Assembly]::LoadWithPartialName("Microsoft.SharePoint.Client") | Out-Null
[System.Reflection.Assembly]::LoadWithPartialName("Microsoft.SharePoint.Client.Runtime") | Out-Null
#Login Information for script
$User = "user#email.com"
$Pass = "password"
$creds = New-Object System.Management.Automation.PSCredential($User, (ConvertTo-SecureString $Pass -AsPlainText -Force));
#Connect to SharePoint Online service
Write-Host "Logging into SharePoint online service." -ForegroundColor Green
Connect-SPOService -Url https://site-admin.sharepoint.com -Credential $creds
#Get the Necessary List
Write-Host "Getting the required list." -ForegroundColor Green
$WebUrl = 'https://site.sharepoint.com/'
$Context = New-Object Microsoft.SharePoint.Client.ClientContext($WebUrl)
$List = $Context.Web.Lists.GetByTitle("VacationRequestForm")
#Edit existing list items
$items = $List.items
foreach($item in $items)
{
if($item["Export Flag"] -eq "New")
{
Write-Host "Changing export flags to Complete." -ForegroundColor Green
$item["Export Flag"] = "Complete"
$item.Update()
}
}
Write-Host "Your changes have now been made." -ForegroundColor Green
I am guessing you have trimmed the script since you are missing things like defining $context and such. You don't have any ExecuteQuery() calls.
MSDN doc on SP 2013 CSOM List Item tasks, which has C# examples of what you need and can be translated to PowerShell.
It generally looks like you have everything but if you could include your whole script I can try and run your script directly.
EDIT: with the updates here is the code that you need
#Load necessary module to connect to SPOService
[System.Reflection.Assembly]::LoadWithPartialName("Microsoft.SharePoint.Client") | Out-Null
[System.Reflection.Assembly]::LoadWithPartialName("Microsoft.SharePoint.Client.Runtime") | Out-Null
#Login Information for script
$User = "user#email.com"
$Pass = "password"
$WebUrl = "https://site.sharepoint.com/"
#Connect to SharePoint Online service
Write-Host "Logging into SharePoint online service." -ForegroundColor Green
$Context = New-Object Microsoft.SharePoint.Client.ClientContext($WebUrl)
$Context.Credentials = New-Object Microsoft.SharePoint.Client.SharePointOnlineCredentials($User, (ConvertTo-SecureString $Pass -AsPlainText -Force))
#Get the Necessary List
Write-Host "Getting the required list." -ForegroundColor Green
$List = $Context.Web.Lists.GetByTitle("VacationRequestForm")
$Query = [Microsoft.SharePoint.Client.CamlQuery]::CreateAllItemsQuery(100);
$Items = $List.GetItems($Query);
$Context.Load($Items);
$Context.ExecuteQuery();
#Edit existing list items
foreach($item in $Items)
{
if($item["Export_x0020_Flag"] -eq "New")
{
Write-Host "Changing export flags to Complete for Id=$($item.Id)." -ForegroundColor Green
$item["Export_x0020_Flag"] = "Complete"
$item.Update()
$Context.ExecuteQuery();
}
}
Write-Host "Your changes have now been made." -ForegroundColor Green
You had a space in your Export Flag name and SharePoint will not have that in the name of the field. By default it will replace that with a _x0020_ string. This value will be based on the first name of the field. So if you change this field name in the future, you will still refer to it as 'Export_x0020_Flag' in this script. I am doing the .ExecuteQuery() for each update but you could do this once at the end of the loop. There is also the limit of 100 records in the query. If you only want records with "New" you should change the CamlQuery to just pull those records back.

Resources