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
kiwid
Sep 30, 2013

How does one get a list of proxyAddresses from AD with the users name with each proxyAddress in a separate row?

For example:

pre:
|  name  |     proxyAddress    |
--------------------------------
|  user1 |  email1@domain.com  |
|  user1 |  email2@domain.com  |
|  user1 |  email3@domain.com  |
|  user2 |  email1@domain.com  |
|  user3 |  email1@domain.com  |
|  user1 |  email2@domain.com  |
|  user4 |  email1@domain.com  |

Adbot
ADBOT LOVES YOU

CLAM DOWN
Feb 13, 2007




kiwid posted:

How does one get a list of proxyAddresses from AD with the users name with each proxyAddress in a separate row?

For example:

pre:
|  name  |     proxyAddress    |
--------------------------------
|  user1 |  email1@domain.com  |
|  user1 |  email2@domain.com  |
|  user1 |  email3@domain.com  |
|  user2 |  email1@domain.com  |
|  user3 |  email1@domain.com  |
|  user1 |  email2@domain.com  |
|  user4 |  email1@domain.com  |

Pipe it into Format-Table?

kiwid
Sep 30, 2013

CLAM DOWN posted:

Pipe it into Format-Table?

Doesn't seem to work since proxyAddresses is a multi-value attribute.

Virigoth
Apr 28, 2009

Corona rules everything around me
C.R.E.A.M. get the virus
In the ICU y'all......



kiwid posted:

Doesn't seem to work since proxyAddresses is a multi-value attribute.

Foreach loop the attributes and then output?

skipdogg
Nov 29, 2004
Resident SRT-4 Expert

kiwid posted:

How does one get a list of proxyAddresses from AD with the users name with each proxyAddress in a separate row?

For example:

pre:
|  name  |     proxyAddress    |
--------------------------------
|  user1 |  email1@domain.com  |
|  user1 |  email2@domain.com  |
|  user1 |  email3@domain.com  |
|  user2 |  email1@domain.com  |
|  user3 |  email1@domain.com  |
|  user1 |  email2@domain.com  |
|  user4 |  email1@domain.com  |

We're an O365 shop as well, so we've done a lot with powershell and AD/Exchange.

For this issue, I basically stole the solution from this blog. Multivalue properties can be a little bit of a pain. My buddy at work is our 'powershell master' and he even wrote something that just pulls the @onmicrosoft.com proxy address from a user object.

http://blogs.technet.com/b/heyscriptingguy/archive/2013/07/22/export-user-names-and-proxy-addresses-to-csv-file.aspx

To comment on one of your previous posts

kiwid posted:

So, we've recently changed our policy for our help desk to start filling in all the fields in an Active Directory user that we never really cared about before, such as organization information, addresses, phone numbers, etc. We've also moved to Office 365 which requires manually editing the proxyAddresses attribute for alias email addresses. They aren't very consistent with filling this information out and often forget to connect home drives and poo poo. I want to create a dummy proof PowerShell script that goes through the process of creating a new user but my experience with PowerShell is running one off commands. If you guys had to choose one book (maybe two), to learn PowerShell (especially syntax), what would it be?

Powershell in a month of lunches is really good. I would start there.

We have some user onboard scripts written in powershell that completely automate the new user creation process, but they're written for bulk new users in our call center environment where 20,40,60 people have mostly the same attributes.

If you can organize the data into a CSV file though, it's pretty easy to automate. You could also just write a script that prompts for each bit of data, that might work better.

Helpdesk dude runs new_user.ps1 and then it prompts for

First Name
Last Name
Logon Name
Email Address
<whatever else you want>
etc.

Then you can throw in some logging, it's really just a matter of what you want to do with powershell.

kiwid
Sep 30, 2013

skipdogg posted:

We're an O365 shop as well, so we've done a lot with powershell and AD/Exchange.

For this issue, I basically stole the solution from this blog. Multivalue properties can be a little bit of a pain. My buddy at work is our 'powershell master' and he even wrote something that just pulls the @onmicrosoft.com proxy address from a user object.

http://blogs.technet.com/b/heyscriptingguy/archive/2013/07/22/export-user-names-and-proxy-addresses-to-csv-file.aspx

Awesome thanks, yeah I saw that blog but we have accounts with like 40 alias email addresses. I did modify his script though and then just end up using Excel's Text to Columns feature.

This is the command I used:

code:
get-aduser -Filter * -SearchBase '[redacted]' -properties * |
	Select-Object DisplayName, Name, UserPrincipalName, @{L = "ProxyAddresses"; E = { $_.ProxyAddresses -join "^"}} |
	Export-Csv C:\proxyAddresses.csv

