I am trying to convert the "Return First recurring character in a string problem" from python to powershell - powershell

I have completed coding this same problem in python and was trying to generate a similar logic or atleast achieve a similar result in powershell.
Python Code-
def FRC(str):
h = {}
for ch in str:
if ch in h:
return ch
else:
h[ch] = 0
return '\0'
print(FRC("abcdedcba"))
I have tried a few possible codes and was able to only enumerate the array of characters to count their occurrences. Thank you for any suggestions.
Update1 - The code I have worked on is as follows:
function get-duplicatechar {
[CmdletBinding()]
param (
[string]$teststring
)
$hash = #()
$teststring = $teststring.ToCharArray()
foreach ($letter in $teststring)
{
if($letter -contains $hash){
return $letter
}else {
$hash = $hash + $letter
}
return "\0"
}
}
get-duplicatechar("saahsahh")

You could use the (.Net) HashSet class for this, which Add method (besides adding the value,) returns true if the element is added to the HashSet<T> object and false if the element is already present.
function get-duplicatechar {
[CmdletBinding()]
param (
[string]$str
)
$h = [System.Collections.Generic.HashSet[char]]::new()
foreach ($ch in $str.ToCharArray()) {
if(!$h.add($ch)) { return $ch }
}
}

Here's a working version using your code as base:
function get-duplicatechar {
[CmdletBinding()]
param (
[string]$teststring
)
$hash = #{}
$CharArray = $teststring.ToCharArray()
foreach ($letter in $CharArray) {
if($letter -in $hash.Keys) {
$letter
break
}
else {
$hash[$letter] = $null
}
}
}
One problem is that you are strongly typing $teststring to be a string, so when you add a character array later PowerShell just converts it into a string and thus $teststring remains a string (try $teststring.GetType() after $teststring = $teststring.ToCharArray() to see this for yourself).
One way to solve this is to do what I did and use a different variable for the character array. You could also solve it by changing the variable to a character array directly by replacing [string]$teststring with [char[]]$teststring, that way any strings input to the function will be automatically cast as a character array.
The next mistake is using -contains where you need -in. The letter doesn't contain the array, you're looking for the letter in the array, just like you did in Python.
You can drop the return keyword entirely, PowerShell does not need it. Any output in your function will be output from the function automatically.
You also call your collection variable "hash", but you made an array. I changed it to be an actual hashtable, just like in your Python code. I also changed the way we add to it to more closely reflect what you did in Python. There are many ways to do this, this is just one. Notice we'll need to add ".Keys" in our if-statement as well so we check for keys matching our letter.
I think that's it, ask if anything is unclear.

Related

Powershell pass complex object By Value, not By Reference

