Get-ADUser - want to write only one part of the OU into a variable - powershell

I have this:
Get-ADUser myuser |
Select #{n='OU';e={$_.DistinguishedName -replace '^.*?,(?=[A-Z]{2}=)'}}
But I need to get only on part of the OU of a specific user which I have to define as a variable in the beginning.
I get this
OU=Users,OU=Munich,DC=xyzdom,DC=xyz
And I want to detect if the user is in the Munich OU or where ever.
So the output should be just $city and the input $username
I have no clue how to do this. But I suspect it should be not as hard to achieve this goal.
Maybe someone has time and passion to show me how :)
Thank you so much
Greetings
Thanks a lot for the help. (I can't use the city property.) My solution looks like this now:
Import-Module ActiveDirectory
$samaccountname = "Smith"
$ou = Get-ADUser $samaccountname | Select #{n='OU';e={$_.DistinguishedName.split(',')[-3].split("=")[-1]}} | FT -HideTableHeaders
$ou
Now, the output is just: Munich
I want to go on using this variable but maybe it's in a wrong format. when I try to use it with orchestrator I get an output like this: Microsoft.PowerShell.Commands.Internal.Format.FormatStartData Microsoft.PowerShell.Commands.Internal.Format.GroupStartData Microsoft.PowerShell.Commands.Internal.Format.FormatEntryData Microsoft.PowerShell.Commands.Internal.Format.GroupEndData Microsoft.PowerShell.Commands.Internal.Format.FormatEndData
So maybe it has to be formated as string??? How can I do that?

I agree with Santiago that using the users AD attribute City would be a much better solution, but if you don't have that filled in on the users, you may try below.
A DistinguishedName can contain commas, escaped characters and even special characters converted to their HEX representation.
See here and there
Simply splitting a DN on the comma can therefore return unwanted results.
For this, I've written a small helper function some time ago you could use:
function Parse-DistinghuishedName {
[CmdletBinding()]
param (
[Parameter(Mandatory = $true, ValueFromPipeline = $true, ValueFromPipelineByPropertyName = $true, Position = 0)]
[string[]]$DistinghuishedName
)
begin {
function _ReplaceSpecial([string]$value) {
# replace all special characters formatted as BackSlash-TwoDigitHexCode
$match = ([regex]'(?i)\\([0-9a-f]{2})').Match($value)
while ($match.Success) {
$value = $value -replace "\\$($match.Groups[1].Value)", [char][convert]::ToUInt16($match.Groups[1].Value, 16)
$match = $match.NextMatch()
}
# finally, replace all backslash escaped characters
$value -replace '\\(.)', '$1'
}
}
process {
foreach ($dn in $DistinghuishedName) {
$hash = [ordered]#{}
# split the string into separate RDN (RelativeDistinguishedName) components
$dn -split ',\s*(?<!\\,\s*)' | ForEach-Object {
$name, $value = ($_ -split '=', 2).Trim()
if (![string]::IsNullOrWhiteSpace($value)) {
$value = _ReplaceSpecial $value
switch ($name) {
'O' { $hash['Organization'] = $value }
'L' { $hash['City'] = $value }
'S' { $hash['State'] = $value }
'C' { $hash['Country'] = $value }
'ST' { $hash['StateOrProvince'] = $value }
'UID' { $hash['UserId'] = $value }
'STREET' { $hash['Street'] = $value }
# these RDN's can occur multiple times, so add as arrays
'CN' { $hash['Name'] += #($value) }
'OU' { $hash['OrganizationalUnit'] += #($value) }
'DC' { $hash['DomainComponent'] += #($value) }
}
}
}
$hash
}
}
}
It parses the DN into its RDN components and returns a Hashtable.
In your case, use it like:
(Parse-DistinghuishedName 'OU=Users,OU=Munich,DC=xyzdom,DC=xyz').OrganizationalUnit[1] # --> Munich

Related

How to use powershell to reorder a string to obfuscate a hidden message?

Just for fun a friend and I are trying to find a creative way to send coded messages to eachother using steganography.I stumbled upon doing something like whats shown below and I have been struggling trying to write a function to automate the process.
this is a secret message
can be turned into:
("{2}{1}{0}{3}"-f'ecret m','is a s','this ','essage')
splitting the string and using reordering seems to be the way to go.
So the string needs to be split in random splits between 5-10 characters
.
The index of the original positions need to be saved
the splits need to be swapped around
and the new indexes sorted as to reorder the message properly
i've just really been struggling
help is appreciated
Just for fun .... 😉🤡
$InputMessage = 'this is a secret message'
$SplittedString = $InputMessage -split '' | Select-Object -Skip 1 | Select-Object -SkipLast 1
[array]::Reverse($SplittedString)
foreach ($Character in $SplittedString) {
if ($Character -notin $CharacterList) {
[array]$CharacterList += $Character
}
}
foreach ($Character in ($InputMessage -split '' | Select-Object -Skip 1 | Select-Object -SkipLast 1)) {
$Index = [array]::indexof($CharacterList, $Character)
$Output += "{$Index}"
}
$Result = "'$Output' -f $(($CharacterList | ForEach-Object {"'$_'"}) -join ',')"
$Result
And the output of this would be:
'{6}{10}{9}{3}{5}{9}{3}{5}{2}{5}{3}{0}{8}{7}{0}{6}{5}{4}{0}{3}{3}{2}{1}{0}' -f 'e','g','a','s','m',' ','t','r','c','i','h'
And the output of this would be:
this is a secret message
And now if you want to go fancy with it you remove the curly braces and the quotes and the commas and the -f and add only the numbers and characters to the data. ;-)
Not exactly what you're looking for but this might give you something to start with:
class Encode {
[string] $EncodedMessage
[int[]] $Map
[int] $EncodingComplexity = 3
Encode ([string] $Value) {
$this.Shuffle($Value)
}
Encode ([string] $Value, [int] $Complexity) {
$this.EncodingComplexity = $Complexity
$this.Shuffle($Value)
}
[void] Shuffle([string] $Value) {
$set = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890!##$%^&*()_-+=[{]};:<>|./?'
$ref = [Collections.Generic.HashSet[int]]::new()
$ran = [random]::new()
$enc = [char[]]::new($Value.Length * $this.EncodingComplexity)
for($i = 0; $i -lt $enc.Length; $i++) {
$enc[$i] = $set[$ran.Next($set.Length)]
}
for($i = 0; $i -lt $Value.Length; $i++) {
do {
$x = $ran.Next($enc.Length)
} until($ref.Add($x))
$enc[$x] = $Value[$i]
}
$this.EncodedMessage = [string]::new($enc)
$this.Map = $ref
}
}
class Decode {
static [string] DecodeMessage ([Encode] $Object) {
return [Decode]::DecodeMessage($Object.EncodedMessage, $Object.Map, $Object.EncodingComplexity)
}
static [string] DecodeMessage ([string] $EncodedMessage, [int[]] $Map) {
return [Decode]::DecodeMessage($EncodedMessage, $Map, 3)
}
static [string] DecodeMessage ([string] $EncodedMessage, [int[]] $Map, [int] $Complexity) {
$decoded = [char[]]::new($EncodedMessage.Length / $Complexity)
for($i = 0; $i -lt $decoded.Length; $i++) {
$decoded[$i] = $EncodedMessage[$Map[$i]]
}
return [string]::new($decoded)
}
}
Encoding a message:
PS /> $message = 'this is a secret message'
PS /> $encoded = [Encode] $message
PS /> $encoded
EncodingComplexity EncodedMessage Map
------------------ -------------- ---
3 B$h^elu2w#CeeHH^qa siQJ)t}es:.a3 ema=eN(GiIcsO;tst1 .fsg}eSUk7ms4 N>rfe# {49, 2, 41, 27…}
For decoding the message you can either use the object of the type Encode or you can give your friend the Encoded Message and the Map to decode it ;)
PS /> [Decode]::DecodeMessage($encoded)
this is a secret message
PS /> [Decode]::DecodeMessage('B$h^elu2w#CeeHH^qa siQJ)t}es:.a3 ema=eN(GiIcsO;tst1 .fsg}eSUk7ms4 N>rfe#', $encoded.Map)
this is a secret message

How can I parse distinguished names from Active Directory using Powershell to determine parent OUs?

I'm using Microsoft's ActiveDirectory module to retrieve and manipulate our domain users, and I need to easily determine the parent OU of the objects I'm retrieving. I've tried using -split ',' or .Split(','), but I keep running into issues with certain objects that have commas in them.
There is no public exposed DN parser method or class built in to the .Net libraries. It does exist because it has to be there for how some of the DirectoryServices classes seem to work, but I don't know how to call it from Powershell and it's not documented.
There is the fairly popular DNParser library on NuGet, which is a .Net library for parsing and manipulating distinguished names.
First, download the package file from NuGet. The package will be called "dnparser.1.3.3.nupkg" for example, but it's just a ZIP file. Extract the contents to a folder. The package is a single library, so all we need is .\dnparser.1.3.3\lib\net5.0\CPI.DirectoryServices.dll for Powershell v5 or .\dnparser.1.3.3\lib\netstandard1.1\CPI.DirectoryServices.dll for Powershell v6+. You only need that library. Nothing else in the package is strictly necessary.
# Load the library
Add-Type -Path 'C:\Path\To\dnparser.1.3.3\lib\netstandard1.1\CPI.DirectoryServices.dll'
Get-ADUser -Filter 'Enabled -eq "True"' |
Select-Object -First 10 |
ForEach-Object {
$DN = [CPI.DirectoryServices.DN]::new($_.DistinguishedName)
[PSCustomObject]#{
DistinguishedName = $DN.ToString()
ParentOU = $DN.Parent.ToString()
}
} |
Format-List *
You can also create the object with New-Object if you prefer that.
$DN = New-Object -TypeName CPI.DirectoryServices.DN -ArgumentList $_.DistinguishedName
There are other methods and properties in the class, but this is enough for what I need.
Warning: I have learned that DNParser, designed around RFC 2253, uses UTF-8 for encoding hex characters, while I think at least some instances of Active Directory use ISO-8859-1 (Western Latin). In short, you may have hex-escaped characters in Active Directory like ü which are escaped as \FC. These may translate to the UTF-8 unprintable character in DNParser � or \EF\BF\BD because they're in an invalid range in UTF-8. The UTF-8 equivalent would be \C3\BC, but that's ó in ISO-8859-1. There does not appear to be a way to force disable this behavior.
You could use this small helper function to parse out the RelativeDistinguishedName components in order:
function Parse-DistinghuishedName {
# See https://learn.microsoft.com/en-us/previous-versions/windows/desktop/ldap/distinguished-names
[CmdletBinding()]
param (
[Parameter(Mandatory = $true, ValueFromPipeline = $true, ValueFromPipelineByPropertyName = $true)]
[string[]]$DistinguishedName
)
begin {
function _UnescapeSpecial([string]$value) {
# replace all special characters formatted as BackSlash-TwoDigitHexCode
$match = ([regex]'(?i)\\([0-9a-f]{2})').Match($value)
while ($match.Success) {
$value = $value -replace "\\$($match.Groups[1].Value)", [char][convert]::ToUInt16($match.Groups[1].Value, 16)
$match = $match.NextMatch()
}
# finally, replace all backslash escaped characters
$value -replace '\\(.)', '$1'
}
}
process {
foreach ($dn in $DistinguishedName) {
$hash = [ordered]#{}
# split the string into separate RDN (RelativeDistinguishedName) components
$dn -split ',\s*(?<!\\,\s*)' | ForEach-Object {
$name, $value = ($_ -split '=', 2).Trim()
if (![string]::IsNullOrWhiteSpace($value)) {
$value = _UnescapeSpecial $value
switch ($name) {
'O' { $hash['Organization'] = $value }
'L' { $hash['City'] = $value }
'S' { $hash['State'] = $value }
'C' { $hash['Country'] = $value }
'ST' { $hash['StateOrProvince'] = $value }
'UID' { $hash['UserId'] = $value }
'STREET' { $hash['Street'] = $value }
# these RDN's can occur multiple times, so add as arrays
'CN' { $hash['Name'] += #($value) }
'OU' { $hash['OrganizationalUnit'] += #($value) }
'DC' { $hash['DomainComponent'] += #($value) }
}
}
}
$hash
}
}
}
Usage:
$dnHash = Parse-DistinghuishedName 'CN=R\fchmann\, Heinz ,OU=Test,OU=SubOU,DC=North America,DC=Fabrikam,DC=COM'
would result in an ordered Hashtable:
Name Value
---- -----
Name {Rühmann, Heinz}
OrganizationalUnit {Test, SubOU}
DomainComponent {North America, Fabrikam, COM}
To get the parent OU name, you just index into the .OrganizationalUnit element:
$dnHash.OrganizationalUnit[0] # --> 'Test' (top parent OU)
$dnHash.OrganizationalUnit[-1] # --> 'SubOU' (direct OU)

Powershell DataTable,Select Filter does not accept single quote character

I'm writing a simple Name search against a datatable using Powershell. The code as following:
$filter = "Name = '$aContact'"
$arow = $dt_resources.Select($filter)
This works all fine except if $aContact contains a single quote (') character, like "O'Connor".
Any ideal how can I workaround this issue?
Thanks all in advance.
Mathias R. Jessen already commented on the solution to the question but to put it as an answer, you can escape the ' by doubling them. I added a simple function that will also serve as workaround for possible $null input since both methods (.Contains and .Replace) would throw an exception in that case.
$dtt = [System.Data.DataTable]::new()
'Name', 'Value' | ForEach-Object{
$dtt.Columns.Add([System.Data.DataColumn]::new($_))
}
$row = $dtt.NewRow()
$row.Name = "O'Connor"
$row.Value = [random]::new().Next()
$dtt.Rows.Add($row)
$row = $dtt.NewRow()
$row.Name = "Doe"
$row.Value = [random]::new().Next()
$dtt.Rows.Add($row)
function CheckQuery {
param(
[parameter(ValueFromPipeline)]
[string]$Value
)
if($Value.Contains("'")) { return $Value.Replace("'","''") }
return $Value
}
"O'Connor", "Doe", $null | ForEach-Object {
$filter = "Name = '{0}'" -f ($_ | CheckQuery)
$dtt.Select($filter)
}

Powershell - if $var -like $var*

I'm working with SCSM in Powershell but running into an issue with an if statement.
I have a function that collects data based on a criteria that is passed into the function as a variable.
Example:
$JMLs1 = collectTickets -crit $JMLCriteria1
collectTickets is the function, $JMLCriteria1 is the criteria that is passed.
This is the collectTickets function:
function collectTickets
{
param (
[parameter (Mandatory=$true)]
$crit
)
$fullDate = Get-Date
if ($fullDate.DayOfWeek -eq 'Monday')
{
$olderThan = $fullDate.AddDays(-4)
}
elseif ($fullDate.DayOfWeek -eq 'Tuesday')
{
$olderThan = $fullDate.AddDays(-4)
}
else
{
$olderThan = $fullDate.AddDays(-2)
}
if ($crit -like '$JML*')
{
$data = Get-SCSMObject -Criteria $crit | select 'Id', 'Title', 'LastModified', 'Priority'
}
else
{
$data = Get-SCSMObject -Criteria $crit | Where-Object {($_.LastModified -lt $olderThan)} | select 'Id', 'Title', 'LastModified', 'Priority'
}
return $data
}
The issue I'm having is with the second if statement, the if ($crit -like '$JML*') - I'm not sure if we can use wildcards like this against variables or if the syntax is just not correct.
Just to clarify there will be multiple $JML criteria variables as well as multiple other criteria variables, but it's only the $JML criteria variables that I want to treat differently.
Use double quotes instead of single. With single quotes, PowerShell thinks you are looking for the the literal string $JML, not the variable.
if ($crit -like "$JML*")
Edit: about_Quoting documentation

How can I pass dynamic parameters to powershell script and iterate over the list?

I want to create a powershell script that accepts dynamic parameters and I also want to iterate through them.
eg:
I call the powershell script in the following manner.
ParametersTest.ps1 -param1 value1 -param2 value2 -param3 value3
And I should be able to access my params inside the script as follows:
for($key in DynamicParams) {
$paramValue = DynamicParams[$key];
}
Is there anyway to do this in powershell? Thanks in advance.
There is nothing built-in like that (essentially you're asking for PowerShell parameter parsing in the absence of any definition of those parameters). You can emulate it, though. With $args you can get at all arguments of the function as an array. You can then iterate that and decompose it into names and values:
$DynamicParams = #{}
switch -Regex ($args) {
'^-' {
# Parameter name
if ($name) {
$DynamicParams[$name] = $value
$name = $value = $null
}
$name = $_ -replace '^-'
}
'^[^-]' {
# Value
$value = $_
}
}
if ($name) {
$DynamicParams[$name] = $value
$name = $value = $null
}
To iterate over dynamic parameters you can either do something like you wrote
foreach ($key in $DynamicParams.Keys) {
$value = $DynamicParams[$key]
}
(note the foreach, not for, the latter of which cannot work like you wrote it) or just iterate normally over the hash table:
$DynamicParams.GetEnumerator() | ForEach-Object {
$name = $_.Key
$value = $_.Value
}