Add-AzureADUser Powershell - azure-powershell

Having issues trying to get my loop grab each member's ObjectID then adding those members into an AD group using the Add-AzureADGroupMember cmdlet. Any help would be great. Thank you
Import-Module MSOnline
Import-Module AzureAD
#2Checks for users with admin roles
$RolesCollection = #()
$Roles = Get-MsolRole
ForEach ($Role In $Roles){
$Members = Get-MsolRoleMember -RoleObjectId $Role.ObjectId
ForEach ($Member In $Members) {
$data = New-Object PSObject -Property #{
RoleName = $Role.Name
MemberName = $Member.DisplayName
MemberObjectID = $Member.ObjectId
}
$RolesCollection += $data
}
#Adds users with admin roles into PIM group via member object ID
forEach ($objectID in $RolesCollection){
Add-AzureADGroupMember -ObjectId 'removed ObjectID for security concerns' -RefObjectId $($Member.ObjectId)
}
}

Please refer to my code below:
$RolesCollection = #()
$Roles = Get-MsolRole
ForEach ($Role In $Roles){
$Members = Get-MsolRoleMember -RoleObjectId $Role.ObjectId
ForEach ($Member In $Members) {
$data = New-Object PSObject -Property #{
RoleName = $Role.Name
MemberName = $Member.DisplayName
MemberObjectID = $Member.ObjectId
}
$RolesCollection += $data
}
#Adds users with admin roles into PIM group via member object ID
forEach ($user in $RolesCollection){
#check if the user exists in the AAD Group, if not, add into it.
$members = Get-AzureADGroupMember -ObjectId 'removed ObjectID for security concerns' | Select -ExpandProperty ObjectId
If ($members -contains $user) {
continue
} Else {
Add-AzureADGroupMember -ObjectId 'removed ObjectID for security concerns' -RefObjectId $($user.MemberObjectID)
}
}
}

Related

Date Variable is not Carry Over to Function for Query String

I receive this error:
ExecuteSqlQuery : Must declare the scalar variable "#date".
I call the query as such: ExecuteSqlQuery -server "sqlbox" -database "dbname" and I receive the date variable error. You can see my query statement uses the variable m.created_date >= #date.
How do I correctly pass the date variable to query string so it runs in the function without an issue? NOTE: the code works when I hardcode the date value.
Function ExecuteSqlQuery {
Param(
[Parameter(Mandatory=$true)][string]$server,
[Parameter(Mandatory=$true)][string]$database
)
Process
{
$date= $((get-date).AddSeconds(-120).ToString("MM-dd-yyyy HH:mm:ss"))
$getscriptinfo = "select m.created_date, a.engine_full_hierarchy as Location, e.exciter_name, e.engine_exciter_id as ExciterID, m.additional_data as ReasonDown from HugsAdminAmador.mv_audit m, HugsAdminAmador.exciter e, HugsAdminAmador.area_map a where m.object_id = e.exciter_id and e.area_map_id = a.area_map_id and m.created_date >= #date and m.additional_data like '%NewStatus=DOWN%' and m.additional_data not like '%autonomous%'"
$scriptscon = New-Object System.Data.SqlClient.SqlConnection
$scriptscon.ConnectionString = "Data Source=$server;Initial Catalog=$database;Integrated Security=true"
$scriptcmd = New-Object System.Data.SqlClient.SqlCommand
$scriptcmd.Connection = $scriptscon
$scriptcmd.CommandText = $getscriptinfo
$scriptcmd.CommandTimeout = 0
$ErrorActionPreference = 'Stop'
try
{
$scriptscon.Open()
$Reader = $scriptcmd.ExecuteReader()
# if reader returns data create an array of the error data for the potential alert.
If ($Reader.HasRows) {
$obj = $Reader | foreach {
$row = $_;
#the left naming is for the column headers in the email.
new-object psObject -Property #{
CreateDate = $row.Item("created_date")
ReasonDown = $row.Item("ReasonDown")
ObjectID = $row.Item("object_id")
}
}
}
return $obj
}
catch [Exception]
{
# Write-Warning "Get-ExecuteScripts (Connection: [$server].[$database])"
# Write-Warning $_.Exception.Message
# Write-Warning "Query: $getscriptinfo --Id $scriptid"
Write-Error $_
$ErrorEvent = #{
LogName = 'Exciter_Log'
Source = 'Exciter_Health'
EventID = 333
EntryType = 'Information'
Message = $_
}
Write-EventLog #ErrorEvent
}
finally
{
$ErrorActionPreference = 'Continue'
$scriptscon.Dispose()
$scriptcmd.Dispose()
}
}
}

How to return a reference value with a method from an extended Powershell object?