skipdogg posted:

To comment on one of your previous posts

Powershell in a month of lunches is really good. I would start there.

We have some user onboard scripts written in powershell that completely automate the new user creation process, but they're written for bulk new users in our call center environment where 20,40,60 people have mostly the same attributes.

If you can organize the data into a CSV file though, it's pretty easy to automate. You could also just write a script that prompts for each bit of data, that might work better.

Helpdesk dude runs new_user.ps1 and then it prompts for

First Name
Last Name
Logon Name
Email Address
<whatever else you want>
etc.

Then you can throw in some logging, it's really just a matter of what you want to do with powershell.

Having a script prompt for everything would ideally be the best way for our help desk to do this. Then at the end of the script, list all the information and ask if everything is correct and to submit or if something is wrong/mistyped, cancel, or better yet, allow them to fix that attribute. I have no idea how to do this though. My programming skills are limited to PHP.

12 rats tied together
Sep 7, 2006

You can pipe your Get-ADuser into a nested foreach to get that, but the big question is "Why?" since you can output to csv or a text file (or actually do something with the addresses) much easier than trying to display a formatted table in the shell window. In any case, I had to play with it a little and here's what I got (it's a bit messy)

code:
Get-ADUser -Identity whatever -Properties * | % {
    $username = $_.samaccountname
        foreach ($proxadd in $_.proxyaddresses) {
            Write-Host "$Username | $proxadd"
            }
}

quote:

Having a script prompt for everything would ideally be the best way for our help desk to do this. Then at the end of the script, list all the information and ask if everything is correct and to submit or if something is wrong/mistyped, cancel, or better yet, allow them to fix that attribute. I have no idea how to do this though. My programming skills are limited to PHP.

It would be pretty simple to brute force your way through this. Have a bunch of hardcoded variables, Read-Host to set the variables to whatever you want, and then use New-ADuser and Set-ADuser to apply the appropriate information to the appropriate place.

e: The only gotcha with this is that I believe setting extension attributes (or in general, any weird AD attribute) requires you to pass a hash table or some other weird thing. I don't believe it's as easy as Set-ADUser -extensionattribute1 Foo -extensionattribute2 Bar, and so on. I haven't really played with it myself, though.

12 rats tied together fucked around with this message at 19:31 on Apr 17, 2014

kiwid
Sep 30, 2013

Reiz posted:

It would be pretty simple to brute force your way through this.

Alright, so I spent today brute forcing together a script and it works pretty well. However, there is one thing I don't know how to validate. At the end of the script when I actually execute the New-ADUser command, how can I tell programmatically if it was successful or failed? Does the command have any return codes to check?

The only thing I can think of is to immediately run a Get-ADUser command to see if the new account exists.

FISHMANPET
Mar 3, 2007

Sweet 'N Sour
Can't
Melt
Steel Beams
You could use -PassThru, which will return the created object. My guess is that if it fails it will just fail and die out.

CLAM DOWN
Feb 13, 2007




I'm drawing a blank with what I'm pretty sure is a simple thing, it's driving me nuts.

I want to import a CSV, iterate through each line, if there are multiple entries on a line separated by a semicolon, split them up into multiple lines, and write them to a new file.

Input file looks like this:

code:
property
value1;value2
value!
valuea;valueb;valuec
etc

code:
$inputcsv = import-csv path\input.csv
foreach ($line in $inputcsv)
{
    $splitline = $line.'property'.Split(";")
    $splitline    #debug echo
    $outputcsv += $splitline
}
$outputcsv | export-csv -path path\output.csv
What do I do here to make that output display in the file correct? The debug echo part there shows 100% correct output in the console as it runs:

code:
value1
value2
value!
valuea
valueb
valuec
But the output file is hosed up like:

code:
Length
14
20
30
etc..

So the output somehow is grabbing the length of each line rather than the content. Am I going about this in the completely wrong way?

12 rats tied together
Sep 7, 2006

