(Powershell) Does powershell have some weird parentheses/bracket balance rules? - powershell

My powershell acts very strangely when I try to make a function. To demonstrate, Here is a basic function that, I dunno, calculates the quadratic formula:
1 function Get-Quadratic {
2
3 [CmdletBinding()]
4
5 param (
6 [Parameter(Position = 0, Mandatory = $true)]
7 [int32]$a
8 [Parameter(Position = 1, Mandatory = $true)]
9 [int32]$b
10 [Parameter(Position = 2, Mandatory = $true)]
11 [int32]$c
12 )
13
14 Write-Output $a + " " + $b + " " + $c
15 }
And if you were to try loading this in with . .\quadratic.ps1, you get:
At C:\Users\(me)\Desktop\Cur\playground\quadratic.ps1:7 char:11
+ [int32]$a
+ ~
Missing ')' in function parameter list.
At C:\Users\(me)\Desktop\Cur\playground\quadratic.ps1:1 char:24
+ function Get-Quadratic {
+ ~
Missing closing '}' in statement block or type definition.
At C:\Users\(me)\Desktop\Cur\playground\quadratic.ps1:12 char:1
+ )
+ ~
Unexpected token ')' in expression or statement.
At C:\Users\(me)\Desktop\Cur\playground\quadratic.ps1:15 char:1
+ }
+ ~
Unexpected token '}' in expression or statement.
+ CategoryInfo : ParserError: (:) [], ParseException
+ FullyQualifiedErrorId : MissingEndParenthesisInFunctionParameterList
I have followed tutorials down to the pixel when trying to make functions, but my powershell doesn't seem to like even the most basic commands. If it helps, my version is
Major Minor Build Revision
----- ----- ----- --------
5 1 19041 1320