I am trying to process some data in an ordered dictionary, then add that to another ordered dictionary, and I can do that by reinitializing my temporary dictionary, like this...
$collection = [Collections.Specialized.OrderedDictionary]::new()
foreach ($id in 1..5) {
$tempCollection = [Collections.Specialized.OrderedDictionary]::new()
foreach ($char in [Char]'a'..[Char]'e') {
$letter = ([Char]$char).ToString()
if ($id % 2 -eq 0) {
$letter = $letter.ToUpper()
}
$int = [Int][Char]$letter
$tempCollection.Add($letter, $int)
}
$collection.Add($id, $tempCollection)
}
foreach ($id in $collection.Keys) {
Write-Host "$id"
foreach ($key in $collection.$id.Keys) {
Write-Host " $key : $($collection.$id.$key)"
}
}
However, I feel like reinitializing is a bit inefficient/inelegant, and I would rather just .Clear() that temporary variable. Which leads to this...
$collection = [Collections.Specialized.OrderedDictionary]::new()
$tempCollection = [Collections.Specialized.OrderedDictionary]::new()
foreach ($id in 1..5) {
foreach ($char in [Char]'a'..[Char]'e') {
$letter = ([Char]$char).ToString()
if ($id % 2 -eq 0) {
$letter = $letter.ToUpper()
}
$int = [Int][Char]$letter
$tempCollection.Add($letter, $int)
}
$collection.Add($id, $tempCollection)
$tempCollection.Clear()
}
foreach ($id in $collection.Keys) {
Write-Host "$id"
foreach ($key in $collection.$id.Keys) {
Write-Host " $key : $($collection.$id.$key)"
}
}
The problem is that while simple objects like string, int, char, etc are passed by value, all complex objects like a dictionary are passed by reference. So I pass the SAME dictionary in every iteration of $collection.Add($id, $tempCollection) and the final state of $tempCollection is cleared, so the result is 5 empty members of $collection.
I know I can force something that is normally passed By Value to be By Reference using [Ref] as outlined here. And [Ref] is just an accelerator for System.Management.Automation.PSReference. So what I need is a way to force an argument By Value, but neither [Val] nor [ByVal] works, and searching for System.Management.Automation.PSValue doesn't seem to return anything useful either. The PSReference doco linked above says
This class is used to describe both kinds of references:
a. reference to a value: _value will be holding the value being referenced.
b. reference to a variable: _value will be holding a PSVariable
instance for the variable to be referenced.
which makes me think I can get to the Value somehow, but for the life of me I can't grok HOW. Am I on the right track, and just missing something, or am I misunderstanding this documentation completely?
Cloning also seems like a potential solution, i.e. $collection.Add($id, $tempCollection.Clone()), but Ordered Dictionaries don't implement ICloneable. .CopyTo() also isn't an option, since it doesn't necessarily maintain the order of the elements. Nor does .AsReadOnly() since
The AsReadOnly method creates a read-only wrapper around the current
OrderedDictionary collection. Changes made to the OrderedDictionary
collection are reflected in the read-only copy. Nor does OrderedDictionary implement .copy() as PSObject does.
I also tried making a new variable, like this...
$newCollection = $tempCollection
$collection.Add($id, $newCollection)
$tempCollection.Clear()
And that doesn't work either. So it seems that complex objects by reference seems to apply to more than just passed arguments.
It seems almost like my Ordered Dictionary choice/need is the root of the problem, but it seems like needing a unconnected copy of an Ordered Dictionary would not be such an edge case that it isn't supported.

Elegant way of setting default value for variable in Powershell 6.0?