I'm trying to extend a Powershell object with a method that
returns a true or false to indicate success
outputs a value by reference ([ref])
I have in my module MyExtensions.psm1.
Update-TypeData -TypeName [MyType] -MemberType ScriptMethod -memberName TryGetValue -force -value `
{
param(
$myInput,
[ref]$myOutput
)
try
{
# do something with $myInput
$myOutput = …
return $true
}
catch
{
return $false
}
}
The goal is to be able to write in a script or in another module:
Import-Module MyExtensions
$myInput = …
$value = $null
if($myTypeItem.TryGetValue($myInput, $value)
{
# I know that the $value is good
}
Using argument by reference (you just miss $myOutput.Value ="")
function addition ([int]$x, [int]$y, [ref]$R)
{
$Res = $x + $y
$R.value = $Res
}
$O1 = 1
$O2 = 2
$O3 = 0
addition $O1 $O2 ([ref]$O3)
Write-Host "values from addition $o1 and $o2 is $o3"
A more comple answer here.

Retrieving a int value from database

I am trying to get sender_id and receiver_id into my variables but it is giving me following error
Warning: mysql_fetch_array() expects parameter 1 to be resource,
object given in /opt/lampp/htdocs/Task/php/insertdatanew.php on line
36
Warning: mysql_fetch_row() expects parameter 1 to be resource, object
given in /opt/lampp/htdocs/Task/php/insertdatanew.php on line 42 N
CODE:
<?php
$sender_id = 0;
$receiver_id = 0;
session_start();
if(isset($_SESSION['login_user'])) {
//header('location: chat.php');
}
else {
header('location: chatlogin.php');
}
if(isset($_REQUEST['sender']) AND isset($_REQUEST['msg']) AND isset($_REQUEST['time']) AND isset($_REQUEST['receiver']) ){
$msg = $_REQUEST['msg'];
$time = $_REQUEST['time'];
$sender = $_REQUEST['sender'];
$receiver = $_REQUEST['receiver'];
echo $sender;
echo $receiver;
echo $msg;
echo $time;
//echo $msg;
if ( empty($_REQUEST['msg']) ) {
}
else{
require_once 'dc_chat.php';
$mysqli = new mysqli(DB_HOST, DB_USER, DB_PASS, DB_NAME);
$result = $mysqli -> query("SELECT id from users where username LIKE '{$sender}'");
$row = mysql_fetch_row($result);
$sender_id = $row[0];
$result = $mysqli -> query("SELECT id from users where username LIKE '{$receiver}'");
$row = mysql_fetch_row($result);
$receiver_id = $row[0];
//echo $receiver_id;
$sql = $mysqli -> query("INSERT INTO `messages` (`sender_id`, `receiver_id`, `msg`, 'chattime') VALUES ('{$sender_id}', '{$receiver_id}', '{$msg}' ,'{$time}')");
if(! $sql ) {
echo 'N';
}
else {
echo 'Y';
}
}
}
else{
echo "hello";
}
?>
I am getting $msg, $time, $sender, $receiver from a ajax and datatype is JSON
You are mixing mysql and mysqli functions. mysql_fetch_row should probably be mysqli_fetch_row.
Replace if (!$sql) with if ($mysqli->affected_rows == 0) to test for success on the INSERT statement.
If you suspect an error in your SQL statement use echo $mysqli->error; after your query line to put that on the screen.

Zend/db/Sql/ query syntax

I am starting with Zend Framework 2 , I want to make a routing choice with the role of My user and I must write getRoleByID($id) ,
then
How can'I write
" Select 'role' from user where ('id' = $id) " with Zend\Db\Sql
Example Using Select:
$select = new \Zend\Db\Sql\Select('user');
$select->columns(array('role'));
$where = new Where();
$where->equalTo('id', $id);
$select->where($where);
/**
* Simple example of executing a query...
*/
$stmt = $this->getSql()->prepareStatementForSqlObject($select);
$results = $stmt->execute();
/* #var $results \Zend\Db\Adapter\Driver\Pdo\Result */
if( ! $results->count()) {
// do something, none found...
}
$row = $results->current();
return $row['role'];
// if you had multiple results to iterate over:
//$resultSet = new \Zend\Db\ResultSet\ResultSet();
//$resultSet->initialize($results);
//$array = $resultSet->toArray();
//foreach($resultSet as $row) { /* ... */ }

Yii how to get Data from Count and Group By

How to get an array by Executing this query in Yii?
SELECT `sevrity_id`,COUNT(*) FROM `Incident` GROUP BY `sevrity_id`
I need an array like this: array(1=>20,2=10,3=12)
public function getSevrityCounts()
{
$data = array();
$command = Yii::app()->db->createCommand('SELECT sevrity_id,COUNT(*) AS num FROM Incident GROUP BY sevrity_id');
foreach($command->queryAll() as $row) {
$data[ $row['sevrity_id'] ] = $row['num'];
}
return $data;
}