Register a SA Forums Account here!
JOINING THE SA FORUMS WILL REMOVE THIS BIG AD, THE ANNOYING UNDERLINED ADS, AND STUPID INTERSTITIAL ADS!!!

You can: log in, read the tech support FAQ, or request your lost password. This dumb message (and those ads) will appear on every screen until you register! Get rid of this crap by registering your own SA Forums Account and joining roughly 150,000 Goons, for the one-time price of $9.95! We charge money because it costs us money per month for bills, and since we don't believe in showing ads to our users, we try to make the money back through forum registrations.
 
  • Post
  • Reply
Submarine Sandpaper
May 27, 2007


What's the best way to terminate a script not using throw or exit?

Adbot
ADBOT LOVES YOU

Zaepho
Oct 31, 2013

Submarine Sandpaper posted:

What's the best way to terminate a script not using throw or exit?

break or return should do it

nielsm
Jun 1, 2009



Submarine Sandpaper posted:

What's the best way to terminate a script not using throw or exit?

Restart-Computer

Pile Of Garbage
May 28, 2007



Zaepho posted:

break or return should do it

Using return is the best practice. break exits "Foreach, For, While, Do, or Switch statements" and return exits a "function, script, or script block."

nielsm posted:

Stop-Computer -Confirm:$false -Force

ftfy

Flaggy
Jul 6, 2007

Grandpa Cthulu needs his napping chair



Grimey Drawer
Learn Windows PowerShell in a Month of Lunches

is this still the go to for learning powershell? Is there anything else out there that would be better?

slartibartfast
Nov 13, 2002
:toot:

Flaggy posted:

Learn Windows PowerShell in a Month of Lunches

is this still the go to for learning powershell? Is there anything else out there that would be better?

Month of Lunches is still widely used. I've sent it to a number of people at my company within the last year who asked to learn PS. If you'd like something a little more interactive, though, I'd recommend you also check out PSKoans, which is a little bit like a text-based adventure game that incrementally teaches you PS.

Flaggy
Jul 6, 2007

Grandpa Cthulu needs his napping chair



Grimey Drawer

slartibartfast posted:

Month of Lunches is still widely used. I've sent it to a number of people at my company within the last year who asked to learn PS. If you'd like something a little more interactive, though, I'd recommend you also check out PSKoans, which is a little bit like a text-based adventure game that incrementally teaches you PS.

Awesome, thank you!

xsf421
Feb 17, 2011

Flaggy posted:

Awesome, thank you!

Don Jones (author of that book) also has a fantastic course on CBT nuggets, if you can find a way to access that. There's probably a dozen coworkers of mine who've learned intermediate to expert level powershell from that course alone.

Flaggy
Jul 6, 2007

Grandpa Cthulu needs his napping chair



Grimey Drawer

xsf421 posted:

Don Jones (author of that book) also has a fantastic course on CBT nuggets, if you can find a way to access that. There's probably a dozen coworkers of mine who've learned intermediate to expert level powershell from that course alone.

Dang, that looks nice but is kind of spendy. 840 per year. That is bonkers.

Pile Of Garbage
May 28, 2007



slartibartfast posted:

Month of Lunches is still widely used. I've sent it to a number of people at my company within the last year who asked to learn PS. If you'd like something a little more interactive, though, I'd recommend you also check out PSKoans, which is a little bit like a text-based adventure game that incrementally teaches you PS.

That PSKoans thing appears to be nothing more than an interactive version of the PowerShell core about_* topics. It's implemented in Pester so zero guarantee that it will operate correctly in your environment and it doesn't allow real experimentation within the learning environment. And god help you if you're just learning and decide to take a look at the code in the underlying module.

