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
The Diddler
Jun 22, 2006


I've just started trying to get into Powershell. I do a fair amount of scripting, with both VBScript and batch files. My problem is that I don't really have a problem right now that I need a new script for. Is there any benefit to replacing my current vbs and bat files with powershell scripts? Or is there anything flat-out awesome that it does, maybe a solution that I could find a problem for?

I can make it beep, but that isn't really useful. :sigh:

Adbot
ADBOT LOVES YOU

The Diddler
Jun 22, 2006


adaz posted:

I guess next time you need a script written pop in here with the problem and we'll go through it. Or if you want to rewrite one of your current ones can help yo out with that.

It's funny you should mention that...I spent most of the day poking around at a script that I already have a version of, but this new one would be way nicer. Right now, it's a vbs that reads the username, sn, and lastlogin time from AD and writes it to an excel file. Then I run a macro to delete every row with a lastlogin time that's less than 30 days from today, so I'm left with a list of accounts that haven't logged into the domain in the last month.

I have the export part working, and I have the macro working, but I can't get the export to open and write in the file with the macro. It doesn't need to be so convoluted, but this is tons simpler than the first version.

The Diddler
Jun 22, 2006


adaz posted:

The full script, coming in at a cool 22 lines :black101:

This was just what I needed, and with a few tweaks I can use it for a couple of other things, thanks!

The Diddler
Jun 22, 2006


adaz posted:

You only wanted a few properties returned, so let's set those. The [void] is a type accelerator that casts the return to, well, null. If you remove it you'll see the $Searcher object returns a number indicating how many items it's searching for everytime you add something. Doesn't hurt anything, but annoying if you leave it.

code:
[void]$searcher.PropertiesToLoad.Add("sn")
[void]$searcher.propertiesToLoad.Add("cn")
[void]$searcher.PropertiesToLoad.Add("lastlogontimestamp")
Now we'll create a custom object with the properties we care about.

code:
$CSVObj = "" | select SN,CN,LastLogonTimestamp
Add those properties to the object, we'll use the [string] accelerator to force the values to string instead of the propertyResultCollection type which won't convert nice.

code:
$csvObj.sn = [string]$users[$i].properties.sn
$csvObj.cn = [string]$users[$i].properties.cn

I ran into some issues with this today. I tried to add some additional properties to look for, but they don't print. I added them to the 3 spots I quoted, and instead of displaying like the rest, they create a column where I tell it and then leaves it empty. For example, if I wanted to add SamAccountName I would do this:

code:
[void]$searcher.PropertiesToLoad.Add("SamAccountName")
code:
$CSVObj = "" | select SN,CN,LastLogonTimestamp,SamAccountName
code:
$csvObj.SamAccountName = [string]$users[$i].properties.SamAccountName
Did I miss something? I assume that the LDAP properties remain the same with Powershell, but I couldn't find anything that specifically said that, they just implied it. I tried it with a handful of other properties to see if I could track down my error, and they all did the same thing.

The Diddler
Jun 22, 2006


adaz posted:

What you ran into was something really stupid and annoying with the language: Case Doesn't Matter Except When It Does.

Hey, it worked! That seems pretty stupid, though. Is there an online resource for that sort of thing? I've tried Technet's scripting center, but it's nearly impossible for me to find what I'm looking for there.

The Diddler
Jun 22, 2006


I've been messing around with Powershell for a week or so, and I've found another question. Is there something you can do at the command prompt that you can't do with Powershell? I do a pretty fair amount of my daily work in a command window, and I've tried a half-dozen or so commands that worked in Powershell. It would be nice to not have to keep switching shells to do different things. I tried to google this, but the only real result was about how awesome Powershell is for scripting.

The Diddler
Jun 22, 2006


What's going on with my script? I have a directory with about 200 files. There's 8 different extensions, making it: file.ex1, file.ex2, file.ex3, file2.ex1, file2.ex2, file2.ex3... I only care about 4 of the extensions, and I need all 4 of them. My thought is to count the number of files with the extensions I care about and put the numbers in an excel document. That part works:
code:
$fim00 = Get-ChildItem "c:\folder\*.fim"
$sheet00.Cells.Item(2,2) = $fim00.Count
$rim00 = Get-ChildItem "c:\folder\*.rim"
$sheet00.Cells.Item(2,3) = $rim00.Count
$idx00 = Get-ChildItem "c:\folder\*.idx"
$sheet00.Cells.Item(2,4) = $idx00.Count
$dir00 = Get-ChildItem "c:\folder\*.dir"
$sheet00.Cells.Item(2,5) = $dir00.Count

