Ying Li(MVP) at myITforum.com

PowerShell & System Center

September 2007 - Posts

PowerShell cmdlet to compare two different objects

Ever has a need to find out what process an application is running as. PowerShell can help.

Let's see you want to know what process AIM running under, before you start AIM, do this:

$x = get-process

Then start AIM and grab the second snapshot:

$y = Get-process

Now you can get the difference by doing this:

Compare-object $x $Y

The output will be something like this:

InputObject                                                 SideIndicator
-----------                                                 -------------
System.Diagnostics.Process (aim6)                           =>
System.Diagnostics.Process (anotify)                        =>
System.Diagnostics.Process (aolsoftware)                    =>
System.Diagnostics.Process (aolsoftware)                    =>
System.Diagnostics.Process (EXCEL)                          <=
 
                                                     
The => sign indicates that the AIM processes were found in the second object, but not found in the first object. The <= sign indicates that the EXCEL process was found in

the first object not the second object(I closed EXCEL before I grab the second set).


You could use the same technique to compare process or eventlog etc on different computer or the same computer at different time.

You can also use this cmdlet to compare two text files

compare-object (type c:\temp\server1.txt) (type c:\temp\server2.txt)

InputObject                                                 SideIndicator                                             

-----------                                                 -------------                                             

IPAddress=192.168.1.11                                      =>                                                        

IPAddress=192.168.1.10                                      <=                                                        

MACAddress=00.11.28.75.DF.DA                                =>                                                        

MACAddress=00.11.28.75.CD.48                                <=                                                        

ComputerName=SERVER2                                        =>                                                        

ComputerName=SERVER1                                        <=                                                        

.
.
.

What can I say? PowerShell Rocks!

 

Posted: Sep 28 2007, 08:01 PM by yli628 | with no comments
Filed under:
How Windows PowerShell handles blank space in the file path?

Here is a little script to get AIM process on the computer, nothing special about it.

get-process | where {$_.ProcessName -match "aim*"}

PS C:\> c:\ps\test.ps1

Handles  NPM(K)    PM(K)      WS(K) VM(M)   CPU(s)     Id ProcessName         
-------  ------    -----      ----- -----   ------     -- -----------         
    521      13    63760      15024   180     9.11   3904 aim6 

If I save it in C:\Documents and Settings\Ying\My Documents\PS\ and run it

PS C:\> C:\Documents and Settings\Ying\My Documents\PS\test.ps1


The term 'C:\Documents' is not recognized as a cmdlet, function, operable progr
am, or script file. Verify the term and try again.
At line:1 char:13
+ C:\Documents  <<<< and Settings\Ying\My Documents\PS\test.ps1

I get an error, this is because there are blank spaces in the path

In order to run it – I have to do the following:


PS C:\Documents and Settings\Ying\My Documents\PS> & "C:\Documents and Settings\Ying\My Documents\PS\test.ps1"

Handles  NPM(K)    PM(K)      WS(K) VM(M)   CPU(s)     Id ProcessName         
-------  ------    -----      ----- -----   ------     -- -----------         
    521      13    63760      15032   180     9.13   3904 aim6      

Now try to do the same from start-run command

Powershell.exe -noexit c:\ps\test.ps1

Handles  NPM(K)    PM(K)      WS(K) VM(M)   CPU(s)     Id ProcessName         
-------  ------    -----      ----- -----   ------     -- -----------         
    521      13    63760      15024   180     9.11   3904 aim6 

The result is expected. but what about doing this:

powershell.exe -noexit & "C:\Documents and Settings\Ying\My Documents\PS\test.ps1"

The term 'C:\Documents' is not recognized as a cmdlet, function, operable progr
am, or script file. Verify the term and try again.
At line:1 char:2
+ &  <<<< C:\Documents and Settings\Ying\My Documents\PS\test.ps1
PS C:\PS>

How we do this from start -run?

powershell.exe -noexit & 'C:\Documents and Settings\Ying\My Documents\PS\test.ps1'

Handles  NPM(K)    PM(K)      WS(K) VM(M)   CPU(s)     Id ProcessName         
-------  ------    -----      ----- -----   ------     -- -----------         
    521      13    63760      15024   180     9.11   3904 aim6 

So if you want to run a powershell script with blank space in it’s path, you have to add “” if you run it in PowerShell console;  add ‘’ if you want to run it from start -run command. Of course, don’t forget the &!


Confused? you are not alone!

 

Posted: Sep 26 2007, 10:29 PM by yli628 | with 3 comment(s)
Filed under:
How to enter password as secure string

In PowerShell script or interactive session, sometimes we will need to ask and store user password information. See below recorded PowerShell session:

PS C:\PS> $name = read-host "Please Enter Your Name"
Please Enter Your Name: Ying Li
PS C:\PS> $pw = read-host "Please Enter Your Password"
Please Enter Your Password: Password1
PS C:\PS> $pw
Password1

The password typed and stored as a plain text which is not we would like. How can we mask the password?

PS C:\PS> $pw = read-host "Please Enter Your Password" -AsSecureString
Please Enter Your Password: *********

PS C:\PS> $pw
System.Security.SecureString

