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
Phone
Jul 30, 2005

親子丼をほしい。
I'm trying to either run a Get-Process or start a PS Session on a remote computer/server at work and everything I throw at it has it's own special error related to which method I try:

Enter-PSSession -ComputerName ComputerName = hangs for a bit then spits out that it can't resolve
Enter-PSSession -ComputerName ComputerName.domain.com = instantly spits out that it can't resolve
Enter-PSSession -ComputerName IP = NOPE, your authentication won't allow it
Enter-PSSession -ComputerName IP -Credential domain\my.user = NOPE, your authentication won't allow it

All of these are Win7 boxes with names and IPs associated with them, but PS won't resolve to the hostname and bitches at me when trying to do it via IP.

Halp. :<

Adbot
ADBOT LOVES YOU

adaz
Mar 7, 2009

If you just do a blame nslookup do the computer names resolve? Are the computers not joined to the same domain/forest?

evil_bunnY
Apr 2, 2003

This is awesome: you map a share from a normal shell: can't use your admin token. You map it from an elevated shell: can't loving resolve. What the gently caress do you want from me.
e: works after restarting the shell. Urgh.

Also, any program that can create 260+ chars paths needs to die in a fire. HAHA you can look at it, but you can't touch it!

Long story short, I'm now writing a script that recursively renames to shortest possible name + takes ownership (in which order? both!) and deletes anything still alive. gently caress you, NTFS.

evil_bunnY fucked around with this message at 10:35 on Oct 11, 2011

Phone
Jul 30, 2005

親子丼をほしい。

adaz posted:

If you just do a blame nslookup do the computer names resolve? Are the computers not joined to the same domain/forest?

The computers are all on the same domain/in the same OU in AD.

adaz
Mar 7, 2009

evil_bunnY posted:

This is awesome: you map a share from a normal shell: can't use your admin token. You map it from an elevated shell: can't loving resolve. What the gently caress do you want from me.
e: works after restarting the shell. Urgh.

Also, any program that can create 260+ chars paths needs to die in a fire. HAHA you can look at it, but you can't touch it!

Reason number #1599215151 to never have UAC turned on.

And yeah it's 2011 and long files names still loving suck in windows. The problem you can have is that you can have a computer with Z:\blah\hi i'm a super loving long file name weeeeeee don't ever try to use me.docx and have it work fine.. until you try to script and touch it and find its actual path is \\blah.local\server\share\admin share\obscure folder\blah\hi i'm a super loving long file name weeeeeee don't ever try to use me.docx


phone posted:

The computers are all on the same domain/in the same OU in AD

Can you resolve them with nslookup? What exact authentication error are you getting? I've only ever seen the authentication errors/token errors if the shell isn't running as an admin (assuming domain authentication is correct & you are in the local admin groups on the remote machine)

Serfer
Mar 10, 2003

The piss tape is real



evil_bunnY posted:

Also, any program that can create 260+ chars paths needs to die in a fire. HAHA you can look at it, but you can't touch it!
Can you use \\?\c:\ (or whatever drive) to access it? Anything that can use UNC paths should be able to access it that way.

See also subst.

Phone
Jul 30, 2005

親子丼をほしい。

adaz posted:

Can you resolve them with nslookup? What exact authentication error are you getting? I've only ever seen the authentication errors/token errors if the shell isn't running as an admin (assuming domain authentication is correct & you are in the local admin groups on the remote machine)

Logged in today at work and got it to work as soon as I ran WinRM on the target computer. I'm going to chalk it up to 1 part "our DNS loving sucks" and 2 parts of "hot drat does our RDSFARM eat a bag of dicks." I saw the Technet blog about and it is simple, but WinRM seems to be a gaping security hole if I'm interpreting the quickconfig correctly: "allows listening on [url]http://*[/url]". :tinfoil:

I'll be back in this thread soon enough, I'm trying modify a goon-made script to report back OS caption and version (yay computers that still don't have W7 SP1).

Thanks guys.

evil_bunnY
Apr 2, 2003

Serfer posted:

See also subst.
it's what I ended up using. It's such a crappy system though.

johnnyonetime
Apr 2, 2010
I have an OU of users that I would like to set the passwords to never expire using Powershell. There are a LOT of google results on how to do this but I have had zero luck getting the script to achieve this. Can a powershell guru take a look and tell me what's wrong with this?

code:
$Never_Expire=0x10000
 
$objou = New-Object System.DirectoryServices.DirectoryEntry("LDAP://ou=MyUsers,dc=example,dc=com")
$objSearcher = New-Object System.DirectoryServices.directorySearcher
$objsearcher.searchroot = $objou
$objsearcher.filter = '(&(objectCategory=User)(Objectclass=user)(!isCriticalSystemObject=*))'
$objsearcher.searchscope = "subtree"
 
$results = $objsearcher.findall()
 
foreach ($result in $results) {
  $user = [adsi]$result.path
  $value = $user.useraccountcontrol.item(0)
  $value = $value -bor $Never_Expire
  $user.useraccountcontrol = $value
  $user.name
  $user.setinfo()
}
Bonus Question! I'm a new powershell user and can already tell it is awesome. What is the easiest way to have a nice little repository of scripts I can pull up in Powershell for day-to-day activities?

adaz
Mar 7, 2009

Johnny,

There's nothing wrong with that code it works perfectly. What errors are you getting?

As far as a repository of scripts you have a couple of options. What I like to do is in my powershell profile dot source a directory or file with a bunch of common functions I use. So, by default, the powershell profile is in \my documents\WindowsPowersHell\Microsoft.PowerShell_profile.ps1

In that file if I want to load up a specific powershell script I do this. The functions in the script will then be available all throughout the shell and to any other scripts you write.

code:
# Load Common Functions
. .\CommonFunctions.ps1

Honey Im Homme
Sep 3, 2009

If I were to use a powershell login script from gpo, the modules I used need to be installed on each machine the script runs on correct? If I install them under my own account will this also install them for other accounts?

adaz
Mar 7, 2009

Honey Im Homme posted:

If I were to use a powershell login script from gpo, the modules I used need to be installed on each machine the script runs on correct? If I install them under my own account will this also install them for other accounts?

Not necessarily, you could have the first line of the script be

code:
import-Module -path "\\some\server\path\module.ps1"
You could also modify the psmodulepath environment variable to point to a specified share where you are storing your modules and run Import-Module Name

Honey Im Homme
Sep 3, 2009

adaz posted:

Not necessarily, you could have the first line of the script be

code:
import-Module -path "\\some\server\path\module.ps1"
You could also modify the psmodulepath environment variable to point to a specified share where you are storing your modules and run Import-Module Name

Did the trick, cheers!

Drumstick
Jun 20, 2006
Lord of cacti
Is it possible to check folder permissions and then print the folder names if the permissions includes a specific user/group using powershell?

Jelmylicious
Dec 6, 2007
Buy Dr. Quack's miracle juice! Now with patented H-twenty!

Drumstick posted:

Is it possible to check folder permissions and then print the folder names if the permissions includes a specific user/group using powershell?

Yes, though it was actually more complicated then I thought. I may have overcomplicated a bit, so if anyone has a more elegant solution, I would love to see it.

Here is the code:
code:
$Identity = "Jelmylicious"
$Path = "c:\users" 

$ACLlist = get-childitem $Path | ? {$_.PSisContainer} | get-acl 
foreach ($ACL in $ACLlist)
    {
    foreach ($access in $ACL.access) 
        {
        if ($access.identityreference -match $identity) 
            {
            Write-host $Identity has the right $access.AccessControlType $access.FileSystemRights to $ACL.path.substring(38)
            }
        }
    }    

Now, lets break this down. First we set who we want to search for and where, in $Identity and $Path. These are strings, so we put them in quotes:
code:
$Identity = "name"
$Path = "c:\users"
Next we do a get-childitem, to get all objects in the given path (add a -recurse if you want to get all subfolders too)
code:
get-childitem $Path 
Then we filter for folders (? is an alias for where)
code:
| ? {$_.PSisContainer}
and get all access control lists
code:
| get-acl 
Next step is to identify each access indentityreference in each ACL, hence the double foreach:
code:
foreach ($ACL in $ACLlist)
    {
    foreach ($access in $item.access) 
And we check the identityreference:
code:
if ($access.identityreference -match $identity) 
Now we finally filtered everything, we can output. But, just stating the folders isn't enough. Are the permissions set to allow, or deny? Is it full control or read only?
[code
Write-host $Identity has the right $access.AccessControlType $access.FileSystemRights to $ACL.path.substring(38)
[/code]
The substring part is to cut off the first 38 characters, because $ACL.path would just output Microsoft.PowerShell.Core\FileSystem:: before the string.
Controltype tells us Allow or Deny, Filesystemrights the actual rights being allowed or denied. Or, if you want to see if the rights are inherited from a parent folder, add $access.isinherited to the output.
You could clean this up, because some of the FileSystemRights are in the form of an integer, such as 268435456, which means full control on all FILES under the specified root directory, according to Here. You could rewrite the integers to human readable strings, if you knew which is which.

Output will look like this:

Jelmylicious has the right Allow 268435456 to C:\users\Jelmylicious
Jelmylicious has the right Allow FullControl to C:\users\Jelmylicious

Jelmylicious fucked around with this message at 10:04 on Oct 28, 2011

Scaramouche
Mar 26, 2001

SPACE FACE! SPACE FACE!

I feel like a big hypocrite because I always resolve to read this thread and learn everything in it, and then I never do, and now I have a quick and dirty problem that I would probably know how to solve had I just read the whole drat thread originally.

I've got a list of about 26,000 file names from a file system, and I've got a database dump of about 29,000 file names. I need to see which file names from the file system aren't present in the database dump (obviously there's about 3,000) so I can see which database rows are missing images. First try was to just paste them both into LibreOffice Calc and then do a CountIf(range) operation, but LibreOffice doesn't apparently like thousands of rows, because it's been 'not responding' for about 30 minutes now. I don't have office on this machine unfortunately.

Is there a way I can use PS to do this elegantly? I could do it in MSDOS batch (but don't want to) by just putting 29,000 of these into a batch file:
code:
dir file1.jpg
dir file2.jpg
dir file3.jpg
...
dir file 29701.jpg
And then piping the results of that to file. But this seems inelegant and wasteful to me.

Is there a better powershell way? I'm just pulling this out of my rear end but something like:
FindMissing (29000Files.txt) (Directory with 26000 files path)

would be great.

EDIT-
It looks like Test-Path might have the functionality, but I can't figure out how to pass it a list of files as the criteria, and I can't figure out how to make it spit out the missing file if it returns FALSE.

EDIT2-
Hmm you'd think this would work but it doesn't:
code:
Get-Content FileList.txt | ForEach-Object(test-path $_)
EDIT3-
Adoy. It was because FileList.txt was unicode; saved it as DOS and ended up doing this:
code:
$FileList = Get-Content FileList.txt
foreach ($FileName in $FileList) { if (!(test-path $FileName)) {Out-File FailLog.txt -append -inputobject $FileName} }
It took me longer to figure out how the negation(!) worked than anything else.

Scaramouche fucked around with this message at 04:32 on Nov 3, 2011

adaz
Mar 7, 2009

There are numerous ways of doing what you want, and it seems like you have figured it out. The other way to do the negation is to run it in a sub-expression:

code:
foreach($path in $paths) {
  if($(test-path $path) -eq $false) {
     # do things
  }
}

Scaramouche
Mar 26, 2001

SPACE FACE! SPACE FACE!

Got some more goodies for you PS gurus. I'm trying to de-dupe that enormous file list mentioned previous (29,000 image files). I'm using this guy's script to find them:
http://blog.codeassassin.com/2007/10/13/find-duplicate-files-with-powershell/

Seems pretty good (goes by size and then md5), and the counts are really handy. Some of the files are duplicated over 1000 times. The problem I'm having though, is it's good to know the counts, but what I really need are all the duplicated file names themselves. Unfortunately the output of the script looks like this:
code:
Count   Name                  Groups
95	137 255 159 230 40 53 {127769_5.jpg, 127770_4.jpg...}
Where the ... is where the file list gets truncated. I >think< this could be controlled with Format-Table, but I'm not sure how I could get it to work, since in some cases (over 1000 file names) I'm probably going to run up against some kind of internal limit in powershell.

My other option is tweaking the script itself, since I don't actually need file counts and the 'name' column, all I would need is something like this:
code:
ID   FileName
1    127769_5.jpg
1    127770_4.jpg
1    127771_3.jpg
2    131110_1.jpg
2    131111_2.jpg
2    131112_3.jpg
etc.
Where the 'ID' just denotes that 'yes all of these files are the same'. The second option is actually more useful to me, because then I could relatively quickly turn this list into SQL, instead of having to harvest out several comma-delimited lists like the Format-Report solution does. My tweaking has not found success thus far though, resulting only in errors, returning no files, or returning that all files are identical. My questions are thus:
1. Do you guys think that I should be concentrating on Format-Report or just tweaking the script to get my desired output? Can Format-Report columns even go that large?
2. Anyone have any advice on how to get the desired output in the second example from the script linked above?

Thanks in advance for any help.

IT Guy
Jan 12, 2010

You people drink like you don't want to live!
Is the OP (April 2010) still the best source for resources?

I have zero .NET programming knowledge and my batch jobs consist of Google results. I'm interested in just full blown learning PowerShell to make my life easier and want to pick up one or two books on the subject. Where is my best start to learn PS?

Walked
Apr 14, 2003

IT Guy posted:

Is the OP (April 2010) still the best source for resources?

I have zero .NET programming knowledge and my batch jobs consist of Google results. I'm interested in just full blown learning PowerShell to make my life easier and want to pick up one or two books on the subject. Where is my best start to learn PS?

Depends on your level of understanding of .NET (you said none), powershell(none), and scripting/programming in general.

Between MSDN + Oreilly's Powershell Cookbook and you've got a TON of material at your disposal, but its also not like it's a 1-2-3 "intro to this stuff" avenue.

Oreilly generally has really good stuff though, I think they have a more introductory powershell book out too.

IT Guy
Jan 12, 2010

You people drink like you don't want to live!

Walked posted:

Depends on your level of understanding of .NET (you said none), powershell(none), and scripting/programming in general.

Between MSDN + Oreilly's Powershell Cookbook and you've got a TON of material at your disposal, but its also not like it's a 1-2-3 "intro to this stuff" avenue.

Oreilly generally has really good stuff though, I think they have a more introductory powershell book out too.

That's what I figured. My "programming" skills stop at PHP (for what that's worth). I barely know the MVC model, and don't know anything about OOP other than what the acronym initialism stands for.

IT Guy fucked around with this message at 20:33 on Nov 8, 2011

adaz
Mar 7, 2009

IT Guy posted:

Is the OP (April 2010) still the best source for resources?

I have zero .NET programming knowledge and my batch jobs consist of Google results. I'm interested in just full blown learning PowerShell to make my life easier and want to pick up one or two books on the subject. Where is my best start to learn PS?

I tried to keep it pretty up to date but some of the books are a bit old. I would still recommend the oreilly powershell cookbook + intro book, I assume they have been updated for V2 by now.

joe944
Jan 31, 2004

What does not destroy me makes me stronger.
Scripting noob here working on my first powershell script and I'm wondering if anyone would be able to help me out.

What I'm trying to do is periodically check the external IP address of a machine and determine if it has changed or not. Preferably if the IP has changed it would create an event log that will be picked up by another monitoring tool.

Feel free to tell me I'm retarded for what I've got so far. It's not complete and doesn't quite do what I want yet, but I think I'm on the right track. I need to do some serious reading up on powershell in general but I've picked up a little bit working on this script so far.

code:
$filename = "path\iplog.txt"
$time = " "+(Get-Date).ToString()
$source = "http://whatismyip.org"
$client = new-object System.Net.WebClient
$webpage = $client.downloadString($source)
$lines = $webpage.split("'n")
foreach ($line in $lines) {
    $value = "6522 "+$line +$time
    $value >> $filename
}
$oldip = get-eventlog -logname 'IP Check' -newest 1 | select message

Write-EventLog  -logname 'IP Check' -source 'IP Check' -eventid 1000 -entrytype information -message $line

kampy
Oct 11, 2008

Scaramouche posted:

Got some more goodies for you PS gurus. I'm trying to de-dupe that enormous file list mentioned previous (29,000 image files). I'm using this guy's script to find them:
http://blog.codeassassin.com/2007/10/13/find-duplicate-files-with-powershell/

Seems pretty good (goes by size and then md5), and the counts are really handy. Some of the files are duplicated over 1000 times. The problem I'm having though, is it's good to know the counts, but what I really need are all the duplicated file names themselves. Unfortunately the output of the script looks like this:
code:
Count   Name                  Groups
95	137 255 159 230 40 53 {127769_5.jpg, 127770_4.jpg...}
Where the ... is where the file list gets truncated. I >think< this could be controlled with Format-Table, but I'm not sure how I could get it to work, since in some cases (over 1000 file names) I'm probably going to run up against some kind of internal limit in powershell.

My other option is tweaking the script itself, since I don't actually need file counts and the 'name' column, all I would need is something like this:
code:
ID   FileName
1    127769_5.jpg
1    127770_4.jpg
1    127771_3.jpg
2    131110_1.jpg
2    131111_2.jpg
2    131112_3.jpg
etc.
Where the 'ID' just denotes that 'yes all of these files are the same'. The second option is actually more useful to me, because then I could relatively quickly turn this list into SQL, instead of having to harvest out several comma-delimited lists like the Format-Report solution does. My tweaking has not found success thus far though, resulting only in errors, returning no files, or returning that all files are identical. My questions are thus:
1. Do you guys think that I should be concentrating on Format-Report or just tweaking the script to get my desired output? Can Format-Report columns even go that large?
2. Anyone have any advice on how to get the desired output in the second example from the script linked above?

Thanks in advance for any help.

I would just modify the script a bit, or perhaps just run something like:
code:
$dupes = .\unmodifiedscriptfromtheweb.ps1 c:\whatever\path
foreach ($dupe in $dupes)
{
	foreach ($d in $dupe.Group)
	{
		# Change $d.Name to $d.FullName for the full path.
		"{0} *{1}" -f $dupe.Name, $d.Name
	}
	write-host ""
}
You could also modify the script a bit so that it produces a prettier md5 output by modifying the Get-MD5 function to something like this:
code:
function Get-MD5([System.IO.FileInfo] $file = $(throw ‘Usage: Get-MD5 [System.IO.FileInfo]‘))
{
# This Get-MD5 function sourced from:
# [url]http://blogs.msdn.com/powershell/archive/2006/04/25/583225.aspx[/url]
$stream = $null;
$cryptoServiceProvider = [System.Security.Cryptography.MD5CryptoServiceProvider];
$hashAlgorithm = new-object $cryptoServiceProvider
$stream = $file.OpenRead();
$hashByteArray = $hashAlgorithm.ComputeHash($stream);
$stream.Close();

## We have to be sure that we close the file stream if any exceptions are thrown.
trap
{
if ($stream -ne $null) { $stream.Close(); }
break;
}

foreach ($byte in $hashByteArray)
{
	$returnme += $byte.ToString("x2")
}
return $returnme
}
Edit:
You could also do something like this:
code:
$output = ""
$dupes = .\unmodifiedscriptfromtheweb.ps1 c:\whatever\path
foreach ($dupe in $dupes)
{
	foreach ($d in $dupe.Group)
	{
		$whatwewant = @{md5=$dupe.Name; filename=$d.Name}
		[array] $output += new-object psobject -property $whatwewant
	}
}
$output

kampy fucked around with this message at 10:32 on Nov 10, 2011

Jelmylicious
Dec 6, 2007
Buy Dr. Quack's miracle juice! Now with patented H-twenty!

joe944 posted:

Scripting noob here working on my first powershell script and I'm wondering if anyone would be able to help me out.

What I'm trying to do is periodically check the external IP address of a machine and determine if it has changed or not. Preferably if the IP has changed it would create an event log that will be picked up by another monitoring tool.

Feel free to tell me I'm retarded for what I've got so far. It's not complete and doesn't quite do what I want yet, but I think I'm on the right track. I need to do some serious reading up on powershell in general but I've picked up a little bit working on this script so far.

code:
$filename = "path\iplog.txt"
$time = " "+(Get-Date).ToString()
$source = "http://whatismyip.org"
$client = new-object System.Net.WebClient
$webpage = $client.downloadString($source)
$lines = $webpage.split("'n")
foreach ($line in $lines) {
    $value = "6522 "+$line +$time
    $value >> $filename
}
$oldip = get-eventlog -logname 'IP Check' -newest 1 | select message

Write-EventLog  -logname 'IP Check' -source 'IP Check' -eventid 1000 -entrytype information -message $line

Few questions/Comments:

You put the old IP address into $oldip, but you never do anything with it.
Do you want to log an event every time the IP changes, or (like you currently do) every time the script checks?
You will never clean your iplog.txt (I assume you use a valid path in the path part). This will slowly grow, even though you are also putting this info in the IP check eventlog.
First run fails on the $oldip line, because the first log isn't there. I will go practice my try/catches.

Edit: Here's my take. I simplified it a bit:
  • You don't need the log file (unless you want it).
  • Removed the foreach loop, because your $lines only contained the IP anyway, renamed that to $IP
  • Removed the select message, Because it is only for display purposes
  • Added in a check for $OldIP.message, to compare IP addresses
  • Made sure the custom eventlog is there, if not, make it.
  • Made two different event-id codes: ID 1000 on first run, 1001 on IP changes. You could also have it log every time it runs and differentiate between changes and no changes. Just add an else to the if.
code:
#Get IP Address
$source = "http://whatismyip.org"
$client = new-object System.Net.WebClient
$webpage = $client.downloadString($source)
$IP = $webpage.split("'n")

#Check if the custom eventlog exists, if not: create it
try 
    {
    get-eventlog -logname 'IP Check'
    }
catch 
    {
    write-host Creating Eventlog
    new-eventlog -logname 'IP Check' -source 'IP Check'
    }

#Try to get eventlog, then compare. Write EventID 1001 on IP change, Write EventID 1000 on first run
try 
    {
    $OldIP = get-eventlog -logname 'IP Check' -newest 1 
    If (!($OldIP.message -eq $IP)) 
        {
        Write-EventLog  -logname 'IP Check' -source 'IP Check' -eventid 1001 -entrytype information -message "$IP"
        }
    }
Catch #First entry into Eventlog
    {
    Write-EventLog  -logname 'IP Check' -source 'IP Check' -eventid 1000 -entrytype information -message $IP
    }
Now, we could always make it slicker, by making the eventlogs more readable. That would need some better text-parsing when comparing the IP addresses though. If you could connect an SMTP server reliably from this computer, you could have it e-mail you on changes. But that is dependent on the final goal of this script.

Jelmylicious fucked around with this message at 11:05 on Nov 10, 2011

joe944
Jan 31, 2004

What does not destroy me makes me stronger.
It was a rough draft. :D My goal with $oldip was to pull the IP from the last event log and compare it to the recently polled IP from whatismyip. I'd like to use a loop to send out a different type of event log if the IP changes and perhaps send out an email.

The path for the iplog.txt was correct. That was the original log that I wrote to; using events was something I tacked quickly at the end but I think would be a superior method. I may still keep that log file just to have a consolidated list of past IP's. Would there be a way to only append the log when a new IP is discovered instead of everytime the script is run?

Appreciate the help.

Edit: That's awesome! I will have to break down the details and figure out why you did what you did tomorrow but that looks like exactly what I need to get this to work.

joe944 fucked around with this message at 11:15 on Nov 10, 2011

Jelmylicious
Dec 6, 2007
Buy Dr. Quack's miracle juice! Now with patented H-twenty!
Since my script compares IP's when writing to the eventlog, you can have it output to a textfile in the same if-statement. If you want to add an eventlog for every check, we could do something like this (only relevant code shown). Note that, since I added an else statement, I removed the negatement in the if statements, for legibility purposes.

code:
#Try to get eventlog, then compare. Write EventID 1001 on IP change, Write EventID 1000 on first run or no change
try 
    {
    $OldIP = get-eventlog -logname 'IP Check' -newest 1 
    If ($OldIP.message -eq $IP)
        {
        Write-EventLog  -logname 'IP Check' -source 'IP Check' -eventid 1000 -entrytype information -message "$IP"
        }
    Else
    {
    $time = 
    Write-EventLog  -logname 'IP Check' -source 'IP Check' -eventid 1001 -entrytype information -message "$IP"
    $after = (Get-Date).ToString("D")
    $before = $oldIP.timewritten.tostring("D")
    $message = "IP Changed to $IP between $before and $after"
    $message | out-file $filename
    }
    }
Catch #First entry into Eventlog
    {
    Write-EventLog  -logname 'IP Check' -source 'IP Check' -eventid 1000 -entrytype information -message $IP
    }
And, in the same block (or maybe make that a function), you can add code to e-mail $message, using send-mailmessage (Powershell v2 only)

Edit: If you are running this on computers with other languages than english, it could be a good idea to force your tostring to use english, like this (replace "en-US" with whatever you want, like "nl-NL" for Dutch).
code:
$Culture = New-Object System.Globalization.CultureInfo("en-US")
$before = $oldIP.timewritten.tostring("D",$Culture)
Different formats for putting time in a string can be used. I noticed I used "D" up there, which is not that good in this instance (no time of day). "r" might be better, which will give you: Thu, 05 Jun 2008 16:40:37 GMT, or "f", since you don't need seconds. "f" will give you: Thursday, June 05, 2008 4:40 PM. See here for details.

Jelmylicious fucked around with this message at 11:51 on Nov 10, 2011

KS
Jun 10, 2003
Outrageous Lumpwad
So I'm a rank beginner at this and I'm embarrassed to post this snip. When a SAN-based snapshot is presented to a different server, it shows up with some flags set on the volumes. I am trying to enumerate those volumes and generate a diskpart script to unset the flags.

code:
$diskpart = diskpart /s diskpartlist.txt | Select-String -pattern "Hidden"

$a = $diskpart[0]
$a = $a.tostring()
$a = $a.substring(2,13)
$a = "select $a"

$b = $diskpart[1]
$b = $b.tostring()
$b = $b.substring(2,13)
$b = "select $b"


write-output $a "att vol clear readonly" "att vol clear hidden" "att vol clear shadowcopy" $b 
`"att vol clear readonly" "att vol clear hidden" "att vol clear shadowcopy" | out-file diskpart.txt

diskpart /s diskpart.txt
The content of diskpartlist.txt is just "list volume" The above generates a file that can be fed into diskpart that looks like:

code:
select volume 3
att vol clear readonly
att vol clear hidden
att vol clear shadowcopy
select volume 7
att vol clear readonly
att vol clear hidden
att vol clear shadowcopy
I ran into so many things I need to learn along the way with the format of the data and breaking it up into useful chunks: system objects vs. arrays vs. strings and the tools you can use for each. For instance, you can write "select $a" to a file and it works, but you cannot write "select $a.substring(2,13)"

I know it shouldn't be this hard, and I really want to learn how to do this better (and generalize it for result sets of indeterminate size). I just feel lost without awk and sed.

joe944
Jan 31, 2004

What does not destroy me makes me stronger.
You're awesome, I got everything working perfectly. Now to do some experimentation for more advanced features!

I think powershell is going to come in very handy..

Jelmylicious
Dec 6, 2007
Buy Dr. Quack's miracle juice! Now with patented H-twenty!

KS posted:

I ran into so many things I need to learn along the way with the format of the data and breaking it up into useful chunks: system objects vs. arrays vs. strings and the tools you can use for each. For instance, you can write "select $a" to a file and it works, but you cannot write "select $a.substring(2,13)"

I know it shouldn't be this hard, and I really want to learn how to do this better (and generalize it for result sets of indeterminate size). I just feel lost without awk and sed.

Well, for the indertimenate size, you could use a foreach loop. Without adjusting your code too much:

code:
$diskpart = diskpart /s diskpartlist.txt | Select-String -pattern "Hidden"
Foreach ($volume in $diskpart)
    {
    $a = $Volume.tostring()
    $a = $a.substring(2,13)
    $a = "select $a"
    write-output $a "att vol clear readonly" "att vol clear hidden" "att vol clear shadowcopy" | out-file diskpart.txt -append
    }
This is quick, dirty and not tested, because it is late. Also, for basic string manipulation, put stuff outside of quotes:
code:
$a = "Select " + $a.substring(2,13)

Janitor Prime
Jan 22, 2004

PC LOAD LETTER

What da fuck does that mean

Fun Shoe
I did something stupid. I associated .ps files with notepad++ because I was tired of having them open in regular notepad, but I've lost the ability to right-click and run with powershell.

Does anyone know how I can make it work again?

joe944
Jan 31, 2004

What does not destroy me makes me stronger.

MEAT TREAT posted:

I did something stupid. I associated .ps files with notepad++ because I was tired of having them open in regular notepad, but I've lost the ability to right-click and run with powershell.

Does anyone know how I can make it work again?

What OS are you running? Does right click > open with > choose default program and select powershell work?

Jelmylicious
Dec 6, 2007
Buy Dr. Quack's miracle juice! Now with patented H-twenty!
My turn for a question:

I will be giving my companies internal Introduction to Powershell course. It will be a two day course for anyone ranging from "never touched powershell" to seasoned sysadmins that know VB by heart, but want to get to know powershell better. (oh god, what am I getting myself into? :ohdear:)
The current iteration of the course is a bit to dry and doesn't allow for that much input from the students about what they want to learn. I am going to make this course more hands-on and practical. My question to you is:
Is there anything that you ever ran into, while using powershell, where you thought to yourself: "If only I had known this when I started out, this would have saved so much time!"
Help me make this course awesome, so my newly made minions can help answer questions in this thread.

Janitor Prime
Jan 22, 2004

PC LOAD LETTER

What da fuck does that mean

Fun Shoe

joe944 posted:

What OS are you running? Does right click > open with > choose default program and select powershell work?

I'm on Windows 7 32bit. It wasn't working at first but it turns out it was because there was a space in my path! The error message was popping up too fast for me to read and I thought it was just broken. Then I managed to grab the error message by timing print screen just right, and moved the file to another folder. Now it works just as you said.

:D

adaz
Mar 7, 2009

Jelmylicious posted:

My turn for a question:

I will be giving my companies internal Introduction to Powershell course. It will be a two day course for anyone ranging from "never touched powershell" to seasoned sysadmins that know VB by heart, but want to get to know powershell better. (oh god, what am I getting myself into? :ohdear:)
The current iteration of the course is a bit to dry and doesn't allow for that much input from the students about what they want to learn. I am going to make this course more hands-on and practical. My question to you is:
Is there anything that you ever ran into, while using powershell, where you thought to yourself: "If only I had known this when I started out, this would have saved so much time!"
Help me make this course awesome, so my newly made minions can help answer questions in this thread.

Advanced Functions & Error Handling but for a 2 day course it'd be a little hard to cram all that on in. I guess, in general the thing I really wish I had known is how to access the entire .net framework from the shell, the syntax for how to call methods/properties on various classes.

adaz fucked around with this message at 18:51 on Nov 14, 2011

Sickening
Jul 16, 2007

Black summer was the best summer.
I hate to ask a vb script question in a powershell thread, but you are probably the same braintrust that would answer the question anyway.

In the following script, I would like to modify two registry entries instead of the one. I can't figure out if I need a different variable or if I am simply entering the second registry key in the wrong location. Anybody have any ideas?


on error resume next
Const HKEY_LOCAL_MACHINE = &H80000002
strPC = InputBox("Type the computer name here.")
Set objReg = GetObject("winmgmts:{impersonationLevel=impersonate}!\\" & strPC & "\root\default:StdRegProv")
strKey = "SYSTEM\CurrentControlSet\Control\Class\{4D36E972-E325-11CE-BFC1-08002bE10318}\0010"
objReg.CreateKey HKEY_LOCAL_MACHINE,strKey
strEntry = "lom"
strValue = 1
objReg.SetStringValue HKEY_LOCAL_MACHINE, strKey, strEntry, strValue
on error goto 0

adaz
Mar 7, 2009

Madmaan it has been awhile since I've touched vbscript but I don't see anything obviously wrong and the setstringvalue syntax you're using is right(http://msdn.microsoft.com/en-us/library/windows/desktop/aa393600%28v=vs.85%29.aspx).

Also for those of you who, like me, have been incredibly annoyed with Export-CSVs inability to handle the vast majority of piped input well the scripting guys wrote an article on it and yet another way to get around it: http://blogs.technet.com/b/heyscriptingguy/archive/2011/11/15/see-why-powershell-can-t-export-some-properties-to-csv.aspx

Quebec Bagnet
Apr 28, 2009

mess with the honk
you get the bonk
Lipstick Apathy

Jelmylicious posted:

My turn for a question:

I will be giving my companies internal Introduction to Powershell course. It will be a two day course for anyone ranging from "never touched powershell" to seasoned sysadmins that know VB by heart, but want to get to know powershell better. (oh god, what am I getting myself into? :ohdear:)
The current iteration of the course is a bit to dry and doesn't allow for that much input from the students about what they want to learn. I am going to make this course more hands-on and practical. My question to you is:
Is there anything that you ever ran into, while using powershell, where you thought to yourself: "If only I had known this when I started out, this would have saved so much time!"
Help me make this course awesome, so my newly made minions can help answer questions in this thread.

One thing that may appeal to your audience is the much cleaner (compared to VBScript) Active Directory integration, at least in my experience probably 3/4 of the Windows scripting I do involves AD in some way. You could mention either the .NET AccountManagement namespace or the wealth of cmdlets available in 2008 R2.

bluegoon
Mar 5, 2010

by Pragmatica
$a = get-childitem C:\Comps\complist.txt
Get-EventLog system -computername $a -newest 3 > systemout.txt

I want to have a list of machines in complist.txt, and have powershell output their eventlogs (system) to systemout.txt, very very new to logic and programming.

Adbot
ADBOT LOVES YOU

Jelmylicious
Dec 6, 2007
Buy Dr. Quack's miracle juice! Now with patented H-twenty!

bluegoon posted:

$a = get-childitem C:\Comps\complist.txt
Get-EventLog system -computername $a -newest 3 > systemout.txt

I want to have a list of machines in complist.txt, and have powershell output their eventlogs (system) to systemout.txt, very very new to logic and programming.

Get-Childitem is enumerating files in a folder, it is the new "dir". What you want is:
code:
$computers = get-content C:\Comps\complist.txt
As for the rest, apart from having to use -logname in front of system, it should work. But I would prefer exporting to a CSV for better manipulation of the data afterwards, like this:
code:
Get-EventLog -computername $computers -newest 3 -logname "System" | Export-CSV systemout.csv
Also, try not to use $a far any variable, it isn't readable

e: Aparently Get-Eventlog System should work too, so your second line should work as intended. Apart from it not showing the full info in your text file. So, at least use the export-csv.

Jelmylicious fucked around with this message at 16:13 on Nov 23, 2011

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