Abraham Zinala provided the crucial pointer with respect to your code's primary problem:
The individual parameter declarations inside a param(...) block must be ,-separated.
While the conceptual about_Functions does state this requirement, it may not be obvious, given that in other contexts (#(...), $(...) and #{ ... }) separating elements by newlines alone is sufficient. In fact, there is an existing feature request to make the use of , optional - see GitHub issue #8957.
The secondary problem is that Write-Output $a + " " + $b + " " + $c won't work as you expect:
Expressions - such as string concatenation with the + operator in your case - require enclosure in (...) in order for their result to be passed as a single command argument - see this answer.

Related

formatting phone numbers using powershell

I'm newbie for script. I am trying to create a powershell to take all my users in active directory and format all of their phone numbers the same + 90 (XXX) XXX XX XX
So an example - +901111111111 will turn to +90 (111) 111 11 11
if your numbers are all the same length & pattern, then the -f string format operator with a format pattern would do the job. [grin] like this ...
$InString = '+901111111111'
$OutPattern = '+## (###) ### ## ##'
$OutString = "{0:$OutPattern}" -f [int64]($InString.Trim('+'))
$OutString
output = +90 (111) 111 11 11
Just in case all numbers have same length this quick solution could solve the problem
$input = "+901234567890"
$output = $input.Substring(0,3) +
" (" +
$input.Substring(3,3) +
") " +
$input.Substring(6,3) +
" " +
$input.Substring(9,2) +
" " +
$input.Substring(11,2)
# $output value should be "+90 (123) 456 78 90"

Split an array based on value

This is my first question here, so sorry if I make any mistakes posting this.
I'm trying to split an array based on its values. Basically I want to create two arrays whose values are as close to the average as possible. I managed to do this with this code:
function Sum($v) {
[Linq.Enumerable]::Sum([int64[]]$v)
}
$arr = 0..9 | % {get-random -min 1 -max 10}
"ARRAY:" + $arr
"SUM: " + (sum $arr)
"AVG: " + (sum $arr)/2
# start of the code that matters
$wavg = (sum $arr)/2
foreach ($i in (0..($arr.Count-1))) {
$wavg -= $arr[$i]
if ($wavg -le 0) {
$i-=(-$wavg -gt $arr[$i]/2);break
}
}
"SPLIT INDEX: " + $i
"ARR1: " + $arr[0..$i] + " (" + $(sum $arr[0..$i]) + ")"
"ARR2: " + $arr[($i+1)..$arr.Count] + " (" + $(sum $arr[($i+1)..$arr.Count]) + ")"
The reason my foreach is structured this way is because in my actual code the values are in an index hash and are accessed as $index[$arr[$i]].
This means that the resulting two arrays could be of unequal size (it would be easy if I could just split the array in half). Sample output of my code to demonstrate this:
ARRAY: 5 3 6 3 2 3 6 3 1 3
SUM: 35
AVG: 17.5
SPLIT INDEX: 3
ARR1: 5 3 6 3 (17)
ARR2: 2 3 6 3 1 3 (18)
The code works as is, but I feel it could be done in a more elegant and speedier way. Because I need to execute this code a few thousand times in my script I want it to be as fast as possible.

error: value saveAsTextFile is not a member of Unit - Spark

I'm trying to save the results into a text file using:
results.collect().foreach { rule => println("[" + rule.antecedent.mkString(",") + "=>" + rule.consequent.mkString(",") + "]," + rule.confidence)}.saveAsTextFile("/user/cloudera/rules")
But I got this error:
<console>:43: error: value saveAsTextFile is not a member of Unit
results.collect().foreach { rule => println("[" + rule.antecedent.mkString(",") + "=>" + rule.consequent.mkString(",") + "]," + rule.confidence)}.saveAsTextFile("/user/cloudera/rules")
What I need to change? I don't understand the error...
If you want to save use:
results.map { rule =>
"[" + rule.antecedent.mkString(",") + "=>" + rule.consequent.mkString(",") + "]," + rule.confidence
}.saveAsTextFile("/user/cloudera/rules")
The foreach operation returns a Unit, which is a stand-in for an empty return value:
scala> val a = (0 to 5).foreach(println)
0
1
2
3
4
5
a: Unit = ()
If you want to save your original results you will need to use something like:
results.collect.saveAsTextFile(...)
Otherwise if you are trying to apply an operation to each element of results.collect and then save the result, then you will need to use a map and do something else to each element (because print also returns a Unit).
I got the same error message when I had initialized the variable with spark.read instead of sc. One of them returns a DataSet that doesn't have the saveAsTextFile method, the other one returns an RDD that does. Hope it helps someone.

Pick data from variable via .substring(10,20) error with the value greater than 10 in powershell [duplicate]

This question already has answers here:
$string.Substring Index/Length exception
(3 answers)
Closed 6 years ago.
Why cant I get the data from "$final.Substring(10,23)" and "$final.Substring(24,31)"?
It looks like it will fail as soon I'm past the range of 9.
The error I get is as follows..
Exception calling "Substring" with "2" argument(s): "Index and length
must refer to a location within the string. Parameter name: length" At
line:34 char:1
+ $thirdOct = $final.Substring(10,23)
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : NotSpecified: (:) [], MethodInvocationException
+ FullyQualifiedErrorId : ArgumentOutOfRangeException
$final = "01234567890123456789012345678901"
$firstOct = $final.Substring(0,8)
$secondOct = $final.Substring(8,16)
$thirdOct = $final.Substring(10,23)
$fourthOct = $final.Substring(24,31)
Write-Host $firstOct
Write-Host $secondOct
Write-Host $thirdOct
Write-Host $fourthOct
The second parameter is length, not endindex.
$final.Substring.OverloadDefinitions
string Substring(int startIndex)
string Substring(int startIndex, int length)
PS-ADMIN > $final.Length
32
PS-ADMIN > 10+23
33

Pre-increment and post-increment operators in Swift

//Post and Pre-Increment Test
func FindValueOFC() -> String
{
var a : Int = 10
var b : Int = 20
var c = a++ + a++ + b++ + b++ + ++a + ++b
return "The value Of variable C is \(c)"
}
let whatsTheValueOfC = FindValueOFC()
println(whatsTheValueOfC)
Why does this program prints out The value Of variable C is 98?
Logically it should be 96, as a++ + a++ + b++ + b++ + ++a + ++b can be translated to 10+11+20+21+12+22 = 96
Please don't ever do this in a real program. It leads to undefined behavior when you mix multiple mutators in the same expression. There is nothing in the language that guarantees that the pre-increment operator happens immediately before the value is accessed or that the post-increment operator happens immediately after the variable is accessed.
The compiler could have done the pre-increment of a and b first, added up all of the values, and then applied the post-increments. This would have given the result of
11 + 11 + 21 + 21 + 11 + 21 = 96
The point being that many answers are possible and valid, hence the name undefined behavior. It is possible that you would get different answers with different levels of compiler optimization, which could lead to very puzzling differences between your testing and shipping versions of your app.