I have the following, which works but looks clunky:
if($config.contentDir){
$contentDir = $config.contentDir
} else {
$contentDir = "contents"
}
Is there a nicer way of doing this? I have seen this answer here, but it isn't exactly "nicer". Just wondering if 6.0 brought any improvements?
I'm likely to be handling a large amount of config options, so it's going to get fairly messy.
This is a little shorter...
$contentDir = if ( $config.contentDir ) { $config.contentDir } else { "contents" }
You could also define an iif function:
function iif {
param(
[ScriptBlock] $testExpr,
[ScriptBlock] $trueExpr,
[ScriptBlock] $falseExpr
)
if ( & $testExpr ) {
& $trueExpr
}
else {
& $falseExpr
}
}
Then you could shorten to this:
$contentDir = iif { $config.contentDir } { $config.contentDir } { "contents" }
As an aside, it looks like the next version of PowerShell will support the ternary operator (see https://devblogs.microsoft.com/powershell/powershell-7-preview-4/), so in the future, you'll be able to write something like:
$contentDir = $config.contentDir ? $config.contentDir : "contents"
Update:
Null-coalescing operators were introduced in PowerShell (Core) 7.0 (along with a ternary operator), which enables the following v7+ solution:
$contentDir = $config.contentDir ?? 'content'
PowerShell v6- solutions:
What you'e looking for is null-coalescing, which PowerShell doesn't have as of v7.0.0-preview.4.
For now, this will have to do:
$contentDir = if ($null -eq $config.contentDir) { 'content' } else { $config.contentDir }
Note: $null is deliberately placed on the LHS of -eq to unambiguously test for $null, because as the RHS it would act as a filter if the value to test happens to be array-valued.
An adaptation of Lee Daily's array-based answer enables a more concise solution:
$contentDir = ($config.ContentDir, 'content')[$null -eq $config.ContentDir]
Use of the ternary operator (conditional), which will be implemented in v7.0, enables a similarly concise equivalent:
$contentDir = $null -eq $config.contentDir ? 'content' : $config.contentDir
However, all these approaches have the following undesirable aspects:
They require an explicit reference to $null; note that if ($config.ContentDir) - i.e. coercing the value to a Boolean - may work with strings, but is not generally robust, because non-$null values such as 0 can evaluate to $false too.
$config.contentDir, the value to test for $null, must be accessed twice, which can have side effects.
Defining a custom function named, say, ??, can address these problems:
# Custom function that emulates null-coalescing.
function ?? ($PossiblyNull, $ValueIfNull) {
if ($null -eq $PossiblyNull) { $ValueIfNull } else { $PossiblyNull }
}
$contentDir = ?? $config.contentDir 'content'
However, such a custom function has down-sides:
The down-sides of custom functions are:
You need to include or import them into in every piece of code you want to use them in.
If you choose familiar name such as ??, the placement of operands can get confusing, because you must (invariably) place them differently in PowerShell, given the implementation as a function (e.g., a ?? b in C# vs. ?? $a $b in PowerShell) - especially once true null-coalescing gets implemented in PowerShell: see next section.
And, of course, calling a function adds overhead.
If this GitHub feature request is implemented, you'll be able to use true null-coalescing, which is both the most concise solution and avoids the aforementioned undesirable aspects:
# Hopefully soon
$contentDir = $config.contentDir ?? 'content'
A related feature also proposed in the linked GitHub issue is null-conditional assignment, $config.ContentDir ?= 'content'
as Bill_Stewart showed, there is a ternary operator due in ps7. however, you can get something similar by using a two-item array and taking advantage of how PoSh will coerce values -- $False gives 0, $True gives 1.
$Config = [PSCustomObject]#{
ContentDir = 'SomewhereElse'
}
#$Config.ContentDir = ''
$ContentDir = #('contents', $Config.ContentDir)[[bool]$Config.ContentDir]
$ContentDir
output with line 4 commented out = SomewhereElse
output with line 4 enabled = contents
Sort of like '||' in bash. If the first one is false or null, it will do the second one.
[void](($contentDir = $config.contentDir) -or ($contentDir = "contents"))

How do I populate an unknown number of variables from user input dynamically in powershell?

I am trying to figure out how to populate an unknown number of variables based on user input (writing a script that obtains certificates from a CA, and sometimes these certificates contain more than one name (SANs) and it is impossible to know how many so this needs to be dynamic).
I know I start with setting up params like this:
[CmdletBinding()]
Param(
[Parameter(Mandatory=$True)]
[string[]]$SANs
)
And then I need to somehow take those values and assign them to $san1, $san2, $san3 and so on.
Being new to programming, I am not even sure what to call this. Would you use a foreach loop to somehow populate these variables?
ForEach ($SAN in $SANs) {
what do I do here?
}
The end result is a need to populate a string with these variables like dns=$san1&dns=$san2&dns=$san3 etc...
Functions and scripts can take parameters. The parameter block in your example looked like...
function foo {
Param([string[]]$SANs)
}
That parameter, $SANs, is an array of strings. A single string would look like this...
$stuff = 'barf'
An array of strings looks like this...
$stuff = #('barf', 'toot', 'ruff', 'meow')
So far so good? If you need to get each of the things in the array, you'd use a loop...
foreach ($thing in $stuff) { write-output $thing }
...for example...
$san_declaration
foreach ($thing in $stuff) {
if ($san_declaration.length -eq 0) {
$san_declaration = "dns=${thing}"
} else {
$san_declaration += "&dns=${thing}"
}
}
Now, if you (not that you asked) happen to be calling Get-Certificate, just remember the SANs parameter is a string array. In that case, you'd just pass in the string array instead of creating the string like you were doing.
Get-Certificate -DnsName $stuff

Powershell: Turn period delimited string into object properties

I have a string that looks something like this:
$string = "property1.property2.property3"
And I have an object, we'll call $object. If I try to do $object.$string it doesn't interpret it that I want property3 of property2 of property1 of $object, it thinks I want $object."property1.property2.property3".
Obviously, using split('.') is where I need to be looking, but I don't know how to do it if I have an unknown amount of properties. I can't statically do:
$split = $string.split('.')
$object.$split[0].$split[1].$split[2]
That doesn't work because I don't know how many properties are going to be in the string. So how do I stitch it together off of n amounts of properties in the string?
A simple cheater way to do this would be to use Invoke-Expression. It will build the string and execute it in the same way as if you typed it yourself.
$string = "property1.property2.property3"
Invoke-Expression "`$object.$string"
You need to escape the first $ since we don't want that expanded at the same time as $string. Typical warning: Beware of malicious code execution when using Invoke-Expression since it can do anything you want it to.
In order to avoid this you would have to build a recursive function that would take the current position in the object and pass it the next breadcrumb.
Function Get-NestedObject{
param(
# The object we are going to return a propery from
$object,
# The property we are going to return
$property,
# The root object we are starting from.
$rootObject
)
# If the object passed is null then it means we are on the first pass so
# return the $property of the $rootObject.
if($object){
return $object.$property
} else {
return $rootObject.$property
}
}
# The property breadcrumbs
$string = '"Directory Mappings"."SSRS Reports"'
# sp
$delimetedString = $String.Split(".")
$nestedObject = $null
Foreach($breadCrumb in $delimetedString){
$nestedObject = Get-NestedObject $nestedObject $breadcrumb $settings
}
$nestedObject
There are some obvious places where that function could be hardened and documented better but that should give you an idea of what you could do.
What's the use case here? You can split the string as you've described. This will create an array, and you can count the number of elements in the array so that n is known.
$string = "property1.property2.property3"
$split = $string.split('.')
foreach($i in 0..($split.Count -1)){
Write-Host "Element $i is equal to $($split[$i])"
$myString += $split[$i]
}

Powershell - Array Range from user input

What would be the easiest way to get user input for an array range.
For example:
function MyArrayOfMachines {
[CmdletBinding()]
param(
[parameter(Mandatory=$true)][string]$Machine
# What should I assign the $Range variable as?
)
# Hardcoded range. User should be able to enter the range
$Range = 2..5
for ($i=0; $i -lt $array.length; $i +=1)
{
$result = $array[$i]
$output = $machine+$result
$output
}
}
The above function should take the input as the name of the machine and the array range. For now I have the array range hardcoded. When I assign $Range as [Array]$Range in the user prompt, there is a prompt for $Range[0] etc etc. But I would like the user the enter the range.
Doesn't this work? Unless I misunderstood your question...
function test($range){
$range
}
test -range (1..5)
You can also accept the range as a string and parse it yourself:
function Test
{
param($range)
if($range -is [String])
{
[int]$start, [int]$end = $range.split('.', [StringSplitOptions]::RemoveEmptyEntries)
$start..$end
}
else
{
$range
}
}
The reason for the if / else is for cases where the user passes an actual range, as in manojlds answer, rather than a string to be parsed (like 1..5). This means you can't strongly type the param though.
Make it two parameters:
function test{
param ( [int]$st,
[int]$end)
$Range = $st..$end
$Range
}
test 1 5
If they input the start and end of the range you can use that to create it dynamically in the function.
EDIT:
To get the range from a string, try:
function test{
param ($Range)
$NewRange = $Range.substring(0,($Range.indexof('.')))..$Range.substring(($Range.lastindexof('.') + 1))
$NewRange
}
test 1..5
I agree with #manojlds, the range should be passed in as an array. Parsing a string limits the possibilities of what a user could enter. By using [int[]] you can force the user to specify an array of integers. This would also allow a user to specify a broken range such as ((2..4)+(6..12)) which is harder to allow for when parsing strings.
In your example I'm not sure where $array is coming from, and you only need one line to return a computed machine name.
function MyArrayOfMachines {
param(
[parameter(mandatory=$true)]
[string] $machine,
[parameter(mandatory=$true)]
[int[]] $range
)
foreach($n in $range) {
$machine+$n
}
}
You could create a single machine name,
MyArrayOfMachines Laptop 1
a range of machines,
MyArrayOfMachines Workstation (2..10)
or a non-consecutive array of machines
MyArrayOfMachines Server ((2..3)+(5..9))
You could just pass a string and evaluate it:
function Test([string]$range) {
if ($Range -match '^\d+\.\.\d+$') {
$RangeArray = Invoke-Expression $Range
} else {
$RangeArray = 1..5
}
}
Some minimal validation is done to ensure that the user cannot pass arbitrary code.