$WorkBook00 = $sheet00.UsedRange
$WorkBook00.Interior.ColorIndex = 8
$WorkBook00.Font.ColorIndex = 11
$WorkBook00.Font.Bold = $True
If I'm missing a file, I need to create it. I can do that by hand, since I just need to copy an existing file and rename it. To make that part easier, if my numbers don't match, I want a list of each one. That part also works, except my if statement doesn't work. I tried all 3 I have here, and they always return the result I have commented at the end of the line.

code:
if ($fim00 = $rim00 = $idx00 = $dir00) {"00 correct"} else { #always true

if (($Sheet00.Cells.Item(2,2))-eq($Sheet00.Cells.Item(2,3))-eq($Sheet00.Cells.Item(2,4))-eq($Sheet00.Cells.Item(2,5))) {"00 correct"} else { #always false

if (($fim00.Count) = ($rim00.Count) = ($idx00.Count) = ($dir00.Count)) {"00 correct"} else { #errors out
What's going on here? I spent most of today banging away at this, and everything else pretty much works right, just not this. I could have it list everything every time, but it's over the network and kind slow since it happens ~20 times by the time it's finished.

On a slightly related note, how do I create an excel document with 5 worksheets? This thing is done to 5 different directories, and my script starts making GBS threads all over when I need sheet 4.

The Diddler
Jun 22, 2006


dalin posted:

The equality operator is "-eq", not "=". Also I don't think you can string them together like that (x -eq y -eq z). Try this:

code:
$counts = @($fim00.Count,$rim00.Count,$idx00.Count,$dir00.Count)
$allEqual = ($counts | ? { $_ -ne $fim00.Count } | Measure-Object).Count -eq 0
if ($allEqual) { ... }
Can't help you with the Excel bit.

Hey, that worked, thanks! If anyone else is curious about adding worksheets to excel, I found this today:
code:
 
$Excel = New-Object -Com Excel.Application
$Excel.visible = $True
$Excel = $Excel.Workbooks.Add()

$ws = $Excel.Worksheets.Item(1) 
for ($i = 0; $i -le 1; $i++) {
$ws = $Excel.Sheets.Add() }
With this snippet you can add as many pages as you need. Since the loop is "less than or equal to" it adds 2 in this instance, giving you 5 sheets. I'm guessing it wouldn't be too much work to create a workbook with 4 sheets. Since the sheets seem to be added sorta haphazardly, you probably want to rename them using $Excel.Worksheets.item(2).name = "whatever", where (2) is the sheet number you want to rename.

Another question: any resources on how to format the output of select-string? I have a 2-liner that produces pretty decent output if I paste it into my session, but if I run the .ps1, the output changes.

The Diddler
Jun 22, 2006


adaz posted:

Can you give us the example? I mean, select-string outputs whatever it finds as a string, not sure what you want to do with it.

I'll have to look when I get to work. I just tried it at home and it worked like I wanted it to.

The Diddler
Jun 22, 2006


adaz posted:

Powershell v1 versus v2 maybe? Also keep in mind that if powershell is returning some really stupid formatting or type for whatever reason the [string] type accelerator can be golden. Works fantastic for a lot of things, especially ADSI type searches that output fine until you try to work with them.

Still, select-string should always return a string as far as I'm aware.

I'm running Win7 on both machines. That comes with v2 out of the box, right?

The differences were something like:
code:
c:\file.txt:2:nacho
c:\file2.txt:2:nacho
c:\file3.txt:2:nacho
c:\file4.txt:2:nacho
and
code:
***********
c:\file.txt
2
true
match
nacho
***********
c:\file2.txt
2
true
match
nacho
***********
The first one is what I want, and the second one is the one that just shows up.

The Diddler
Jun 22, 2006


adaz posted:

What is the full code though that's generating all this? I'm not sure.. what are you piping to select string (or inputting)?

This is the script:
code:
Get-ChildItem C:\users\user\desktop\pim
grep -pattern "EXCEPTIONS" -path "C:\users\user\desktop\pim\*.*"
Grep is defined in my profile as an alias for select-string. I tried it using select-string instead of grep, and it did the same thing. When I paste it into powershell, it does this:
code:
   Directory: C:\users\user\desktop\pim


Mode                LastWriteTime     Length Name
----                -------------     ------ ----
-a---         6/16/2010   5:45 PM        645 I00F1.DOC
-a---         6/16/2010   5:45 PM        645 I00F2.DOC
-a---         6/16/2010   5:45 PM        645 I00F3.DOC

C:\users\user\desktop\pim\I00F1.DOC:7:*** NO EXCEPTIONS TO REPORT ***
C:\users\user\desktop\pim\I00F2.DOC:7:*** NO EXCEPTIONS TO REPORT ***
C:\users\user\desktop\pim\I00F3.DOC:7:*** NO EXCEPTIONS TO REPORT ***
When it's run as a ps1, it does this:
code:
   Directory: C:\users\user\desktop\pim


Mode                LastWriteTime     Length Name
----                -------------     ------ ----
-a---         6/16/2010   5:45 PM        645 I00F1.DOC
-a---         6/16/2010   5:45 PM        645 I00F2.DOC
-a---         6/16/2010   5:45 PM        645 I00F3.DOC
-a---         6/16/2010   5:45 PM        645 I00F4.DOC
-a---         6/16/2010   5:45 PM        645 I00F5.DOC
-a---         6/16/2010   5:45 PM        645 I00F6.DOC
-a---         6/16/2010   5:45 PM        645 I00F7.DOC
-a---         6/16/2010   5:45 PM        645 I00F8.DOC
-a---         6/16/2010   5:45 PM        645 I00F9.DOC
-a---         6/16/2010   5:45 PM        645 I04F10.DOC
-a---         6/18/2010   7:12 PM        637 I06F11.DOC

IgnoreCase : True
LineNumber : 7
Line       : *** NO EXCEPTIONS TO REPORT ***
Filename   : I00F1.DOC
Path      : C:\users\user\desktop\pim\I00F1.DOC
Pattern    : EXCEPTIONS
Context    :
Matches    : {EXCEPTIONS}


IgnoreCase : True
LineNumber : 7
Line       : *** NO EXCEPTIONS TO REPORT ***
Filename   : I00F2.DOC
Path      : C:\users\user\desktop\pim\I00F2.DOC
Pattern    : EXCEPTIONS
Context    :
Matches    : {EXCEPTIONS}


IgnoreCase : True
LineNumber : 7
Line       : *** NO EXCEPTIONS TO REPORT ***
Filename   : I00F3.DOC
Path      : C:\users\user\desktop\pim\I00F3.DOC
Pattern    : EXCEPTIONS
Context    :
Matches    : {EXCEPTIONS}
This is generally going to be run against a directory of 7 to 30 files, which is going to make it really hard to read. Any ideas?

The Diddler
Jun 22, 2006


adaz posted:

That is really bizarre and I don't know why it is doing that to you. I tried quite a few things to get your original code to work executed as a ps1 but nothing would, sorry. I did, however, find a way around that output problem and it that works just fine.


code:
$dir = Get-Childitem C:\users\user\desktop\pim
$dir  
$dir | select-string "EXCEPTIONS"

I'll give that a shot tomorrow. Some other things I came up with today were creating a batch file with the powershell commands in it or some crazy thing that I found on Technet that will sort and filter the results. I don't really understand it, so I was having issues making it work.

Adbot
ADBOT LOVES YOU

The Diddler
Jun 22, 2006


Bob Cthulhu posted:

I'll give that a shot tomorrow. Some other things I came up with today were creating a batch file with the powershell commands in it or some crazy thing that I found on Technet that will sort and filter the results. I don't really understand it, so I was having issues making it work.

I got it working today. Did a Get-Childitem with a format-table and the second line was a select-string, I believe a sort to get what I needed, and a format-table. I found something interesting today: if you use a format-table in your script, you have to format-table every line that has output. You can't mix implied and explicit formatting.

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