Is it possible that powershell is assuming you want to add (since you're using += and powershell is weird about that) the length of $outputcsv to $splitline (0 + whatever), and then writing that to file?

There might also be an issue with you using import-csv instead of get-content. I don't really use import-csv a whole lot but I was under the impression that it creates objects from your CSV, so I could see that possibly being an issue as well. Is Length the first property in your csv?

CLAM DOWN
Feb 13, 2007




Reiz posted:

Is it possible that powershell is assuming you want to add (since you're using += and powershell is weird about that) the length of $outputcsv to $splitline (0 + whatever), and then writing that to file?

There might also be an issue with you using import-csv instead of get-content. I don't really use import-csv a whole lot but I was under the impression that it creates objects from your CSV, so I could see that possibly being an issue as well. Is Length the first property in your csv?

The imported CSV only has one property/column, the value as shown, there is no length property or intentional calculation of the length anywhere.

I'm using import/export-csv because it's just something I'm used to. It also has a really easy way of handling headers with -Header. I'd definitely want to switch to something better/newer like Get-Content but I'm not sure I have the time with this one.

Same with the +=, I was used to using stuff like this from other languages. I may have to try a different approach here.

Jethro
Jun 1, 2000

I was raised on the dairy, Bitch!
Maybe define $outputcsv before the loop (assuming you weren't already) just so powershell knows it's an array:
code:
$inputcsv = import-csv path\input.csv
$outputcsv = @()
foreach ($line in $inputcsv)
{
    $splitline = $line.'property'.Split(";")
    $splitline    #debug echo
    $outputcsv += $splitline
}
$outputcsv | export-csv -path path\output.csv
Or in one-line form:
code:
import-csv path\input.csv | %{$_.property -split ";" } | export-csv -path path\output.csv

Jethro fucked around with this message at 19:08 on Apr 25, 2014

12 rats tied together
Sep 7, 2006

quote:

The imported CSV only has one property/column, the value as shown, there is no length property or intentional calculation of the length anywhere.

That is very strange; I'd be really interested in where it's pulling the Length property from, then.

But, in this case (which I'm reading as: you have a text file and want to split it up on the semicolon), I would probably just use:

edit: You probably don't want the semicolons
code:
Get-Content .\test.csv -Delimiter ";" | % { $_.replace(";","") } | Out-File .\output.csv or
Get-Content .\test.csv -Delimiter ";" | % { $_.trim(";") } | Out-File .\output.csv
Right? Unless I'm misreading this, you don't really need to use import-csv or export-csv. For reference:

code:
property
value1;value2
value!
valuea;valueb;valuec

returns as:

property
value1
value2
value!
valuea
valueb
valuec

12 rats tied together fucked around with this message at 01:02 on Apr 26, 2014

ghostinmyshell
Sep 17, 2004



I am very particular about biscuits, I'll have you know.
What is the best way to capture all the output of a Powershell script running via task scheduler to a log file? I'm trying to troubleshoot some scripts that I have that are failing and finding the lovely method that I implemented is not capturing all the commands or variables.

MJP
Jun 17, 2007

Are you looking at me Senpai?

Grimey Drawer
So I have to do a big broad discovery for a consultant. I need to get some hardware stats - disk space, make/model, etc. - and it looks like I can use get-wmiobject to do so. (I'm open to other methods, so long as I can gather total disk space, used disk space, etc.)

I was able to use get-adcomputer to get a list of all computer objects in AD, and I've piped it to an array. But whenever I run the command below in Powershell with Active Directory module (logged on as a domain admin, launching Powershell as administrator):
code:
get-wmiobject win32_logicaldisk -computer $computers
I get a bunch of the following:
code:
Get-WmiObject : The RPC server is unavailable. (Exception from HRESULT: 0x800706BA) At line:1 char:14 + get-wmiobject <<<<win32_logicaldisk -computer $computers   
+ CategoryInfo          : InvalidOperation: (:) [Get-WmiObject], COMException   + FullyQualifiedErrorId : GetWMICOMException,Microsoft.PowerShell.Commands.GetWmiObjectCommand
If I try to use test-connection -computer $computers I get nothing but errors that a non-recoverable error has occurred during database lookup. I can ping any computer in $computers and get a response.

Our environment has Windows Firewall off for all connections via group policy, and we don't filter or firewall any internal traffic. I used Lansweeper Connectiontester to test connections, and it shows port 135 as open and WMI access tests OK to any computers I use.

I am running all this from one of our domain controllers.

Anyone know what else I should be trying?

Edit: I can rpcping other machines without issue from the domain controller I'm using for this.

MJP fucked around with this message at 14:25 on Apr 28, 2014

12 rats tied together
Sep 7, 2006

This might be a little silly but have you tried doing enable-psremoting on all of the target machines? There were a shitload of hoops we had to jump through to get all of our desktop machines remote-powershell friendly. You should also double check that the WinRM service is running on all the target machines (Test-WsMan). While you're jumping through all these hoops you might want to enable CredSSP authentication too, which allows your remote sessions to use your passed credentials to authenticate against a third machine (Say, you want to run an installer or write to a log file located on a server).

With get-wmiobject I usually get RPC errors when trying to grab from machines that aren't online, that obviously isn't the case for you at the moment. What happens when you try to Enter-PSSession? Get-WMIObject usually takes a long rear end time, have you tried it specifically against one computer that you know is online right now?

Also, for when you do actually get powershell remoting working, it might make your job a lot easier to know that you can Get-WmiObject -class win32_logicaldisk | select PSComputerName,DeviceID,Size,Freespace,VolumeName | export-csv .\diskspace.csv -append

To get a full list of all of the properties of a win32_logicaldisk wmi object, you can pipe it into Get-Member (shows all properties and methods) or Select * (shows all properties and their values).

Reiz posted:

That is very strange; I'd be really interested in where it's pulling the Length property from, then.
I believe the issue here was that export-csv was writing the objects' properties referenced in $outputcsv (an array of strings) to file. Strings, by default, only have one property which is length. So all you're likely to get is:
code:
#TYPE PS.type.of.object.or.whatever
Length,(other properties would go here),(and here)
6,
12,
18,
If you replace export-csv in your original script with out-file, it will probably work just fine. Haven't tested it myself though.

Jethro
Jun 1, 2000

I was raised on the dairy, Bitch!

MJP posted:

So I have to do a big broad discovery for a consultant. I need to get some hardware stats - disk space, make/model, etc. - and it looks like I can use get-wmiobject to do so. (I'm open to other methods, so long as I can gather total disk space, used disk space, etc.)

I was able to use get-adcomputer to get a list of all computer objects in AD, and I've piped it to an array. But whenever I run the command below in Powershell with Active Directory module (logged on as a domain admin, launching Powershell as administrator):
code:
get-wmiobject win32_logicaldisk -computer $computers
I get a bunch of the following:
code:
Get-WmiObject : The RPC server is unavailable. (Exception from HRESULT: 0x800706BA) At line:1 char:14 + get-wmiobject <<<<win32_logicaldisk -computer $computers   
+ CategoryInfo          : InvalidOperation: (:) [Get-WmiObject], COMException   + FullyQualifiedErrorId : GetWMICOMException,Microsoft.PowerShell.Commands.GetWmiObjectCommand
If I try to use test-connection -computer $computers I get nothing but errors that a non-recoverable error has occurred during database lookup. I can ping any computer in $computers and get a response.

Our environment has Windows Firewall off for all connections via group policy, and we don't filter or firewall any internal traffic. I used Lansweeper Connectiontester to test connections, and it shows port 135 as open and WMI access tests OK to any computers I use.

I am running all this from one of our domain controllers.

Anyone know what else I should be trying?

Edit: I can rpcping other machines without issue from the domain controller I'm using for this.
Are you sure $computers is an array of strings, as opposed to some sort of array of ad results or something like that?

Also, what happens when you manually run Get-WmiObject for one of the computers in question?

Fenrisulfr
Oct 14, 2012

ghostinmyshell posted:

What is the best way to capture all the output of a Powershell script running via task scheduler to a log file? I'm trying to troubleshoot some scripts that I have that are failing and finding the lovely method that I implemented is not capturing all the commands or variables.

Start-Transcript should work for you.

ghostinmyshell
Sep 17, 2004



I am very particular about biscuits, I'll have you know.

Fenrisulfr posted:

Start-Transcript should work for you.

This looks like it will work well, but now I can't use the Powershell ISE. Is there another popular IDE I can use with this command and powershell?

Otherwise, thanks, I will just notepad it up from now on, but this will do the trick for me.

CLAM DOWN
Feb 13, 2007





Just wanted to say thanks to you and others for the tips, I'm gonna give these a try today. I was so frustrated with this Friday that I shelved it for the weekend, but it's definitely something I want to fix by the end of this work week. Will post here if I manage to get it working how I want.

Virigoth
Apr 28, 2009

Corona rules everything around me
C.R.E.A.M. get the virus
In the ICU y'all......



ghostinmyshell posted:

This looks like it will work well, but now I can't use the Powershell ISE. Is there another popular IDE I can use with this command and powershell?

Otherwise, thanks, I will just notepad it up from now on, but this will do the trick for me.

You should be able to add something like this into your script:
code:
	#Stop any existing transcripts
		Stop-Transcript | Out-Null
	#Start transcript in the Temp directory, overwrite if existing?
		$filename = "C:\Windows\Temp\Foo.txt"
			if(test-path $filename)
				{
					Start-Transcript -path $filename -append
				}
				else
				{
					new-item $filename -type file
					Start-Transcript -path $filename -append
				}
At the top (it stops just in case something weird is happening)

and then close it at the bottom with Stop-Transcript

MJP
Jun 17, 2007

Are you looking at me Senpai?

Grimey Drawer

Jethro posted:

Are you sure $computers is an array of strings, as opposed to some sort of array of ad results or something like that?

Also, what happens when you manually run Get-WmiObject for one of the computers in question?

$computers is a list of computers. I took an export from get-adcomputer piped to CSV, removed all other columns and rows not in use, saved as CSV, and confirmed that there were no trailing spaces. So it should fit a list of string values.

If I run get-wmiobject against a remote computer manually, it runs just fine.

Jethro
Jun 1, 2000

I was raised on the dairy, Bitch!

MJP posted:

$computers is a list of computers. I took an export from get-adcomputer piped to CSV, removed all other columns and rows not in use, saved as CSV, and confirmed that there were no trailing spaces. So it should fit a list of string values.

If I run get-wmiobject against a remote computer manually, it runs just fine.

Get-Adcomputer returns a list of Microsoft.ActiveDirectory.Management.ADComputer objects, not a list of strings. So maybe something like
code:
$computers | %{get-wmiobject win32_logicaldisk -computer $_.name}

Djimi
Jan 23, 2004

I like digital data

Ithaqua posted:

For the record, parsing HTML with regexes is not recommended. Something like the HTML Agility Pack would make your life much easier.

Djimi posted:

I've outlined all the cases and the structure is guaranteed. I'd really rather not have to install anything.
So I did what I needed by hacking away at my (or PoSH's) inadequacies and to bring my question to a resolution here's what I did (basically):
code:
# some variable crud etc. above (not important)
$tmp= (gc env:temp)
$newcsv= $tmp + "csvlinks.csv"
$tempcsv=$tmp + "temp.csv"
$report="\\server\Shared\report.html"
$csv="\\server\Shared\Report_" + $yr +$us +$month+$us+$day+".csv"
(gc $csv | select -Skip 1) -replace '^([^,]+)(.+)','<a href="/////server/Shared/reports/logs/$1_info.log" target="_blank">$1</a>$2' | out-file $newcsv -append
(gc $newcsv) | Export-Csv $tempcsv -NoTypeInformation
# ..other html stuff redacted...
Import-Csv -Path $newcsv | ConvertTo-Html -Head $htmlformat -Body $body | Out-File $report
(gc $report | select -Skip 1) -replace "&lt;","`<" | set-content $report
(gc $report | select -Skip 1) -replace "&quot;", "`"" | set-content $report
(gc $report | select -Skip 1) -replace "&gt;","`>" | set-content $report
Thank y'all for your help, and pointing me in the right direction.

Djimi
Jan 23, 2004

I like digital data

MJP posted:

So I have to do a big broad discovery for a consultant. I need to get some hardware stats - disk space, make/model, etc. - and it looks like I can use get-wmiobject to do so. (I'm open to other methods...)

Anyone know what else I should be trying?
Well - I think you're in luck because I have written much of what you're being asked for, or suggesting. In fact my questions about creating html links from csv output has to do with said script.

Mainly I think you should make workstations report the information themselves instead attempting to run it off the DC or a member server. The method(s) below have been in place for over two years and it is pretty handy. When we were running all XP, my script was all batch because of the lack of PoSH on machines. Then I transitioned to PoSH and installed it on machines if it wasn't present (on XP) clients.

My method has been:
1) group policy on domain for a startup script for all computers (within a group, if you don't want servers etc.)
2) startup script copies a local ps1 script to each machine. And creates system task that
3) each machine runs the script once an hour.
4) each output of a machine status (log file) is copied to server directory as page of information for the workstation as well as a secondary file that is a single line of text as comma separated values. (I call this the tail log).
5) Once a day the server share runs a task to collate all the csv lines into one large appended csv.
6) Immediately after that a second script as a task takes that large csv and creates an html file with links by hostname to the individual logs of the workstations (more easily read as a text file in a browser, if you just want to check out a single host). This is really just a nice way to look up a computer and click to link to a page of information instead of scrolling horizontally on a large spreadsheet. Really not needed, but nice.

Specifically if you want to figure out diskspace stuff here's my code for that and a few more tasty bits as well: :tipshat:
code:
# Drive C
$disk = ([wmi]"\\.\root\cimv2:Win32_logicalDisk.DeviceID='c:'")
[int]$disksize= ($disk.Size/1GB)
[int]$diskfree= ($disk.FreeSpace/1GB)

$sys= gwmi win32_computersystem
$Comp= $sys.Caption
$log= $temp+"\"+$Comp+"_info.log"
$tail=$temp+"\"+$Comp+"_tail.log"
$prod= gwmi win32_ComputerSystemProduct
$UUID= $prod.UUID
$Vendor= $sys.Manufacturer
$Serial= $prod.IdentifyingNumber
$Model= $sys.Model
# if Mac remove those commas!
$Model=$Model.Replace(",", ".")
$os = gwmi win32_operatingsystem
$inDate = $os.ConvertToDateTime($os.installDate)
$Arch= $os.OSArchitecture
if (!$Arch) {$Arch="32-bit"}
$installDate= ([WMI]'').ConvertToDateTime((Get-WmiObject Win32_OperatingSystem).InstallDate)
$LastBoot= $os.ConvertToDateTime($os.LastBootupTime)
$osName= $os.Caption
$ServicePack= $os.CSDVersion
$User= $sys.UserName
$lpath=$temp + "\lastuser.tmp"
If(Test-Path -path $lpath) {$lastUser= (gc $temp\lastuser.tmp)}
$IP= ( ipconfig | Select-String -pattern 'Address' |  ?{$_ -notmatch 'fe'} | foreach { $_.ToString().split(":")[1] })
$ncard= gwmi win32_networkadapterconfiguration -Filter 'ipenabled = "true"'
$ind= $ncard.index
$ind=gwmi win32_networkadapter -Filter "index = $ind"
$Mac=$ind.MACAddress
$cpu= gwmi win32_processor
$procName=$cpu.Name
$procCount=$cpu.NumberOfLogicalProcessors
$procCores=$cpu.NumberOfCores
$speed=($cpu.MaxClockSpeed/1024)
$speed= "{0:N2}" -f $speed
gwmi Win32_PhysicalMemory | % {$TotalMem += [math]::Round($_.Capacity/1mb)}
$vidcard= (gwmi Win32_VideoController | Select Caption -Last 1 | ft -hide | out-file $temp\vid.tmp)
$vidcard= (gc $temp\vid.tmp | Where {$_ -ne ""})
$vidcard=$vidcard.TrimEnd()
$vidversion= gwmi Win32_VideoController
$vidcardversion=$vidversion.DriverVersion
I also have the time it takes the script to run on the machine. The average for all the different wmi lookups and creation of the log file is around 7 to 10 seconds. Not a very big hit.
The code for that is the beginning of the script:
code:
$start= (get-date -format T)
And at the end:
code:
$end= (get-date -format T)
And then I just print it out in the log file. I do this because originally I worried about how much of a resource hog it may be to run this script.
I just print out "execution time: " + $start + " to " + $end

Anyway, it may not be for your particular needs, but every machine joined to the domain starts reporting back and everyday at 4:30 p.m. I have a current, accurate spreadsheet and html file to refer to of every workstation or server. I also rotate (rename) the prior day's collated csv log (step 5). So I have a historical record as well. Next I would say I should inject everything in a MySQL server and serve that up.

New Yorp New Yorp
Jul 18, 2003

Only in Kenya.
Pillbug
How have I been doing so much PowerShell lately, but not known about out-gridview until yesterday?

:argh:

Dr. Arbitrary
Mar 15, 2006

Bleak Gremlin

Ithaqua posted:

How have I been doing so much PowerShell lately, but not known about out-gridview until yesterday?

:argh:

That's part of my PowerShell sales pitch to people who aren't sure it's worth learning. You already know all sorts of cool DOS commands, right? Now you can supplement them with the pipe, try "arp -a"
Now try "arp -a | out-gridview"

Mr. Clark2
Sep 17, 2003

Rocco sez: Oh man, what a bummer. Woof.

MJP posted:

So I have to do a big broad discovery for a consultant. I need to get some hardware stats - disk space, make/model, etc. - and it looks like I can use get-wmiobject to do so. (I'm open to other methods, so long as I can gather total disk space, used disk space, etc.)

I was able to use get-adcomputer to get a list of all computer objects in AD, and I've piped it to an array. But whenever I run the command below in Powershell with Active Directory module (logged on as a domain admin, launching Powershell as administrator):
code:
get-wmiobject win32_logicaldisk -computer $computers
I get a bunch of the following:
code:
Get-WmiObject : The RPC server is unavailable. (Exception from HRESULT: 0x800706BA) At line:1 char:14 + get-wmiobject <<<<win32_logicaldisk -computer $computers   
+ CategoryInfo          : InvalidOperation: (:) [Get-WmiObject], COMException   + FullyQualifiedErrorId : GetWMICOMException,Microsoft.PowerShell.Commands.GetWmiObjectCommand
If I try to use test-connection -computer $computers I get nothing but errors that a non-recoverable error has occurred during database lookup. I can ping any computer in $computers and get a response.

Our environment has Windows Firewall off for all connections via group policy, and we don't filter or firewall any internal traffic. I used Lansweeper Connectiontester to test connections, and it shows port 135 as open and WMI access tests OK to any computers I use.

I am running all this from one of our domain controllers.

Anyone know what else I should be trying?

Edit: I can rpcping other machines without issue from the domain controller I'm using for this.

Is there some reason you cant just use PDQ Inventory? It does what you're asking for and it's free. http://www.adminarsenal.com/pdq-inventory I use it every day at work and find it to be invaluable

CLAM DOWN
Feb 13, 2007




What's the best way to get started on DSC? I consider myself pretty experienced and skilled with Powershell, but the majority of my scripting has been on 2.0, only very recently in 3.0. I'd really like to learn DSC and start using it as the Linux management in v5 is an incredibly attractive option for us.

The Electronaut
May 10, 2009

Dr. Arbitrary posted:

That's part of my PowerShell sales pitch to people who aren't sure it's worth learning. You already know all sorts of cool DOS commands, right? Now you can supplement them with the pipe, try "arp -a"
Now try "arp -a | out-gridview"

:aaa:

I tried this yesterday and gasped. It was like the aliens from Toy Story when the claw comes out. I IMed it another guy I work with and he did same thing. Amazing.

New Yorp New Yorp
Jul 18, 2003

Only in Kenya.
Pillbug

CLAM DOWN posted:

What's the best way to get started on DSC? I consider myself pretty experienced and skilled with Powershell, but the majority of my scripting has been on 2.0, only very recently in 3.0. I'd really like to learn DSC and start using it as the Linux management in v5 is an incredibly attractive option for us.

I've been doing a lot of messing around with DSC lately. It's not very well documented, and it feels like it's very limited out-of-the-box. Most of the stuff you'd actually want to use it for is being accomplished via unsupported community extensions. IMHO it's not mature enough for prime-time yet. Soon, but not yet.

Dr. Arbitrary
Mar 15, 2006

Bleak Gremlin

The Electronaut posted:

:aaa:

I tried this yesterday and gasped. It was like the aliens from Toy Story when the claw comes out. I IMed it another guy I work with and he did same thing. Amazing.

Thank you for letting me know. I'm on my second year in IT and if you look through my post history it's a lot of "how do I do x?" and "why does z?"

I'm glad that I get to give back a little bit.

12 rats tied together
Sep 7, 2006

I've got a script currently that tests the websites/apps my employer hosts. One of the tests involves detecting a popup and I'm struggling to come up with a way to detect it.

I've played around a little with opening the popup and then using Shell.Application and assigning a dummy variable to basically Shell.Application.Windows() | ? { $_.LocationURL -eq "whatever" }, but I can't get it to 'stick'. While messing around with the windows() method I noticed that it wasn't pulling any of the IE processes I had running at all, despite multiples of them running.

It's a fairly simple check, I just need to see if the LocationURL or body contains a string which will give me a pass/fail. I don't even really need to control the popup directly - as long as I can detect that it exists and check properties of it I can probably work something out. I'm really clueless as to why windows() was barely detecting anything, though. Any thoughts? Is there a better way to do this?

Loten
Dec 8, 2005



Wow thanks for this. I think this is my new favourite thing.

12 rats tied together
Sep 7, 2006

Reiz posted:

It's a fairly simple check, I just need to see if the LocationURL or body contains a string which will give me a pass/fail. I don't even really need to control the popup directly - as long as I can detect that it exists and check properties of it I can probably work something out. I'm really clueless as to why windows() was barely detecting anything, though. Any thoughts? Is there a better way to do this?

I believe the issue here is something to do with namespaces or resource providers or some other windows thing. I'm running powershell as an admin on an account that isn't an admin and the IE processes are being created under admin but displayed on user and it seems like they hook into a process running as system. From what I understand windows() either isn't looking or can't look in the right place to detect any IE windows I don't open manually.

New question: what's the deal with capturing named groups with regex in powershell? Normally I test my regexes in sublime text and they work out fine, but this time I feel like the interpreter is doing something funny. I'm pulling XML from share point and looking for everything between a tag using basically (?<=URL=") (.*?) (?=\"). In sublime text it matches fine, in powershell it matches absolutely nothing.

I've confirmed I'm matching against a string, I've even matched XML from share point before (although with a simpler regex). I can give examples later when I'm not phone posting.

New Yorp New Yorp
Jul 18, 2003

Only in Kenya.
Pillbug
DSC is pissing me off right now.

First off:
How do I push custom modules to remote boxes? I'm trying to use the PowerShell DSC Resource Kit, and I don't want to install it on the servers manually. That's dumb.

Second:
The PowerShell DSC Resource Kit is a big piece of poo poo as far as I can tell. Nothing works exactly as advertised.

Trying to create a website? Nope, that's going to fail because the site doesn't exist.

Trying to deploy a service? Nope! As far as I can tell, you can't do the world's most basic "service installation" workflow:
Stop service if it exists.
Copy binaries.
Create service if it doesn't exist.
Start it.

WhoNeedsAName
Nov 30, 2013

Dr. Arbitrary posted:

Thank you for letting me know. I'm on my second year in IT and if you look through my post history it's a lot of "how do I do x?" and "why does z?"

I'm glad that I get to give back a little bit.

I had a very similar Toy Story moment too when I saw it. It makes dealing with Exchange logs so much easier. Thanks

fromoutofnowhere
Mar 19, 2004

Enjoy it while you can.
Ok, so I'm trying to pull AD info, sort and parse by username, profilepath, and home directory. I then want to dump users with correct profilepath/home directory in one file, and dump the incorrect profilepath/homedirectory users into another file. Parse incorrect file with users with no profilepath and home directory vs those that do. Show users with incorrect profile path and home directory.

Then I want to have a script for changing and setting the new users profile data.

As I'm still just starting with this, I'm having issues understanding why certain commands work while others keep giving me errors.
code:

PS N:\> Get-ADUser -filter * -Properties profilepath, homedirectory | ft Name, profilepath, homedirectory > c:\temp\users1.txt
PS N:\> Get-ADUser –filter * -Properties profilepath, homedirectory | export-clixml c:\temp\users1.xml
PS N:\> import-clixml c:\temp\users1.xml | ConvertTo-Html | Set-Content c:\temp\users1test.html
PS N:\> Get-ADUser –filter { profilepath -like "\\ProfileServerName\*" } | ft name, profilepath, homedirectory > c:\temp\user4.txt

The last line of script only provides the usernames for some reason. I'm not sure what I'm doing wrong, adding -Properties kills the script. Any assistance would be fantastic. I'm currently at a wall trying to get powershell to pull and split the data. Importing the file is fine, it's just trying to export it with a -like that's kicking my rear end. Oh, the other lines are there as a brain dump, I'm still playing around with information types like .csv and .xml. I'm still trying to figure out which type would be better for the task I'm trying to accomplish.

Adbot
ADBOT LOVES YOU

The Electronaut
May 10, 2009

fromoutofnowhere posted:

Ok, so I'm trying to pull AD info, sort and parse by username, profilepath, and home directory. I then want to dump users with correct profilepath/home directory in one file, and dump the incorrect profilepath/homedirectory users into another file. Parse incorrect file with users with no profilepath and home directory vs those that do. Show users with incorrect profile path and home directory.

Then I want to have a script for changing and setting the new users profile data.

As I'm still just starting with this, I'm having issues understanding why certain commands work while others keep giving me errors.
code:

PS N:\> Get-ADUser -filter * -Properties profilepath, homedirectory | ft Name, profilepath, homedirectory > c:\temp\users1.txt
PS N:\> Get-ADUser –filter * -Properties profilepath, homedirectory | export-clixml c:\temp\users1.xml
PS N:\> import-clixml c:\temp\users1.xml | ConvertTo-Html | Set-Content c:\temp\users1test.html
PS N:\> Get-ADUser –filter { profilepath -like "\\ProfileServerName\*" } | ft name, profilepath, homedirectory > c:\temp\user4.txt

The last line of script only provides the usernames for some reason. I'm not sure what I'm doing wrong, adding -Properties kills the script. Any assistance would be fantastic. I'm currently at a wall trying to get powershell to pull and split the data. Importing the file is fine, it's just trying to export it with a -like that's kicking my rear end. Oh, the other lines are there as a brain dump, I'm still playing around with information types like .csv and .xml. I'm still trying to figure out which type would be better for the task I'm trying to accomplish.

The format- commands are for rendering the data, use select to get those two properties.

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