IDK maybe I'm too cynical but this kind of stuff just doesn't seem useful. IMO a better approach is regular learning stuff peppered with problem solving (This script is hosed, fix it using concepts learned) and open design (Make a script that returns "thing" using the concepts you've learned) activities in a sandbox environment. That's the good poo poo but I don't know what provides that though so gently caress me in advance.

The Fool
Oct 16, 2003


If you want to get some practice in, Advent of Code is up and is fun.

Mute_Fish
Nov 9, 2009

The Fool posted:

If you want to get some practice in, Advent of Code is up and is fun.

Thanks for posting this. These puzzles are indeed a lot of fun and educational.

MF_James
May 8, 2008
I CANNOT HANDLE BEING CALLED OUT ON MY DUMBASS OPINIONS ABOUT ANTI-VIRUS AND SECURITY. I REALLY LIKE TO THINK THAT I KNOW THINGS HERE

INSTEAD I AM GOING TO WHINE ABOUT IT IN OTHER THREADS SO MY OPINION CAN FEEL VALIDATED IN AN ECHO CHAMBER I LIKE

Yeah it's awesome, I have found out how little I know about powershell very quickly...

Agrikk
Oct 17, 2003

Take care with that! We have not fully ascertained its function, and the ticking is accelerating.
I am basically brand spanking new to Powershell and am trying to edit the DNS settings of a NIC that I might not know the name of. This script will run on different AWS EC2 instance types and the adapter name and driver type can vary.


Right now I have :

code:
1. $adapterName = get-netadapter -Physical | where status -eq 'up'| Format-List -Property "Name"

2. Set-DnsClientServerAddress -InterfaceAlias $adapterName -ServerAddresses "10.1.1.10","10.2.1.10"
But it throws up a bunch of errors on $adapterName being an invalid adapter interface alias.

But when I run line 1 on its own the output is "Name : Ethernet0"

Somehow line 2 is picking up a bunch of different stuff that I don't see in "normal" output.


Before I get too deep into an X-Y problem here, am I even going about this the right way? Is there a better way to accomplish the task of setting DNS entries for the only active ethernet adapter?

xsf421
Feb 17, 2011

Agrikk posted:

I am basically brand spanking new to Powershell and am trying to edit the DNS settings of a NIC that I might not know the name of. This script will run on different AWS EC2 instance types and the adapter name and driver type can vary.


Right now I have :

code:
1. $adapterName = get-netadapter -Physical | where status -eq 'up'| Format-List -Property "Name"

2. Set-DnsClientServerAddress -InterfaceAlias $adapterName -ServerAddresses "10.1.1.10","10.2.1.10"
But it throws up a bunch of errors on $adapterName being an invalid adapter interface alias.

But when I run line 1 on its own the output is "Name : Ethernet0"

Somehow line 2 is picking up a bunch of different stuff that I don't see in "normal" output.


Before I get too deep into an X-Y problem here, am I even going about this the right way? Is there a better way to accomplish the task of setting DNS entries for the only active ethernet adapter?

Try:

code:

$adapterName = get-netadapter -Physical | where status -eq 'up' | select InterfaceAlias -ExpandProperty interfacealias

The second line should be fine, but you were pulling the "Name:" header in your first line, which was causing your error.

Agrikk
Oct 17, 2003

Take care with that! We have not fully ascertained its function, and the ticking is accelerating.

This worked. Thank you!

Inspector_666
Oct 7, 2003

benny with the good hair
I'm not 100% but I'm pretty sure you only ever want to use "Format-List" to make something human readable rather than when you're trying to pipe the value around.

nielsm
Jun 1, 2009



Agrikk posted:

Format-List -Property "Name"
This returns one or more formatting objects, that instruct the shell to print the object in a particular way.

code:
Select-Object Name
This creates a new object based on the input, the output object has a single "Name" property.

code:
Select-Object -ExpandProperty Name
This returns the value of the "Name" property of each input object.

code:
ForEach-Object Name
Same effect as the above, just expressed differently, and likely has different performance characteristics. This particular syntax only works in PowerShell 3 and later, but it can also be used to call methods on objects, rather than just extracting properties.

PierreTheMime
Dec 9, 2004

Hero of hormagaunts everywhere!
Buglord
How do you properly define JSON with nested/bracketed values in PowerShell? I have a number of processes that are using curl right now to make some REST calls, but I'd be happy to swap them over to Invoke-RestMethod and avoid using a third-part application.

Here's a payload formatted for CURL in PowerShell (using automation variables as well as PS variables):
code:
[{\"email\":\"${EmailAddress}\",\"enabled\":true,\"firstName\":\"${FirstName}\",\"lastName\":\"${LastName}\",\"emailVerified\":false,\"sendWelcomeEmailEnabled\":false,\"groupDetails\":[\"/APP\",\"' + $Group + '\"],\"attributes\":{\"tableau-username\":[\"' + $TableauSiteName + '-${EmailAddress}\"]},\"isUser\":\"true\"}]
I don't work with JSON often enough to know how to properly define this as a $Body object off the top of my head, but I'd appreciate it if someone could show me because I'm sure I'm just missing something simple.

The Fool
Oct 16, 2003


Is there a reason that ConvertTo-JSON and ConvertFrom-JSON wouldn't work for you?

Jowj
Dec 25, 2010

My favourite player and idol. His battles with his wrists mirror my own battles with the constant disgust I feel towards my zerg bugs.
I'll echo The Fool, that's what I would do. I will mention a weird finnicky thing:

code:
$jsonObjects = # pretend this is valid json that when converted from json has a name property.
$workingObjects = $jsonObjects | ConvertFrom-Json

# this must exist on a new line. I don't know why. 
# ConvertFrom-Json must just....not finish processing before piping fwd?
$workingObjects = $workingObjects | select -ExpandProperty name
To make sure that makes sense: ConvertFrom-Json must be the last section of a pipeline; i cannot pipe its output further along in one line, I have to split it up. its weird.

FISHMANPET
Mar 3, 2007

Sweet 'N Sour
Can't
Melt
Steel Beams
Also don't curl, use Invoke-RestMethod or Invoke-WebRequest if you can't use Invoke-RestMethod.

And Powershell can be weird with nested JSON, by default ConverTo-Json assumes 2 levels of bojects, but there is a depth flag to the cmdlet if your JSON is more nested than that.

PierreTheMime
Dec 9, 2004

Hero of hormagaunts everywhere!
Buglord
ConvertTo-JSON worked just fine, the issue was just formatting the line properly.

code:
$Body = @"
[{"email":"${EmailAddress}","enabled":true,"firstName":"${FirstName}","lastName":"${LastName}","emailVerified":false,"sendWelcomeEmailEnabled":false,"groupDetails":["/APP","' + $Group + '"],"attributes":{"tableau-username":["' + $TableauSiteName + '-${EmailAddress}"]},"isUser":"true"}]
"@ | ConvertTo-JSON
Now I just have to mess around with the other requirements of the endpoint, as it's still giving me a headache.

Edit: If anyone have experience with Keycloak calls I’d appreciate being shown where I’m wrong. I can get an auth token but my POST call using the token gets rejected. The same info works fine using curl, so it’s especially frustrating.

PierreTheMime fucked around with this message at 22:36 on Jan 10, 2019

Agrikk
Oct 17, 2003

Take care with that! We have not fully ascertained its function, and the ticking is accelerating.
Remember when they said that json formatting was poo poo but it doesn’t matter because no human would ever be editing it or interacting with it in any way?

Bruegels Fuckbooks
Sep 14, 2004

Now, listen - I know the two of you are very different from each other in a lot of ways, but you have to understand that as far as Grandpa's concerned, you're both pieces of shit! Yeah. I can prove it mathematically.

Agrikk posted:

Remember when they said that json formatting was poo poo but it doesn’t matter because no human would ever be editing it or interacting with it in any way?

the problem is that there's a paradox between "human readable" and "human editable" - JSON was touted as human readable, but you're really not supposed to be creating JSON through string concatenation because there are edge cases that will break the parser (and it becomes more likely to hit those the more complicated the object gets) - but people do it anyway and it mostly works until it doesn't, even though just creating an object and serializing it is easier code to write and will always generate valid JSON.

Methanar
Sep 26, 2013

by the sex ghost
json is more readable than yaml.

fight me

Pile Of Garbage
May 28, 2007



They're both shite, use whatever has a convenient conversion library for your language.

Or use XML :getin:

New Yorp New Yorp
Jul 18, 2003

Only in Kenya.
Pillbug

PierreTheMime posted:

ConvertTo-JSON worked just fine, the issue was just formatting the line properly.

code:
$Body = @"
[{"email":"${EmailAddress}","enabled":true,"firstName":"${FirstName}","lastName":"${LastName}","emailVerified":false,"sendWelcomeEmailEnabled":false,"groupDetails":["/APP","' + $Group + '"],"attributes":{"tableau-username":["' + $TableauSiteName + '-${EmailAddress}"]},"isUser":"true"}]
"@ | ConvertTo-JSON
Now I just have to mess around with the other requirements of the endpoint, as it's still giving me a headache.

Edit: If anyone have experience with Keycloak calls I’d appreciate being shown where I’m wrong. I can get an auth token but my POST call using the token gets rejected. The same info works fine using curl, so it’s especially frustrating.

You are hurting yourself by writing JSON by doing string concatenation. Use an associative array and convert it to JSON.

code:
$foo = @{
  email = $EmailAddress
  enabled = $true
  groupDetails = @( 'entry 1', 'entry 2')
  attributes = @{ key = 'value' }
}
Then push that through ConvertTo-Json to get a JSON string.

@() is a regular array
@{} is an associative array (hash table, key/value pair)

PierreTheMime
Dec 9, 2004

Hero of hormagaunts everywhere!
Buglord

New Yorp New Yorp posted:

You are hurting yourself by writing JSON by doing string concatenation. Use an associative array and convert it to JSON.

code:
$foo = @{
  email = $EmailAddress
  enabled = $true
  groupDetails = @( 'entry 1', 'entry 2')
  attributes = @{ key = 'value' }
}
Then push that through ConvertTo-Json to get a JSON string.

@() is a regular array
@{} is an associative array (hash table, key/value pair)

Thanks for this, this was the first way I tried it (as it’s obviously more human-friendly) but I’d screwed up the arrays and figured I’d do it in a more literal way to prove the call worked and come back to it later. Your example showed me where I made the mistake, so problem solved, at least in terms of the body content.

Jowj
Dec 25, 2010

My favourite player and idol. His battles with his wrists mirror my own battles with the constant disgust I feel towards my zerg bugs.

Methanar posted:

json is more readable than yaml.

fight me

i guess maybe depending on what you’re doing?

for “never needs to be human edited” usecases, ok maybe.

for like, configuration files that are always human edited though json loses because of comments

Dirt Road Junglist
Oct 8, 2010

We will be cruel
And through our cruelty
They will know who we are
Haha, one of my co-workers was struggling with pulling data out of a JSON return, and I was like, "Hold my beer, someone on the forums has the answer."

Judge Schnoopy
Nov 2, 2005

dont even TRY it, pal

Jowj posted:

i guess maybe depending on what you’re doing?

for “never needs to be human edited” usecases, ok maybe.

for like, configuration files that are always human edited though json loses because of comments

Why not have a json key of 'comment' for anything worth editing?

Jowj
Dec 25, 2010

My favourite player and idol. His battles with his wrists mirror my own battles with the constant disgust I feel towards my zerg bugs.
Strict checkers of json data / proximity to the thing you actually wanna comment IMO.

For instance: If you want to do something like configure an IAM policy in AWS through JSON, you can't just add a json key called "comment"; aws only allows certain keys within the thing. Which is a real pain if something is counter-intuitive and you want to comment it for posterity! You just! Can't!

loving json.

PierreTheMime
Dec 9, 2004

Hero of hormagaunts everywhere!
Buglord
How does one capture a dynamic image source as a local file? While it's deprecated and I can generate the chart using PS, I do like the ease and simplicity of the Google Chart API. That said, while the API call renders in a browser properly using the <img src=""> tag, I get a 400 error if I try to use a webclient call to retrieve it. I'm downloading the image file to add it as an inline-attachment to emails, as the render gets blocked by our email filter.

Example chart:
code:
https://chart.googleapis.com/chart?chs=600x300&amp;chco=86BC25&amp;chd=t:0.70,0.30&amp;cht=p&amp;chdl=Test1|Test2&amp;chl=70.10%|29.90%

The Fool
Oct 16, 2003


I wouldn't do it in Powershell, but maybe either C# or Python using something like Selenium

PierreTheMime
Dec 9, 2004

Hero of hormagaunts everywhere!
Buglord

The Fool posted:

I wouldn't do it in Powershell, but maybe either C# or Python using something like Selenium

Yeah, I considered other code but I've already got the rest of the script driven in shell and would prefer not to bounce around to different languages if I can help it. My current version that creates the chart through System.Windows.Forms.DataVisualization.Charting.Chart works fine, it's just not as polished and takes more code upfront.

mystes
May 31, 2006

PierreTheMime posted:

How does one capture a dynamic image source as a local file? While it's deprecated and I can generate the chart using PS, I do like the ease and simplicity of the Google Chart API. That said, while the API call renders in a browser properly using the <img src=""> tag, I get a 400 error if I try to use a webclient call to retrieve it. I'm downloading the image file to add it as an inline-attachment to emails, as the render gets blocked by our email filter.

Example chart:
code:
https://chart.googleapis.com/chart?chs=600x300&amp;chco=86BC25&amp;chd=t:0.70,0.30&amp;cht=p&amp;chdl=Test1|Test2&amp;chl=70.10%|29.90%
It looks like your url is double escaped. Replacing "&amp;" with "&" I can use wget on this url and it works fine. I don't know if this is the problem you were having specifically, but you may want to check for some sort of escaping problem.

The Fool posted:

I wouldn't do it in Powershell, but maybe either C# or Python using something like Selenium
I would definitely not recommend using selenium for this. The only reason to use selenium would be if Google was providing this service as an SPA or something rather than an api and you were trying to get around this (which probably wouldn't be a good idea).

mystes fucked around with this message at 20:08 on Jan 18, 2019

PierreTheMime
Dec 9, 2004

Hero of hormagaunts everywhere!
Buglord

mystes posted:

It looks like your url is double escaped. Replacing "&amp;" with "&" I can use wget on this url and it works fine. I don't know if this is the problem you were having specifically, but you may want to check for some sort of escaping problem.
Yep, that was it, thanks!

TITTIEKISSER69
Mar 19, 2005

SAVE THE BEES
PLANT MORE TREES
CLEAN THE SEAS
KISS TITTIESS




I need to find out how many AD users in a certain OU have extensionAttribute7 populated, and export this to a .csv file. I'm sure it'll start with Get-ADuser, but as a newb to this I'm having trouble fleshing out the rest. Can anyone help?

EDIT: The following gave me what I wanted, except from all of AD. Now trying to figure out how to get from just one OU

code:
Get-ADUser -filter * -properties extensionAttribute7 | Select-Object name, extensionAttribute7 | export-csv $dir$\ExAt7.csv -Encoding "Unicode"

TITTIEKISSER69 fucked around with this message at 19:19 on Jan 22, 2019

Adbot
ADBOT LOVES YOU

Inspector_666
Oct 7, 2003

benny with the good hair

TITTIEKISSER69 posted:

I need to find out how many AD users in a certain OU have extensionAttribute7 populated, and export this to a .csv file. I'm sure it'll start with Get-ADuser, but as a newb to this I'm having trouble fleshing out the rest. Can anyone help?

code:
Get-ADUser -Filter * -Properties extensionAttribute7 | Select Name,SamAccountName,extensionAttribute7 | Export-CSV -Path <WHEREVER YOU WANT TO PUT THE CSV> -NoTypeInformation
should get you the CSV showing the user's name, AD login, and the value of extensionAttribute7. This'll pull everybody in AD, you can then filter in Excel to not see any of the empty ones. That's the simplest way to do it.


EDIT: to answer the question of how to search in a specific OU, use the -SearchBase flag in Get-ADUser with the distinguished name of the OU.

  • 1
  • 2
  • 3
  • 4
  • 5
  • Post
  • Reply