The password is typed as * characters and stored as a “SecureString”

Now you may ask, what if I want to know the password?

The following method will get our password back in plain text

PS C:\PS> $BasicString = [System.Runtime.InteropServices.Marshal]::SecureStringToBSTR($pw)
PS C:\PS> $pw = [System.Runtime.InteropServices.Marshal]::PtrToStringAuto($BasicString)
PS C:\PS> $pw
Password1

 

 

Posted: Sep 22 2007, 11:05 PM by yli628 | with no comments
Filed under:
Finding fidden files/folders using PowerShell

To display hidden files or folders, use the Force parameter with the get-childitem cmdlet.

Please see below recorded session in PowerShell:


PS C:\> Get-ChildItem


    Directory: Microsoft.PowerShell.Core\FileSystem::C:\


Mode                LastWriteTime     Length Name                             
----                -------------     ------ ----                             
d----         5/13/2005  11:29 PM            DELL                             
d----          5/9/2005   8:23 PM            Documents and Settings           
d----          8/3/2006  10:45 PM            i386                             
d----         8/25/2007   6:06 PM            My Downloads                     
d----         8/25/2007  10:33 PM            mytest                           
d----          3/1/2007   1:55 PM            Office 2007                      
d----         7/22/2007   1:09 PM            Opsware                          
d----         8/27/2007   7:22 PM            Program Files                    
d----          9/5/2007  10:13 PM            PS                               
d----         8/28/2007   9:36 PM            Temp                             
d----         9/15/2007   8:09 PM            WINDOWS                          
d----         5/10/2005  12:39 AM            winnt                            
-a---          5/9/2005   7:58 PM          0 AUTOEXEC.BAT                     
-a---        12/28/2005  10:12 PM       8717 caavsetup.log                    
-a---        12/14/2006   7:19 PM      35041 caavsetupLog.txt                 
-a---         8/28/2007   2:57 PM      68896 caisslog.txt                     
-a---          2/2/2007   8:36 PM        219 cmd.txt                          
-a---          1/4/2007   7:55 PM          0 COMLOG.txt                       
-a---          5/9/2005   7:58 PM          0 CONFIG.SYS                       
-a---          4/3/2007  10:10 PM         81 DVDPATH.TXT                      
-a---         7/22/2007   3:34 PM       1346 nonav.log                        

Now add -force switch
PS C:\> Get-ChildItem -force


    Directory: Microsoft.PowerShell.Core\FileSystem::C:\


Mode                LastWriteTime     Length Name                             
----                -------------     ------ ----                             
d--h-         9/11/2007   8:57 PM            Config.Msi                       
d----         5/13/2005  11:29 PM            DELL                             
d----          5/9/2005   8:23 PM            Documents and Settings           
d----          8/3/2006  10:45 PM            i386                             
d-rh-          3/1/2007   2:37 PM            MSOCache                         
d----         8/25/2007   6:06 PM            My Downloads                     
d----         8/25/2007  10:33 PM            mytest                           
d----          3/1/2007   1:55 PM            Office 2007                      
d----         7/22/2007   1:09 PM            Opsware                          
d----         8/27/2007   7:22 PM            Program Files                    
d----          9/5/2007  10:13 PM            PS                               
d--hs         5/10/2005  12:38 AM            RECYCLER                         
d--hs          5/9/2005   8:16 PM            System Volume Information        
d----         8/28/2007   9:36 PM            Temp                             
d----         9/15/2007   8:09 PM            WINDOWS                          
d----         5/10/2005  12:39 AM            winnt                            
-a---          5/9/2005   7:58 PM          0 AUTOEXEC.BAT                     
-arhs         3/19/2007   4:58 PM        211 boot.ini                         
-a---        12/28/2005  10:12 PM       8717 caavsetup.log                    
-a---        12/14/2006   7:19 PM      35041 caavsetupLog.txt                 
-a---         8/28/2007   2:57 PM      68896 caisslog.txt                     
-a---          2/2/2007   8:36 PM        219 cmd.txt                          
-a---          1/4/2007   7:55 PM          0 COMLOG.txt                       
-a---          5/9/2005   7:58 PM          0 CONFIG.SYS                       
-a---          4/3/2007  10:10 PM         81 DVDPATH.TXT                      
-arhs          5/9/2005   7:58 PM          0 IO.SYS                           
-a-h-         3/16/2006   7:02 PM        437 IPH.PH                           
-arhs          5/9/2005   7:58 PM          0 MSDOS.SYS                        
-a---         7/22/2007   3:34 PM       1346 nonav.log                        
-arhs         8/12/2004   9:25 AM      47564 NTDETECT.COM                     
-arhs         8/12/2004   9:25 AM     250032 ntldr                            
-a-hs         9/15/2007   7:58 PM  804089856 pagefile.sys                     

What a difference –force make! The hidden folders RECYCLER, System Volume Information or files pagefile.sys, NTDETECT.com, etc. all show up…

Posted: Sep 18 2007, 09:12 PM by yli628 | with no comments
Filed under:
The Comlet to record a PowerShell session

