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
New Yorp New Yorp
Jul 18, 2003

Only in Kenya.
Pillbug

FISHMANPET posted:

I'm writing an Azure runbook that's going to validate a spreadsheet of customer data to make sure the data meets various conditions (make sure every email address is actually an email address, make sure the data matches up with our inventory, etc). It's a series of for each loops that loop through testing every row for whatever the condition is. I'd really like to pesterize this but I can't figure out any way to do it. I can break each test into a function, and I can write a pester test against that function, but I have no idea what the "best" way to actually run the tests is. The functions aren't exported, they only exist within the script. I don't want to put them in a module or something like that, because they serve no purpose outside of this runbook. I don't really want to have the functions external to the runbook in anyway because I don't want to have extra runbooks hanging out that only exist to be a source of functions.

It seems like there's no way for Pester to extract the functions from a script to test them without also executing the rest of the script, so the question becomes what's the best hacky work around.

The corrected answer is "module".

Adbot
ADBOT LOVES YOU

FISHMANPET
Mar 3, 2007

Sweet 'N Sour
Can't
Melt
Steel Beams

New Yorp New Yorp posted:

The corrected answer is "module".


FISHMANPET posted:

I don't want to put them in a module or something like that, because they serve no purpose outside of this runbook.

New Yorp New Yorp
Jul 18, 2003

Only in Kenya.
Pillbug
Your desire doesn't change that it's the correct solution.

FISHMANPET
Mar 3, 2007

Sweet 'N Sour
Can't
Melt
Steel Beams
Doesn't making a highly specific module just for a single script go against the principal of writing functions to be as modular as possible?

New Yorp New Yorp
Jul 18, 2003

Only in Kenya.
Pillbug

FISHMANPET posted:

Doesn't making a highly specific module just for a single script go against the principal of writing functions to be as modular as possible?

No, the two things aren't related at all. Modules enable reuse across multiple consuming scripts. In this case, your scenario for reuse is "testing".

Judge Schnoopy
Nov 2, 2005

dont even TRY it, pal

FISHMANPET posted:

Doesn't making a highly specific module just for a single script go against the principal of writing functions to be as modular as possible?

Write your functions more broadly then, so they can be used on similar reports in the future if the need arises. Have one highly specific function that ties all your pieces together for this specific report.

Then you can pester the underlying worker functions that you might end up sharing later.

CLAM DOWN
Feb 13, 2007




FISHMANPET posted:

Doesn't making a highly specific module just for a single script go against the principal of writing functions to be as modular as possible?

I feel personally attacked

PierreTheMime
Dec 9, 2004

Hero of hormagaunts everywhere!
Buglord
I got an ask to validate and custom sort input based on an expected list of values, but I'm not sure if there's a simpler way to do what I did. While it certainly works, it seems a little lengthy for what I'm trying to do. Can anyone tell me if this is fine or what improvements could be made?

code:
$UserInput = "MARYLAND, GEORGIA,   florida ,norTH CAROLINA,CHEESESTEAK,FLORIDA"

$ValidLocations = @{ "1" = "FLORIDA";"2" = "GEORGIA";"3" = "SOUTH CAROLINA";"4" = "NORTH CAROLINA";"5" = "VIRGINIA";"6" = "MARYLAND" }
$LocationTable = @{}
ForEach ($Key in $ValidLocations.Keys) { $LocationTable.Add($Key,"") }
$SortedLocations = @()

$CustomerLocations = ($UserInput).ToUpper() -Split(",")

ForEach ($Location in $CustomerLocations) {
	$TrimmedLocation = $Location.Trim()
	If ($ValidLocations.ContainsValue($TrimmedLocation)) {
		ForEach ($Key in ($ValidLocations.GetEnumerator() | Where-Object { $_.Value -Eq $TrimmedLocation})) {
			If ($LocationTable.ContainsValue($TrimmedLocation)) {
				Write-Host "Location $TrimmedLocation is a duplicate and will not be added"
			} Else {
				$LocationTable["$($Key.Name)"] = $TrimmedLocation
			}
		}
	} Else {
		Write-Host "Location $TrimmedLocation is not valid and has been removed."
	}
}
For ($i = 0; $i -LE $ValidLocations.Keys.Count; $i++) {
	If (!([String]::IsNullOrEmpty($LocationTable["$i"]))) { $SortedLocations += $LocationTable["$i"] }
}
Return $SortedLocations -Join(",")

PierreTheMime fucked around with this message at 16:26 on Apr 23, 2019

mystes
May 31, 2006

PierreTheMime posted:

I got an ask to validate and custom sort input based on an expected list of values, but I'm not sure if there's a simpler way to do what I did. While it certainly works, it seems a little lengthy for what I'm trying to do. Can anyone tell me if this is fine or what improvements could be made?

code:
$UserInput = "MARYLAND, GEORGIA,   florida ,norTH CAROLINA,CHEESESTEAK,FLORIDA"

$ValidLocations = @{ "1" = "FLORIDA";"2" = "GEORGIA";"3" = "SOUTH CAROLINA";"4" = "NORTH CAROLINA";"5" = "VIRGINIA";"6" = "MARYLAND" }
$LocationTable = @{}
ForEach ($Key in $ValidLocations.Keys) { $LocationTable.Add($Key,"") }
$SortedLocations = @()

$CustomerLocations = ($UserInput).ToUpper() -Split(",")

ForEach ($Location in $CustomerLocations) {
	$TrimmedLocation = $Location.Trim()
	If ($ValidLocations.ContainsValue($TrimmedLocation)) {
		ForEach ($Key in ($ValidLocations.GetEnumerator() | Where-Object { $_.Value -Eq $TrimmedLocation})) {
			If ($LocationTable.ContainsValue($TrimmedLocation)) {
				Write-Host "Location $TrimmedLocation is a duplicate and will not be added"
			} Else {
				$LocationTable["$($Key.Name)"] = $TrimmedLocation
			}
		}
	} Else {
		Write-Host "Location $TrimmedLocation is not valid and has been removed."
	}
}
For ($i = 0; $i -LE $ValidLocations.Keys.Count; $i++) {
	If (!([String]::IsNullOrEmpty($LocationTable["$i"]))) { $SortedLocations += $LocationTable["$i"] }
}
Return $SortedLocations -Join(",")
If you want something that behaves exactly like what you have except that I changed the format for the validlocations hashtable (it prints the messages about invalid/duplicate input in the order of the input and uses a hashtable to check for duplicate input for efficiency) how about something like this?
code:
$UserInput = "MARYLAND, GEORGIA,   florida ,norTH CAROLINA,CHEESESTEAK,FLORIDA"
$ValidLocations = @{"FLORIDA" = 1 ;"GEORGIA"  = 2; "SOUTH CAROLINA" = 3; "NORTH CAROLINA" = 4 ; "VIRGINIA"  = 5; "MARYLAND" = 6}
$CustomerLocations = @{}

$UserInput.ToUpper() -Split(",") | % {$_.trim()} | % {
    if ($ValidLocations.Keys -notcontains $_) {
        Write-Host "Location $_ is not valid and has been removed."
    }
    elseif ($CustomerLocations.Keys -contains $_) {
        Write-Host "Location $_ is a duplicate and will not be added"
    }
    else {
        $CustomerLocations[$_] = $true
    }
}
($CustomerLocations.Keys | Sort-Object {$ValidLocations[$_]}) -join ","
Otherwise depending on the requirements you could just use sort-object -uniq or group-object or something and it could be a one liner depending on exactly what you need.

(You could also just use a list rather than a hashtable for the valid locations if they are sorted.)

mystes fucked around with this message at 17:26 on Apr 23, 2019

PierreTheMime
Dec 9, 2004

Hero of hormagaunts everywhere!
Buglord

mystes posted:

If you want something that behaves exactly like what you have except that I changed the format for the validlocations hashtable (it prints the messages about invalid/duplicate input in the order of the input and uses a hashtable to check for duplicate input for efficiency) how about something like this?
code:
$UserInput = "MARYLAND, GEORGIA,   florida ,norTH CAROLINA,CHEESESTEAK,FLORIDA"
$ValidLocations = @{"FLORIDA" = 1 ;"GEORGIA"  = 2; "SOUTH CAROLINA" = 3; "NORTH CAROLINA" = 4 ; "VIRGINIA"  = 5; "MARYLAND" = 6}
$CustomerLocations = @{}

$UserInput.ToUpper() -Split(",") | % {$_.trim()} | % {
    if ($ValidLocations.Keys -notcontains $_) {
        Write-Host "Location $_ is not valid and has been removed."
    }
    elseif ($CustomerLocations.Keys -contains $_) {
        Write-Host "Location $_ is a duplicate and will not be added"
    }
    else {
        $CustomerLocations[$_] = $true
    }
}
($CustomerLocations.Keys | Sort-Object {$ValidLocations[$_]}) -join ","
Otherwise depending on the requirements you could just use sort-object -uniq or group-object or something and it could be a one liner depending on exactly what you need.

No this is exactly what I was asking for. I hadn't thought to pipe the values through a chain like that, which helps flatten it out. Just using this as yet another learning exercise. Thanks!

mystes
May 31, 2006

I have a tendency to overuse ForEach-Object actually; It's probably better PowerShell style to use a foreach loop when it makes sense.

PierreTheMime
Dec 9, 2004

Hero of hormagaunts everywhere!
Buglord
You mentioned just sorting based on a list and not a hashtable; provided its simpler than the current method how would you go about that with a required order like the example? I only use hashtables when necessary, so I'd love to drop that as well.

mystes
May 31, 2006

PierreTheMime posted:

You mentioned just sorting based on a list and not a hashtable; provided its simpler than the current method how would you go about that with a required order like the example? I only use hashtables when necessary, so I'd love to drop that as well.
I meant that you could just rebuild the hashtable so you didn't have to enter numbers for each location:
code:
$ValidLocationsList = @("FLORIDA", "GEORGIA", "SOUTH CAROLINA", "NORTH CAROLINA", "VIRGINIA", "MARYLAND")
$ValidLocations = @{}
for ($i = 1; $i -lt $ValidLocationsList.Length; $i+=1) {
    $ValidLocations[$ValidLocationsList[$i]] = $i
}
But if you don't want to use hashtables at all, you could just as easily just do it with just the array for valid locations (it just means that you will have to search the list for each location when you sort) and an array to keep track of what locations you've seen:
code:
$UserInput = "MARYLAND, GEORGIA,   florida ,norTH CAROLINA,CHEESESTEAK,FLORIDA"

$ValidLocations = @("FLORIDA", "GEORGIA", "SOUTH CAROLINA", "NORTH CAROLINA", "VIRGINIA", "MARYLAND")

$CustomerLocations = @()

$UserInput.ToUpper() -Split(",") | % {$_.trim()} | % {
    if ($ValidLocations -notcontains $_) {
        Write-Host "Location $_ is not valid and has been removed."
    }
    elseif ($CustomerLocations -contains $_) {
        Write-Host "Location $_ is a duplicate and will not be added"
    }
    else {
        $CustomerLocations += $($_)
    }
}
($CustomerLocations | Sort-Object {$ValidLocations.IndexOf($_)}) -join ","

nielsm
Jun 1, 2009



Instead of $foo | % {$_.Trim()} you can simply write $foo | % Trim. Since Powershell 3 ForEach-Object can take the name of a member property or function and will just extract (or call) that on each object.

If you don't need the verbose output you can do just this:

code:
$UserInput = "MARYLAND, GEORGIA,   florida ,norTH CAROLINA,CHEESESTEAK,FLORIDA"
$ValidLocations = @{"FLORIDA" = 1 ;"GEORGIA"  = 2; "SOUTH CAROLINA" = 3; "NORTH CAROLINA" = 4 ; "VIRGINIA"  = 5; "MARYLAND" = 6}
$CustomerLocations = $UserInput.ToUpper() -Split "," | ForEach-Object Trim | Where-Object { $ValidLocations[$_] } | Sort-Object -Unique { $ValidLocations[$_] }
$CustomerLocations -Join ","

PierreTheMime
Dec 9, 2004

Hero of hormagaunts everywhere!
Buglord
As much as I like the succinct version, from a troubleshooting perspective I'll probably want to kick messages to the log, but it's cool to know that you can sort in order of unique keys that way.

Gucci Loafers
May 20, 2006

Ask yourself, do you really want to talk to pair of really nice gaudy shoes?


Has anyone had a problem where the Powershell ISE just starts skipping through the entire script and not running?

One of my first cmdlets is essentially $aadusers = Get-AzureADUser -all $true but it just doesn't run? I've already connected, authenticated, etc. It worked flawlessly last week.

EDIT - Well, I guess restarting the ISE along with re-connecting to Azure AD several times fixed it but drat that was one bizarre bug.

Gucci Loafers fucked around with this message at 20:10 on May 6, 2019

FISHMANPET
Mar 3, 2007

Sweet 'N Sour
Can't
Melt
Steel Beams
That's powershell telling you to use VS Code

mllaneza
Apr 28, 2007

Veteran, Bermuda Triangle Expeditionary Force, 1993-1952




You should totally be using VS Code. I'm as shocked as anyone that Microsoft is releasing cross-platform (Win, Mac, Linux) development tools that are actually good. I need to argue with the debugger some more to get good at it, but just having multiple editors open at once is a loving godsend (I do a lot with telling machine X to run a script hosted on file share Y). I do Powershell on Windows, and have it on my Mac laptop for my occasional foray into Python (BBEdit is good enough for bash).

xsf421
Feb 17, 2011

mllaneza posted:

You should totally be using VS Code. I'm as shocked as anyone that Microsoft is releasing cross-platform (Win, Mac, Linux) development tools that are actually good. I need to argue with the debugger some more to get good at it, but just having multiple editors open at once is a loving godsend (I do a lot with telling machine X to run a script hosted on file share Y). I do Powershell on Windows, and have it on my Mac laptop for my occasional foray into Python (BBEdit is good enough for bash).

MS is seriously trying to make macs obsolete for dev work, which I'm 100% for. (My company is 95% windows, but some of our special snowflake devs need their macbooks.)

https://code.visualstudio.com/blogs/2019/05/02/remote-development

You can now run your stuff in vscode remotely over ssh to a linux box, to a container, to your WSL linux installation, or in a hyper-v VM hosted on your machine. I do powershell, terraform, and bash all day, and vscode is a lifesaver.

New Yorp New Yorp
Jul 18, 2003

Only in Kenya.
Pillbug

mllaneza posted:

You should totally be using VS Code. I'm as shocked as anyone that Microsoft is releasing cross-platform (Win, Mac, Linux) development tools that are actually good. I need to argue with the debugger some more to get good at it, but just having multiple editors open at once is a loving godsend (I do a lot with telling machine X to run a script hosted on file share Y). I do Powershell on Windows, and have it on my Mac laptop for my occasional foray into Python (BBEdit is good enough for bash).

I love VS code but the powershell extension is loving awful and crashes every 15-20 minutes whenever I'm trying to use it to do any serious work.

I have seen this behavior across 4 different computers.

The Fool
Oct 16, 2003


New Yorp New Yorp posted:

I love VS code but the powershell extension is loving awful and crashes every 15-20 minutes whenever I'm trying to use it to do any serious work.

I have seen this behavior across 4 different computers.

For me the powershell debugger crashes every 3rd or 4th time I launch it.

Gucci Loafers
May 20, 2006

Ask yourself, do you really want to talk to pair of really nice gaudy shoes?


VS Code is awesome but my current client refuses to update it enough to be useful. :smith:

I've used it on a few other projects and it's pretty drat close to replacing the whole ISE. Not quite there yet completely but pretty drat close.

Scaramouche
Mar 26, 2001

SPACE FACE! SPACE FACE!

Might as well post this here. I'm hoping to automate grabbing some shopify product information via their API and dump/display it somewhere so it can be compared against a database. This is mostly half-assed together from other people's scripts, and the first part works (connecting/retrieving) and what errors out is actually using/displaying what comes down in any usable fashion:
code:
$Uri = "https://blahdeblah.myshopify.com/admin/products.json"
$apikey = "blah de blah"
$password = "blah de blah"
$headers = @{"Authorization" = "Basic "+[System.Convert]::ToBase64String([System.Text.Encoding]::UTF8.GetBytes($apikey+":"+$password))}

write-output Invoke-RestMethod -Uri $uri -ContentType "application/json" -Method Get -Headers $headers -UseBasicParsing | ConvertFrom-Json
so everything works until the last line; if I just assign the output of Invoke-RestMethod I get a truncated string of stuff (which is accurate/valid), so I was hoping to parse the JSON in powershell itself. I'm only interested in the two values of sku and fulfillment service.

The JSON is 'valid' in the sense that I normally take this output and manually parse it in MSSQL using JSON_VALUE/OPENJSON, but powershell doesn't seem to like it saying:
code:
ConvertFrom-Json : Invalid JSON primitive: Invoke-RestMethod.
At C:\ProdCheck.ps1:6 char:106
+ ... cation/json" -Method Get -Headers $headers | ConvertFrom-Json
+                                                  ~~~~~~~~~~~~~~~~
    + CategoryInfo          : NotSpecified: (:) [ConvertFrom-Json], ArgumentException
    + FullyQualifiedErrorId : System.ArgumentException,Microsoft.PowerShell.Commands.ConvertFromJsonCommand
Googling around I'm seeing a lot of people running into the problem using get-content (to read files locally) and solving it by using -Raw and/or removing line breaks, but I was hoping to do this relatively "natively" since I know it's good JSON coming down the pipe from the Invoke-RestMethod?

Ideally I'd like the output to look like:
SKU : fulfillment_service
1 : yes
2: no

etc etc. if anyone wants to make it even fancier with say CSV-output or the like.

The Fool
Oct 16, 2003


I suspect that Invoke-RestMethod is returning a PSObject and ConvertFrom-JSON is expecting a JSON formatted string.

e: Back at a computer. Let's try a few things:

code:
 Invoke-RestMethod [url]https://jsonplaceholder.typicode.com/comments[/url] | Get-Member

   TypeName: System.Object[]
Data is returned as an array of objects. But that is probably why you threw in the Write-Output.

code:
Write-Output Invoke-RestMethod https://jsonplaceholder.typicode.com/comments | Get-Member

   TypeName: System.String
Ok, but I don't think that's doing what you want either:

code:
Write-Output Invoke-RestMethod https://jsonplaceholder.typicode.com/comments
Invoke-RestMethod
https://jsonplaceholder.typicode.com/comments
Yeah, that's not even giving us results, much less JSON formatted results.

Let's just do this:
code:
Invoke-RestMethod https://jsonplaceholder.typicode.com/comments | ConvertTo-Json
Now this gets you a JSON formatted string.

But Invoke-RestMethod is already producing your PSObject for you, if you wanted to select specific properties you can do this:
code:
(Invoke-RestMethod https://jsonplaceholder.typicode.com/comments) | Select name, email | ConvertTo-Json
And if you wanted to outpout as a csv, you just change your output:
code:
(Invoke-RestMethod https://jsonplaceholder.typicode.com/comments) | Select name, email | ConvertTo-CSV

The Fool fucked around with this message at 23:19 on May 7, 2019

mystes
May 31, 2006

To put it more briefly, I think the main point is that Invoke-RestMethod is equivalent to Invoke-WebRequest | ConvertFrom-Json so you don't need to pipe Invoke-RestMethod to ConvertFromJson.

The Fool
Oct 16, 2003


mystes posted:

To put it more briefly, I think the main point is that Invoke-RestMethod is equivalent to Invoke-WebRequest | ConvertFrom-Json so you don't need to pipe Invoke-RestMethod to ConvertFromJson.

In addition, Invoke-RestMethod and ConvertFrom-Json to weird things to the pipeline in order to properly unroll arbitrary length JSON objects.

Judge Schnoopy
Nov 2, 2005

dont even TRY it, pal

Scaramouche posted:

since I know it's good JSON coming down the pipe from the Invoke-RestMethod?

A dangerous assumption to make.

It definitely returns a psobject. Powershell json shows up as a type of string, and is generally not operable by other powershell commands.

You can operate on the object returned by invoke-restmethod directly.

Scaramouche
Mar 26, 2001

SPACE FACE! SPACE FACE!

Hey! Thanks guys; The Fool especially, I quite liked seeing the iteration of outputs and seeing the differences between them.

I do believe the prevailing theory here is correct, I was trying to do some things but after the ConvertFrom-JSON when I should have been manipulating it natively as the PSO object from the Rest-Invoke method. I've got "an" output now, just need to tweak things so it is "the" output I want. I'm also doing some array within array stuff, so I foresee some for each coming up in my future.

Happiness Commando
Feb 1, 2002
$$ joy at gunpoint $$

Work is willing to pay for some training. Before I started this job (and using powershell every day), I tried working my way through the month of lunches book and never finished. I imagine the right move is for me to start it again and finish it this time, and then look at the toolmaking book too.

What do I do after that?

Wizard of the Deep
Sep 25, 2005

Another productive workday
It really depends on what you want to accomplish. Off the top of my head, I'd suggest some basic Azure training (when Microsoft gets their certification path figured out), which uses PowerShell for 93.3% of what you want to do.

Pile Of Garbage
May 28, 2007



Happiness Commando posted:

Work is willing to pay for some training. Before I started this job (and using powershell every day), I tried working my way through the month of lunches book and never finished. I imagine the right move is for me to start it again and finish it this time, and then look at the toolmaking book too.

What do I do after that?

IMO once you learn the language fundamentals the next step is learning how to use the myriad core and product-specific (e.g. Active Directory, Exchange, SharePoint, PowerCLI, etc.) cmdlets that are available as well as some of the more advanced language features that are described in the about pages.

When I was starting out with PowerShell I found that I learnt the fastest when I was doing things related to my work. Whenever you approach an activity take a moment to see whether it can be done with PowerShell and then try that out (Or refuse to deploy anything other than Server Core so that you're forced to use PowerShell :getin:).

Even better is when you identify an inefficient process that can be optimised or even fully automated with PowerShell. Specific to training perhaps you could talk to your employer about being granted time to work on optimisations like that to both improve your ability and provide value.

Also once you've finished Month of Lunches convince your employer to shell-out for a copy of PowerShell in Depth which is also by Don Jones. It's very thorough and teaches some good design patterns for extending the utility of the code that your write.

klosterdev
Oct 10, 2006

Na na na na na na na na Batman!
Learned about a cool PS script that I can use to figure out Windows 7 usage in my environment. https://gallery.technet.microsoft.com/Get-ADComputerInfops1-b5b3e656 Tried running it on a '08 R2 AD test server (with AD module imported), and all it spit out was a single column named "Length" with a bunch of three digit numbers. Can't find any use examples, does anybody know if there's any switches I need to suffix to ./Get-ADComputerInfo.ps1 ?

Wizard of the Deep
Sep 25, 2005

Another productive workday
Reading through that script, it doesn't look like it accepts any passed information. Is there something specific you need it to do?

If you just have one domain, you should be able to use something like the below to get your Win7 count:

code:
Get-ADcomputer -server $yourFavoriteDC -filter {((OperatingSystem -like '*7*')) -and (LastLogonDate -ge $SomeReasonableTimeframe)} -properties * | select Name,DistinguishedName,LastLogonDate,OperatingSystem,operatingsystemversion,enabled | export-csv $whereTheCSVShouldGo -notypeinformation -noclobber
Use "Get-ADComputer -Name <one specific name> -Properties *" to see all the properties you can select.

klosterdev
Oct 10, 2006

Na na na na na na na na Batman!

Wizard of the Deep posted:

Reading through that script, it doesn't look like it accepts any passed information. Is there something specific you need it to do?

If you just have one domain, you should be able to use something like the below to get your Win7 count:

code:
Get-ADcomputer -server $yourFavoriteDC -filter {((OperatingSystem -like '*7*')) -and (LastLogonDate -ge $SomeReasonableTimeframe)} -properties * | select Name,DistinguishedName,LastLogonDate,OperatingSystem,operatingsystemversion,enabled | export-csv $whereTheCSVShouldGo -notypeinformation -noclobber
Use "Get-ADComputer -Name <one specific name> -Properties *" to see all the properties you can select.

That worked perfectly actually, thanks!

Am I using the second thing you provided correctly?

code:
Get-ADComputer -Name LABTEST-1630DT -Properties *
It just spits out A parameter cannot be found that matches parameter name 'Name'

Wizard of the Deep
Sep 25, 2005

Another productive workday
You were using it right, I just gave you the wrong switch. Replace -name with -identity, I think.

Use "get-help get-adcomputer" to get a better idea of how to use the command. You may have to run update-help from an elevated/administrator PowerShell instance.

klosterdev
Oct 10, 2006

Na na na na na na na na Batman!

Wizard of the Deep posted:

You were using it right, I just gave you the wrong switch. Replace -name with -identity, I think.

Use "get-help get-adcomputer" to get a better idea of how to use the command. You may have to run update-help from an elevated/administrator PowerShell instance.

-Identity works, thanks! I'll def take a look at what get-help shows me. The more accurate we can get our active W7 domain computer count for the big W10 upgrade, the happier the people above are going to be.

Wizard of the Deep
Sep 25, 2005

Another productive workday
For identifying active Win7 machines in the domain, I'd filter against PwdLastSet < 90 days. I think PwdLastSet syncs to all DCs, where LastLogonDate might not. I don't have an AD environment available right now to verify, though.

Mario
Oct 29, 2006
It's-a-me!

Wizard of the Deep posted:

Use "get-help get-adcomputer" to get a better idea of how to use the command.
Also Show-Command is great for discovering parameters.

Dirt Road Junglist
Oct 8, 2010

We will be cruel
And through our cruelty
They will know who we are

Wizard of the Deep posted:

Use "get-help get-adcomputer" to get a better idea of how to use the command. You may have to run update-help from an elevated/administrator PowerShell instance.

Also, if you don't have a test environment, using -WhatIf at the end of a command can tell you what it's going to do without it actually committing any actions.

Adbot
ADBOT LOVES YOU

Judge Schnoopy
Nov 2, 2005

dont even TRY it, pal

Dirt Road Junglist posted:

Also, if you don't have a test environment, using -WhatIf at the end of a command can tell you what it's going to do without it actually committing any actions.

Assuming the command supports shouldProcess and is built with the state-changing part of the function inside a shouldProcess or shouldContinue block.

It's a dangerous assumption for functions and scripts built in-house.

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