r/PowerShell • u/[deleted] • Sep 17 '20
PowerShell vs Python Reference
https://blog.ironmansoftware.com/powershell-vs-python/11
Sep 17 '20 edited Oct 09 '20
I've been using PowerShell extensively since 2014 and I had no idea you could declare your arguments in the function definition's opening parentheses. I always did it like:
function ass
{
param
(
$has_donk = $true
)
}Even if this is better practice I'm just shocked I didn't know you could do it the "traditional" way.
4
Sep 17 '20
Learn something new every day! I had to look up some PS stuff when I was compiling this list and comparing it with Python.
0
Sep 17 '20
[deleted]
6
Sep 17 '20
Yeah, it's odd that you can define the function that way, but not call it. If I had a background in other programming languages before picking up PS that would have confused the hell out of me.
3
u/TheIncorrigible1 Sep 17 '20
And it does confuse plenty of newcomers every day. There are countless SO duplicates for this "problem"
4
u/Thotaz Sep 17 '20
never cmdlet(a, b)
Actually, you can do that:
Get-ChildItem("C:\")works just fine.8
5
u/azjunglist05 Sep 17 '20
Really awesome article! Just curious when getting a data type why:
$var = 1
$var | Get-MemberInstead of:
$var = 1
$var.GetType()The latter, to me at least, more resembles the Python equivalent. Get-Member does a lot more than to just the get the type of the object. It also pulls the methods and properties available to that object.
6
1
u/purplemonkeymad Sep 18 '20
The pipe "unrolls" collections that are input (iterates over the elements). This means that
Get-Memberis working on the members in an array, where as.GetType()is working on the array. eg:PS> $var = 1..4 PS> $var.GetType().tostring() System.Object[] PS> $var | Get-Member TypeName: System.Int32You can use
Get-Memberto get all possible members of a mixed type array.You don't want to choose the wrong one if you are testing for bad input or for multiple results.
2
u/Tiberius666 Sep 17 '20
Seeing this really makes me think I should seriously take up Python.
I've got quite a knack for Powershell, and although i'm not a dev by trade, spend quite a fair chunk of my working time creating scripts to help out various departments and seeing this shows it's not exactly a million miles away from Powershell's syntax which should make it quite easy to get to grips with.
1
Sep 17 '20
The use of white spaces to denote scope throws me off a lot but other than that the syntax is pretty similar.
2
u/Raymich Sep 18 '20 edited Sep 18 '20
You’ve been contributing a lot to Powershell community, dude, I think you should apply for Microsoft MVP title at some stage.
edit: on datatypes you can also use $var.GetType(), which is more similar to Python
3
Sep 18 '20
Thanks :)
I've already been granted the title so I'm glad my work is appreciated!
https://mvp.microsoft.com/en-us/PublicProfile/4040089?fullName=Adam%20Driscoll
2
u/artur-carvalho Sep 18 '20
Great reference, thank you! Some little corrections:
- you have typo: "adpated "
- lambda is missing a 5
- the formatting and formatting index is the same text. Typo right?
Anyway, hope this is helpful and thank you again!
3
Sep 18 '20
Thanks! Fixed.
The formatting\formatting index one is the same for PowerShell but not python. Python doesn't require the index if there is only one as I understand it. PowerShell always requires the index.
8
u/MrSnoobs Sep 17 '20
Honestly, even without the Python column, this is a fantastic overview of programmatic Powershell. Nice.
5
u/wtmh Sep 17 '20
Excellent. I am a PowerShell expert learning Python and constantly finding myself doing the "How do I do what I already know how to do?" check over and over.
Much appreciated.
4
4
1
3
3
Sep 17 '20
regarding:
PowerShell:
[string]myfunc() {
return "Hello my name is $($this.Name)"
}Python:
def myfunc(self):
print("Hello my name is " + self.name)print() doesn't return a string in Python.
5
u/prp7 Sep 17 '20
Does powershell have something like python's list comprehension?
a = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
print(a[1:10:2])6
u/bozho Sep 17 '20
It does, not always as terse as Python. Your example could be written as:
$a = @(1..10) $a | ? { $_ % 2 -eq 0 }I don't think there's a nice syntax to select every Nth element though. On the other hand, you can use LINQ for that :-)
4
u/TofuBug40 Sep 18 '20
The answers given so far using Where-Object (?) aren't really replicating what Python's notation is doing they are focusing on the VALUE of the item and not the POSITION of the item ( u/HeKis4's for loop is a valid answer) if you want to use the pipe line method what you need is
$a = ('a','b','c','d','e','f','g') $Step = 3 $a | Where-Object -FilterScript { $a.IndexOf($_) % $Step -eq 0 }THAT will do what the Python example above is doing step over the INDEXES of the array regardless of the values in said array
Yes its not as terse as a[0..9:3] but I would argue that pythons array split has a VERY limited use case base on the logic of iterating over an array based on a linear progression of the indexes, where as
Where-Objectcan do that as we've shown above but can ALSO do something like$Vowels = @('a','e','i','o','u','y') $a | Where-Object -FilterScript { $_ -in $Vowels }You need much more Python than a[0:10:2] to get that array result
What
Where-Objectlacks in the RAW terseness it MORE than makes up for in flexibility while still maintaining a respectable amount of terseness itself.2
2
u/setmehigh Sep 17 '20
What does that do?
4
u/DecentWalrus Sep 17 '20
a = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] print(a[1:10:2])Would result in printing
[2, 4, 6, 8, 10].The print function is being passed a slice of the list.
a[1:10:2]essentially means start at position 1 in list (in this case, that's the number 2) and go until position 9. 10 is used in this case because slicing will go up to position 10 but not including position 10. Position 9 in the list is the number 10. Lastly, the 2 tells python to print every other list item (print position 1, skip position 2, print position 3, skip position 4, etc.)0
u/setmehigh Sep 17 '20
Maybe I'm dumb, but why would you want to do this? I can't think of a reason, but I haven't run into a situation where I needed it either...
4
u/DecentWalrus Sep 17 '20
An example for slicing would be if you only wanted to grab the first three values of a list. For example, I have a list of names of people who ran a race. The list is already ordered by who finished first to who finished last. If I want to print the top three finishers, I'd do this:
Code:
finishers = ["Tom", "Sally", "Taylor", "Jack", "Ginger", "John"] print(f'The top three finishers are: {finishers[0:3]}')Result:
The top three finishers are: ['Tom', 'Sally', 'Taylor']Now you could go the extra step of actually formatting that properly and such but it's just a simple way to grab a slice of the list.
As for using the step option, it allows for quick access to, for example, all odd or even positioned values in the list. The simplest example is the one given in the original comment where you may need to count by 2s.
2
u/omers Sep 17 '20 edited Sep 17 '20
finishers[0:3]
That's reproducible in PS with
..or a list of indicies.C:\> $finishers = @("Tom", "Sally", "Taylor", "Jack", "Ginger", "John") C:\> $finishers[0..2] Tom Sally Taylor C:\> $finishers[0,1,2] Tom Sally TaylorEvery n-th I do not believe is possible without using /u/bozho's method or a loop... You can "compress" (remove the pipeline) bozho's method to this:
$finishers.Where({$finishers.IndexOf($_) % 2 -eq 0})but it's still not clean like in some other languages.In a script where keeping it to one line isn't an issue I'd probably do something like this:
$Finishers = @("Tom", "Sally", "Taylor", "Jack", "Ginger", "John") $OddIndicies = @(0..$Finishers.GetUpperBound(0)) | ? {$_ % 2 -eq 0} $Finishers[$OddIndicies]1
u/blooping_blooper Sep 18 '20
for that specific case couldn't you also do
$Finishers | select -first 33
u/HeKis4 Sep 17 '20
Gets every other list elements from the 1st to the 10th (0-indexed of course, we're not savages).
As a for loop, it would look like
for(int i=1; i<10; i+=2) { a[i] }1
u/HeKis4 Sep 17 '20
Afaik it doesnt. Your code would either filter out every other element like what has already been posted or use a for loop with
$i += 2at the end.
4
u/ihaxr Sep 17 '20
This is great! I'm sure it'll help a lot of people out, Python <=> PowerShell isn't the easiest thing in the world to translate
For arrays, we should really stop using ArrayList in favor of a generic list:
$arr = [System.Collections.Generic.List[string]]@('Hello', 'World')
$arr.RemoveAt($arr.Count-1)It'll save memory and avoid some casting errors (probably not an issue in PowerShell, but is for the rest of .NET)
Also for the dictionaries part, maybe adding in how you loop through each key=value pair (have to use .GetEnumerator() in PowerShell):
# This won't work:
$thisdict = @{
brand = "Ford"
model = "Mustang"
year = 1964
}
$thisdict | ForEach-Object {
Write-Host "key is $($_.key) ; value is $($_.value)"
}
#This will!
$thisdict = @{
brand = "Ford"
model = "Mustang"
year = 1964
}
$thisdict.GetEnumerator() | ForEach-Object {
Write-Host "key is $($_.key) ; value is $($_.value)"
}2
u/TofuBug40 Sep 18 '20
That's because you're piping a SINGLE object to
ForEach-Object; JUST$thisdict. its not treating it as an arrayWhat you want is
$thisdict.Keys | ForEach-Object { "Key is $_ ; Value is $($thisdict[$_])" }Where PowerShell really trips a lot of people up especially people that might not have a complete functional understanding of the difference between an array and a dictionary (hashtable technically) is in what its actually looking at vs what we think its looking at.
For instance
1..10 | ForEach-Object { $_ }is an array (or if you want to go fully down to the metal anIEnumerablee.g. something you can enumerate over that's because if we call(1..10).GetType()we getIsPublic IsSerial Name BaseType -------- -------- ---- -------- True True Object[] System.ArrayBut if I call the same type check on
$thisdict.GetType()we getIsPublic IsSerial Name BaseType -------- -------- ---- -------- True True Hashtable System.ObjectThat's why
ForEach-Objectdoesn't understand$_.Keyor$_.Valueit was passed basically a single value array and $thisdict is the only item in that array and those aren't valid properties of the HastTable Object. We THINK of it as just a list but its actually an object with TWO lists as properties of that object and toForEach-Object, andWhere-Objectand ALL the otherIEnumerablebased Cmdlets THAT makes all the difference
2
2
u/ssnani Sep 17 '20
Great article! Thank you for that! There was a lot that I would do different with powershell, but that really helpful!
2
2
u/Test-NetConnection Sep 17 '20
Why the hell does python require you to enclose numbers in quotes when casting? That syntax is reserved for strings!
2
u/yardshop Sep 18 '20
It doesn't, those examples just show casting strings to different numerical types.
You can also cast an int to a float or vice versa, either from literals or other variables:
f = float(10) i = int(f) i = int(3.14)
2
u/jftuga Sep 18 '20
Python 3.6 added f-strings:
Instead of:
print(fname + " " + lname)you would use this:
print(f"{fname} {lname}")Python 3.8 improves this by allowing the = for self-documenting expressions and debugging
For example:
domain="reddit.com"
print(f"{domain=}")Would output:
domain='reddit.com'
30
u/[deleted] Sep 17 '20
I've been spending some time learning Python and have put together a PowerShell vs Python reference for various language features.