Check if AD group exists or not - ldap

Trying to check if AD group exists or not using below script :
$Path = "LDAP://dc=cmc,dc=com"
$object = "CMC\QTKS-DEP-Admin-Temp"
$type = "Group"
$search = [System.DirectoryServices.DirectorySearcher]$Path
$search.Filter = "(&(name=$object)(objectCategory=$type))"
$Result = $search.FindOne()
IF( $Result -eq $null)
{
Write-Host "Group does not exist"
}
Else
{
Write-Host "Group exists"
}
I know something wrong with the LDAP connection string or variables declarations. Or something else. Can someone please correct. The result always shows as "Group does not exist" even if it exists.

Got it finally :
$Search = New-Object DirectoryServices.DirectorySearcher
$Search.Filter = '(&(objectCategory=Group)(anr=CMC\QTKS-DEP-Admin-Temp))'
$Search.SearchRoot = 'LDAP://DC=cmc,DC=com'
$Result = $Searcher.FindOne()
IF( $Result -eq $null)
{
Write-Host "Group does not exist"
}
Else
{
Write-Host "Group exists"
}

Related

I can't access admin panel of my script : Invalid query You have an error in your SQL syntax

I have an error message when i try to access my script (php):
Invalid query: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 's marketing advertising'' at line 1
This is a admin php file contain mysql query
<?php
$stt_query = $ocdb->get_rows("SELECT * FROM ".$config->prefix."search order by id desc limit 13" );
if (count( $stt_query ) > 0) {
foreach ($stt_query as $row) :
?>
<li><?php echo $row['title'];?></li>
<?php
endforeach;
}
?>
the php query page:
<?php class OCDB { var $server = ""; var $port = ""; var $db = ""; var $user = ""; var $password = ""; var $prefix = ""; var $insert_id; var $link; function __construct($_server, $_port, $_db, $_user, $_password, $_prefix) { $this->server = $_server; $this->port = $_port; $this->db = $_db; $this->user = $_user; $this->password = $_password; $this->prefix = $_prefix; $host = $this->server; if (defined('DB_HOST_PORT') && !empty($this->port)) $host .= ':'.$this->port; $this->link = mysqli_connect($host, $this->user, $this->password) or die("Could not connect: " . mysqli_connect_error()); mysqli_select_db($this->link, $this->db) or die ('Can not use database : ' . mysqli_error($this->link)); mysqli_query($this->link, 'SET NAMES utf8'); } function get_row($_sql) { //$res = $this->link->query($_sql); //if ($this->link->error) { //try { //throw new Exception("MySQL error $mysqli->error <br> Query:<br> $query", $this->link->errno); //} catch(Exception $e ) { //echo "Error No: ".$e->getCode(). " - ". $e->getMessage() . "<br >"; //echo nl2br($e->getTraceAsString()); //} //} $result = mysqli_query($this->link, $_sql) or die("Invalid query: " . mysqli_error($this->link)); $row = mysqli_fetch_array($result, MYSQL_ASSOC); mysqli_free_result($result); return $row; mysqli_close($this->link); } function get_rows($_sql) { $rows = array(); $result = mysqli_query($this->link, $_sql) or die("Invalid query: " . mysqli_error($this->link)); while ($row = mysqli_fetch_array($result, MYSQL_ASSOC)) { $rows[] = $row; } mysqli_free_result($result); return $rows; } function get_var($_sql) { $result = mysqli_query($this->link, $_sql) or die("Invalid query: " . mysqli_error($this->link)); $row = mysqli_fetch_array($result, MYSQL_NUM); mysqli_free_result($result); if ($row && is_array($row)) return $row[0]; return false; } function query($_sql) { $result = mysqli_query($this->link, $_sql) or die("Invalid query: " . mysqli_error($this->link)); $this->insert_id = mysqli_insert_id($this->link); return $result; } function escape_string($_string) { return mysqli_real_escape_string($this->link, $_string); } } ?>
Please can you help me i can't access admin panel because of this error.
Thanks

Azure DevOps API: Get all files (source and target) of Pull Request

I searched quite a bit, found several threads here (e.g. this, that, and more), but I could not find the answer to the following task:
Use the Azure DevOps API to retrieve the content changes (basically the file before and after) of all the files of a specific PR.
I can find a PR, can loop through changes, iterations, commits (in various combinations), but I have not been able to download both the first and the last version of each or the files (and there should be a way as I can view the before and after in a PR in DevOps).
Any hints where/how I can retrieve both versions of a file of a certain commit/change/iteration?
Many thanks in advance!
Cheers,
Udo
Thanks for all the hints. Looks like I managed to find a wat to pull it. Please feel free to correct my approach.
Here's the complete PowerShell file:
[CmdletBinding()]
param (
[int]
$pullRequestId,
[string]
$repoName
)
# --- your own values ---
$pat = 'your-personal access token for Azure DevOps'
$urlOrganization = 'your Azure DevOps organization'
$urlProject = 'your Azure DevOps project'
$basePath = "$($env:TEMP)/pullRequest/" # a location to store all the data
# --- your own values ---
if (!$repoName)
{
$userInput = Read-Host "Please enter the repository name"
if (!$userInput)
{
Write-Error "No repository name given."
exit
}
$repoName = $userInput
}
if (!$pullRequestId)
{
$userInput = Read-Host "Please enter the PullRequest ID for $($repoName)"
if (!$userInput)
{
Write-Error "No PullRequest ID given."
exit
}
$pullRequestId = $userInput
}
$prPath = "$($basePath)$($pullRequestId)"
$sourcePath = "$($basePath)$($pullRequestId)/before"
$targetPath = "$($basePath)$($pullRequestId)/after"
# --- helper methods ---
function CleanLocation([string]$toBeCreated)
{
RemoveLocation $toBeCreated
CreateLocation $toBeCreated
if (!(Test-Path $toBeCreated))
{
Write-Error "Path '$toBeCreated' could not be created"
}
}
function CreateLocation([string]$toBeCreated)
{
if (!(Test-Path $toBeCreated)) { New-Item -ErrorAction Ignore -ItemType directory -Path $toBeCreated > $null }
}
function RemoveLocation([string]$toBeDeleted)
{
if (Test-Path $toBeDeleted) { Remove-Item -Path $toBeDeleted -Recurse -Force }
}
function DeleteFile([string]$toBeDeleted)
{
if (Test-Path $toBeDeleted) { Remove-Item -Path $toBeDeleted -Force }
}
# --- helper methods ---
# --- Azure DevOps helper methods ---
function GetFromDevOps($url)
{
$patToken = [System.Convert]::ToBase64String([System.Text.Encoding]::ASCII.GetBytes(":$($pat)"))
$repoHeader = #{ "Authorization" = "Basic $patToken" }
$response = $(Invoke-WebRequest $url -Headers $repoHeader)
if ($response.StatusCode -ne 200)
{
Write-Error "FAILED: $($response.StatusDescription)"
}
return $response
}
function JsonFromDevOps($url)
{
$response = GetFromDevOps $url
return ConvertFrom-Json -InputObject $response.Content
}
function DownloadFromDevOps($url, $filename)
{
$patToken = [System.Convert]::ToBase64String([System.Text.Encoding]::ASCII.GetBytes(":$($pat)"))
$repoHeader = #{ "Authorization" = "Basic $patToken" }
$ProgressPreference = 'SilentlyContinue'
Invoke-WebRequest $url -Headers $repoHeader -OutFile $filename
$ProgressPreference = 'Continue'
}
function DownloadAndSaveFile($itemUrl, $outputPath, $path, $overwrite)
{
$outFile = "$outputPath$($path)"
$fileExists = Test-Path $outFile
if (!$fileExists -or $overwrite)
{
$outPath = [System.IO.Path]::GetDirectoryName($outFile)
CreateLocation $outPath
if ($fileExists)
{
Write-Host " overwriting to $outputPath"
}
else
{
Write-Host " downloading to $outputPath"
}
DownloadFromDevOps $itemUrl $outFile
}
}
function DownloadFiles($changes, $beforePath, $beforeCommitId, $afterPath, $afterCommitId)
{
foreach ($change in $changes)
{
$item = $change.item
if ($item.isFolder)
{
continue;
}
$path = $item.path
$originalPath = $change.originalPath
if (!$path)
{
$path = $change.originalPath
}
$displayPath = $path ?? $originalPath
$changeType = $change.changeType
Write-Host "[$($changeType)] $($displayPath)"
if (($changeType -eq "edit, rename"))
{
$itemUrl = "$($urlRepository)/items?path=$($originalPath)&versionDescriptor.version=$($beforeCommitId)&versionDescriptor.versionOptions=0&versionDescriptor.versionType=2&download=true"
DownloadAndSaveFile $itemUrl $beforePath $originalPath
}
# just get the source/before version
if ($changeType -eq "delete")
{
$itemUrl = "$($urlRepository)/items?path=$($originalPath)&versionDescriptor.version=$($beforeCommitId)&versionDescriptor.versionOptions=0&versionDescriptor.versionType=2&download=true"
DownloadAndSaveFile $itemUrl $beforePath $originalPath
DeleteFile "$($afterPath)$($originalPath)"
}
if ($changeType -eq "edit")
{
$itemUrl = "$($urlRepository)/items?path=$($path)&versionDescriptor.version=$($beforeCommitId)&versionDescriptor.versionOptions=0&versionDescriptor.versionType=2&download=true"
DownloadAndSaveFile $itemUrl $beforePath $path
}
if (($changeType -eq "add") -or ($changeType -eq "edit") -or ($changeType -eq "edit, rename"))
{
$itemUrl = "$($urlRepository)/items?path=$($path)&versionDescriptor.version=$($afterCommitId)&versionDescriptor.versionOptions=0&versionDescriptor.versionType=2&download=true"
DownloadAndSaveFile $itemUrl $afterPath $path $true
}
$validChangeTypes = #('add', 'delete', 'edit', 'edit, rename')
if (!($validChangeTypes.Contains($changeType)))
{
Write-Warning "Unknown change type $($changeType)"
}
}
}
# --- Azure DevOps helper methods ---
$urlBase = "https://dev.azure.com/$($urlOrganization)/$($urlProject)/_apis"
$urlRepository = "$($urlBase)/git/repositories/$($repoName)"
$urlPullRequests = "$($urlRepository)/pullRequests"
$urlPullRequest = "$($urlPullRequests)/$($pullRequestId)"
$urlIterations = "$($urlPullRequest)/iterations"
CleanLocation $prPath
$iterations = JsonFromDevOps $urlIterations
foreach ($iteration in $iterations.value)
{
# the modified file
$srcId = $iteration.sourceRefCommit.commitId
# the original file
$comId = $iteration.commonRefCommit.commitId
$comId = $iteration.targetRefCommit.commitId
$urlIterationChanges = "$($urlIterations)/$($iteration.id)/changes"
$iterationChanges = JsonFromDevOps $urlIterationChanges
DownloadFiles $iterationChanges.changeEntries $sourcePath $comId $targetPath $srcId
}

PowerShell script with looping can not work after encryption

I have powershell script with looping. But After I encrypt the script. The looping is always running and never stop.
Anyone can help please. THank you
Function 101_Pr
{
Write-Host " 101_Pr"
}
Function CleanUp
{
Write-Host "CleanUp"
}
Function Image
{
$Stoploop = $false
[int]$Retrycount = "0"
do {
try {
$Get = "123AB"
$connectionString = "Server=$IP;uid=$UID;pwd=$Pswd;Database=$Database;Integrated Security=False;"
Write-Host $connectionString
$connection = New-Object System.Data.SqlClient.SqlConnection
$connection.ConnectionString = $connectionString
$connection.Open()
$query = "select Number='$Get'"
$command = $connection.CreateCommand()
$command.CommandText = $query
$result = $command.ExecuteReader()
$table = new-object "System.Data.DataTable"
$table.Load($result)
[array] $DB = $table.Number
Write-Host "Result: $DB"
if($null -ne $DB)
{
$Stoploop = $true
101_Pr
break
}
}
catch {
if ($Retrycount -gt 2)
{
Write-Host "Could not get after 3 retrys."
$Stoploop = $true
CleanUp
break
}
else{
Write-Host "Retry"
Start-Sleep -s 1
$Retrycount = $Retrycount + 1
}
}
}
While ($Stoploop -eq $false)
}
Image
The output is always print this Write-Host $connectionString
I use this script for encryption
ps2exe.ps1
anyone can help really appreciated. THank you

ModX PDO SQL returns empty array

I pretty much copy/pasted this from the ModX RTFM:
$results = $modx->query("SELECT * FROM `saved_jobs` WHERE `job_id` = $job_id AND `user_id` = $user");
if (!is_object($results)) {
return 'No result!';
}
else {
$r = $results->fetchAll(PDO::FETCH_ASSOC);
echo $r;
echo "<br>count " . count($r);
print_r($r);
}
But even though there are no records in the database I still get the 'else' occurring. The line echo "count " . count($r); produces the output: count 0
Does anyone know whats going on and how to fix it?
If your query is successful, you still create an object with your first statement.
take a peek [also from the docs]:
$result = $modx->query("SELECT * FROM modx_users WHERE id='blah'");
echo '<pre>'; var_dump($result); echo '</pre>';
if (!is_object($result)) {
return 'No result!';
}
else {
$row = $result->fetch(PDO::FETCH_ASSOC);
return 'Result:' .print_r($row,true);
}
What you want to do is find out if the object actually contains a result set:
$result = $modx->query("SELECT * FROM modx_users WHERE id='1'");
echo '<pre>'; var_dump($result); echo '</pre>';
if (!is_object($result)) {
return FALSE;
}
if(sizeof($result) > 0){
while($row = $result->fetch(PDO::FETCH_ASSOC)){
echo'Result:' .print_r($row,true);
}
}
so you can either test the size of the $result variable or just run the while loop & test if it has any data as well.

Varchar takes zero field empty

I have a table with a series of codes, which has a field called "numerousuarios" which has a default value "0"
Here the code:
$statement = " SELECT numerousuarios FROM codigos WHERE codigos = :codigo";
$sth = $db ->prepare($statement);
$sth -> execute(array(':codigo'=>$codigo));
$result = $sth->fetch();
$mivariable = $result[numerousuarios];
if(!empty($mivariable)){
if($mivariable>=5){
echo "the code is full users";
}
else{
// Do something...
}
}
else{
echo "el codigo no existe";
}
The if (empty ($ myvar)) is to see if that record in the database.
The problem is that if the value is "0" I take it as an empty field.
What am I doing wrong?
You say the result is "0" by default .just check the returend value is not equal 0 :)
$statement = " SELECT numerousuarios FROM codigos WHERE codigos = :codigo";
$sth = $db ->prepare($statement);
$sth -> execute(array(':codigo'=>$codigo));
$result = $sth->fetch();
$mivariable = $result[numerousuarios];
if($mivariable !=0){
if($mivariable>=5){
echo "the code is full users";
}
else{
// Do something...
}
}
else{
echo "el codigo no existe";
}
:)