Sometime when we write powershell scripts, we will need to test out a lot of lines in the interactive PowerShell session. Once we have the working “lines”, we want to copy them back to the script. You can use edit -select -copy as in DOS. But PowerShell has two builtin cmdlets to help us recording a PowerShell session.

Start-Transcript – creates a record of all or part of a Windows PowerShell session in a txt file. The transcript includes all command that the user types and all output that appears on the console.

Stop-Transcript – stops a transcript that was started by using the Start-Transcript cmdlet. Of course, you can also stop a stranscript by ending the session.

Here is a sample output file:

**********************
Windows PowerShell Transcript Start
Start time: 20070915230637
Username  : MAYFLOWER\Ying
Machine   : MAYFLOWER (Microsoft Windows NT 5.1.2600 Service Pack 2)
**********************
Transcript started, output file is C:\Documents and Settings\Ying\My Documents\
PowerShell_transcript.20070915230637.txt
PS C:\PS> Get-Process svc*

Handles  NPM(K)    PM(K)      WS(K) VM(M)   CPU(s)     Id ProcessName         
-------  ------    -----      ----- -----   ------     -- -----------         
    228       6     3712       2916    68     1.40    356 svchost             
     94       5     2316        644    37     0.56    448 svchost             
    662      15     3292       3376    47    17.76    808 svchost             
    232       7     3856       1424    48     0.69    996 svchost             
   1948      94    24368      14688   169    37.35   1512 svchost             
    133       3     3000        148    39     0.39   1836 svchost             
    156       4     3264       1060    45     1.91   2084 svchost             
    101      12     2112        180    43     1.15   2772 svchost             


PS C:\PS> stop-process

cmdlet stop-process at command pipeline position 1
Supply values for the following parameters:
Id[0]: PS C:\PS> Stop-Transcript
**********************
Windows PowerShell Transcript End
End time: 20070915230700
**********************

Is this cool or what?

 

Posted: Sep 15 2007, 11:30 PM by yli628 | with no comments
Filed under:
One step further - PowerShell script to modify multiple users' property in Active Directory

In my previous script, I showed how we can add or modify the user propertites in Active Directory for single user. Now as a by request script, I will go one step further and try to do the samething for multiple users. The trick is you need to have a csv file ready and the import-csv cmdlet.

I have a sample users.csv file and it looks like this:

DN                                                                                       Telephonenumber
CN=UserA,OU=X,OU=Y,OU=Z,DC=what,DC=ever,DC=com      xxx-yyy-zzz
CN=UserB,OU=A,OU=B,OU=C,DC=what,DC=ever,DC=com     aaa-bbb-ccc
CN=UserC,OU=L,OU=M,OU=N,DC=what,DC=ever,DC=com     lll-mmm-nnn

 

Once you have the csv file ready – you could run the below script against it (You need to have the approriate right to your domain!)

$users = import-csv users.csv
foreach($row in $users)
{
$dn = $row.dn
$user=[ADSI]"LDAP://$dn"
$tel = $row.telephonenumber
$user.put("telephoneNumber", $tel)
$user.SetInfo()
}

You could change the Telephonenumber to EmployeeID or whatever fields you are interested at and it can target as many users as you want. Of course, test it in a small scale first!

Posted: Sep 11 2007, 10:15 AM by yli628 | with 9 comment(s)
Filed under:
PowerShell script to modify user properties in Active Directory

Here is a PowerShell script to modify user properties in Active Directory such as telephone number or employeeid, etc.

In some case you will need to extend your AD schema first – like to add the employeeid field.

$rootdn=([adsi]"").distinguishedName
$ou=[adsi]("LDAP://ou=x,ou=y,ou=z,"+ $rootdn)
$user=$ou.psbase.children.find("cn=Li\, Ying \ ")
$user.put("telephonenumber","xxx-xxx-xxx")
$user.setinfo()

With a little bid more work, we could make this to work for multiple users – ever has a need to update telephone number for 1000 users in AD?

Posted: Sep 10 2007, 04:18 PM by yli628 | with no comments
Filed under:
PowerShell script to check how many items are in the quarantine folder - Symantec

Here is a by request powershell script to check how many items are in Quarantine folder and you can easily merge it with my Previous Script to make it to work on multiple computers.

$a = new-object -comobject MSScriptControl.ScriptControl
$a.language = "vbscript"
$a.addcode("function getInput() getInput = inputbox(`"Enter Your Computer Name`",`"Computer Name`") end function" )
$strComputer= $a.eval("getInput")


Function GetQItems
{
$QFolder = "\\$strcomputer\c$\Documents and Settings\All Users\Application Data\Symantec\Symantec AntiVirus Corporate Edition\7.5\Quarantine"
$x = (get-childitem $QFolder).count
Write-host "There are currently" $x "items in Quarantine Folder on $strComputer!"
}
GetQItems

Posted: Sep 06 2007, 11:29 AM by yli628 | with no comments
Filed under: ,
Windows PowerShell: Securing the Shell -- TechNet Magazine, September 2007

Windows PowerShell: Securing the Shell -- TechNet Magazine, September 2007.

Posted: Sep 06 2007, 09:20 AM by yli628 | with no comments
Filed under: