Maximo 的个人资料Max - Put It Together照片日志列表更多 工具 帮助

日志


3月11日

So Florida.Net User group presentation: Powershell v2 Remoting features

First, THANKS for everyone who show up to see my presentation and I hope that I have pass some valuable information about Powershell.  Here's a *ZIP file with my presentation (including my demo psscripts).  Please, keep in mind, the final demo on backup/restore of the database, you need to have some SQL Features for both SQL 2k5 and 2k8 in place.  If you need some additional information don't hesitate to email me.

<download me: SoFlaDotNet_PowerShellv2Remoting.zip >

Please keep supporting our Florida .Net Community by attending our events.

Thanks again,

Max

:)

3月4日

Powershell CTP v2 – Remoting: “Invoke-Expression” consideration...

Powershell Remoting is an excellent feature which can be exploit by everyone. But it has its limitation. At work, I need of building a solution that would automate a manual process for our IT staff. In this case, I had to create a Powershell script (psscript) that will allow me to copy a file in the user desktop for later retrieval without interrupting his work. So, I decided to use Powershell Remoting features using the CMDLET “Invoke-Expression” ran some with/without the “-runspace” switch.

Here’s what I found out :

1. If you have the need to passing strings parameters, no spaces are allowed. Exception – when using the “-runspace” parameter with “dir” commands. You might have a folder name with spaces “’My Documents”. In this case you need to add the single quote in the string, sample $dirName = “’My Documents’”.

2. You can’t use the “-credential” parameter past invoking the psscript on another computer. I mean, if within the script you is trying to copy a file to a network folder, the credential only work for executing the script.

3. When using the “-runspace” parameter make sure to use the “Remove-Runspace” CMDLET or the connection to the computer stays active.

See below:

Sample code for executing a PSscript remotely
" HelloPS.ps1 "

########################################
## HelloPS.ps1
## To test a string value with spaces
########################################

param($arg);
if ($arg -eq "Max Trinidad") {
Write-host -foreground green "*HelloPS* - Hello World!! My name is $arg, Its working!!"
} else {
write-host -foreground yellow "*HelloPS* - I'm missing my name again?? ** $arg **"}

## End of Script ##

Sample code for executing a PSscript remotely
" HelloPS2.ps1 "

########################################
## HelloPS2.ps1
## To test a string value with no spaces
########################################

param($arg);
if ($arg -eq "Max") {
Write-host -foreground green "*HelloPS2* - Hello World!! My name is $arg, Its working!!"
} else {
write-host -foreground yellow "*HelloPS2* - I'm missing my name again?? ** $arg **"}

## End of Script ##

String Sample #1 - Using the -runspace parameter showing losing of some string value when passing to a remote script.
StringSample1
String Sample #2 - showing how the filesystem CMDLET "Dir" handles a string value with spaces to a remote script.
StringSample2
String Sample #1 - Without the -runspace parameter showing losing of some string value when passing to a remote script.
StringSample3
Copy2Net Samples - Shows some limitation when trying to a "Copy" CMDLET.
SampleCopy2Net1
SampleCopy2Net2

So, as you can see, there some limitations in using this feature.  But, it doesn't leave dead in the water.  You still can run script remotely as long as it contains no spaces, it must run local on the remote computer, and you can use the *-PSjob CMDLET to run in the background of the remote computer.  This coming Tuesday March 11th I will be speaking about "Powershell 2.0 CTP Remoting features". I will have my presentation and samples available later.

3月2日

SQL Server 2008 Features Require PowerShell

(extracted from ReadmeSQL2008.htm)

SQL Server 2008 Setup installs PowerShell 1.0, which is used by the following SQL Server 2008 PowerShell features: the sqlps.exe utility; SQL Server Management Studio Object Explorer right-click menus that launch SQL Server PowerShell scripts; and creating or running scheduled SQL Server Agent PowerShell job steps. If PowerShell is uninstalled after Setup completes, these features will not function. PowerShell can be uninstalled by Windows users, and uninstalling PowerShell may be required by some Windows operating system upgrades. If PowerShell has been uninstalled and you wish to use the SQL Server PowerShell features, you must either:

  • Manually download and reinstall PowerShell 1.0 from the Microsoft Download Center. Download instructions are on the Windows Server 2003 Web site.
  • If you are running Windows Server 2008, PowerShell 1.0 exists in the operating system but is disabled by default. You can re-enable PowerShell from Windows Server 2008.
clip_image002

Note: You can’t use Powershell CTP V2 with SQL Server 2008. On Windows Servers 2008, you can install Powershell v1 after installing SQL Server 2008 CTP Feb2008.

Other Microsoft Applications using Powershell:

1. Microsoft Exchange

2. Microsoft System Virtual Machine Manager Center

2月7日

Powershell - Using WMI "Win32_OperatingSystem" for Restart/Shutdown

Following script will accomplish the task of either Reboot or Shutdown a computer:

I've been using a version of this script on my network environment:

##--- Reboot computer ---###

$ServerName = Read-Host "Restart - Enter the ServerName: "

if($ServerName.length -eq 0)
{ Write-Host "No Server restarted"
  Break }
else
{ $RebootSystem = get-wmiobject -Class "Win32_OperatingSystem" -ComputerName $ServerName
  $RebootSystem | Select-Object SerialNumber, Manufacturer, Name, CSname
  $RebootSystem.Reboot()
  Write-Host "ServeName -> ", $ServerName, " <- Its been restarted" }

##--- Shutdown computer ---##

$ServerName = Read-Host "Shutdown - Enter the ServerName: "

if($ServerName.length -eq 0)
{ Write-Host "No Server restarted"
  Break }
else
{ $RebootSystem = get-wmiobject -Class "Win32_OperatingSystem" -ComputerName $ServerName
  $RebootSystem | Select-Object SerialNumber, Manufacturer, Name, CSname
  $RebootSystem.Shutdown()
  Write-Host "ServeName -> ", $ServerName, " <- Shutdown" }

## Keep in mind, you can build a string variable containing a list of computer ##

## Example: $ServerName = "Server1","Server2","Laptop1","Desktop3"...

Caution trying to get FolderSize information w/Powershell...

Make sure to roughly test all Powershell script you may download from the Internet (even the ones I'm putting in my blog).  I just found a couple of sample that will help display a list folder size (which Windows Explorer won't provide).  Unfortunately the results displayed wasn't perfect.  I had to use Windows Explorer to verify size information by doing the right-click on the folder to compare the results.  Is this a bug? or just a mistake when creating complex cmdlet.

The problem is that, in most cases, the folders listed are fine.  I only caught this issue when listings folders that contains lots of subfolders. 

Here are some Powershell samples:

1. Powershell (PS) script code from the Internet: (building a function)

Function getFolderSize{
$items = Get-Childitem $args
foreach($item in $items){
if ($item -is [System.IO.DirectoryInfo]){
    Add-member -inputobject $item -membertype ScriptProperty -Name Length -Value{$a = `
    get-childitem $this.FullName -include *.* -recurse | measure-object -sum Length;
    If($a -eq $null){return 0;} else {return $a.sum}}
    write-output $item
    }
}
}

This code work but still doesn't give you 100% correct information(maybe about 80%).

2. Another PS script I retouched from another source: (building a function

Function DisplayFolderSize {
$folderTree=get-childitem $args;
[double] $fsize = 0;
[double] $fsz = 0;
[double] $TotalFSZ = 0;
Write-Host "";
Write-Host "Get Foldersize for $Args";
write-host "------------------------";
foreach ($folt in $folderTree) {
    if($folt.mode -match "d") {         
         $fsz=((get-childItem $folt.fullname -recurse | Measure-object length -sum).sum);
         $fsize="{0:N2}" -f $fsz;
         write-host ("$fsize `t `t `t `t $folt ");
         [string] $FolderRecords = $FolderRecords + $folt.name + "," + $fsize + "`r`n";
        $TotalFSZ=$TotalFSZ+$fsize;               
    }
  }
write-host "------------------------";
write-host "Total Foldersize";
write-host $TotalFSZ;
write-host "";
}

This code gave me better result but still not a 100% correct information (maybe 90%).

3. Now, here's the winner.  I created this PS script using the "Scripting.FileSystemObject" COM object.  This way I can create a collection of members for the folder I'm querying the information. (notice this is not a function)
The following lines you can execute line at a time or just create a PS script file or create a function.

###############################################
## objFolderSize.ps1                                              ##
## Author: Max Trinidad, 02/07/2008                    ##
###############################################

$FolderName = Read-Host -Prompt "Enter Foldername: "
$FileSystem = new-object -com "Scripting.FileSystemObject";
$getFolderAttr = $FileSystem.GetFolder($FolderName);
$getSubFolderAttr = $getFolderAttr.SubFolders
$getSubFolderAttr | select name, size | ft -auto

## end of script##This code gave me a 100% correct information.
 

I did gather the results of all three PS scripts and copy/paste them into Excel.  Then I verify the folder size result against Windows Explorer making the #3 PS Script the winner.
Did you notice how many lines of code I use in PS script #3 ?   :)
Happy coding!!
2月2日

Today's So.Fla CodeCamp08 was a success!!!

Check the pictures:
   
Windows Live Spaces
1月31日

My CodeCamp2008 Topic - Building a Windows App in Powershell

This coming Saturday, February 2nd 2008, I will be giving one presentation in both Spanish and English on "Building a Windows Application in Powershell".  So, here's all the presentation material including some bonus code.  Enjoy!!
Here's the link to download the file:
 
<download me: SoFla_CodeCamp2008.zip >
 
1月28日

Come to our So.Florida CodeCamp 2008 on Saturday, Feb. 2th (all day event)...

Welcome to the FlaDotNet User Groups!


South Florida Code Camp 2008
Don't miss this FREE Developer Event on Saturday - February 2, 2008 at Devry University in Miramar.
For more information visit:
http://codecamp08.fladotnet.com
REGISTER NOW BEFORE IT FILLS UP!
http://www.clicktoattend.com/?id=122048


I will be one of the speakers presenting in this event.  My topic: "Building a Windows Application in Powershell" and it will be given in both English and Spanish.  See you all there!

1月25日

Combining a COM object to a simple solution to get SQL Server Information

This is a simple solution that will generate a *.txt report with some SQL Server information. The “Scripting.FileSystem” COM Object is use to verify that the file is deleted before is created by the Powershell “Out-File” CMDlet. We’ll use the COM object methods *.FileExist() and *.DeleteFile().

After loading the SMO assembly you gather the database information, then using the “foreach” CMDlet get the information for each servername from the string array $SQLLocalList.

Requirements:

1. You need to have installed both SQL Server 2005 SMO and SQL Server 2008 on your computer to be able to manage all SQL Servers (2000/2005/2008) on the network.

2. This script will work with both Powershell version 1.0 and CTP version 2.0.

3. Have the proper permission to access your SQL Servers and Powershell script.

 

###################################################

## SQLLocalInfo.ps1

## Author: Max Trinidad, 01/21/2008

###################################################

#--Set execution policy to allow to run this script

Set-executionpolicy -executionpolicy remotesigned

 

#--Load the SQL Server SMO assembly

[System.Reflection.Assembly]::LoadWithPartialName("Microsoft.SqlServer.Smo")

 

#--Build the array with the SQL Server names

$SQLLocallist = "SQLSvr2k","SQLSvr2k5”, “SQLSql2k8”;

 

#--Build the string holding the location of the output file

$Filename = "C:\Developer\Max Events 2008\SQLServerInfo.txt";

#--Build the COM object holding the collection of methods we can use

$FileSystem = new-object -com "Scripting.FileSystemObject";

 

#--If the file already exist then delete

if ($FileSystem.FileExists($FileName)) {  

  $FileSystem.DeleteFile($FileName) ; }

 

#--Basically for each server name in the Array then get the information and append to the output file

foreach ($srvr in $SQLLocallist)

{

  #--Build the variable with the SQL Server collection for each server and then create the outfile

  $MySQL = new-object('Microsoft.SqlServer.Management.Smo.Server') $Srvr

  Out-File -filepath $Filename -inputobject ($MySQL.Information | Select Parent, Product, Edition, VersionString) -append

  Out-File -filepath $Filename -inputobject ($MySQL.Databases | Select Name, Parent) –append

}

 

##--Display the outfile in Notepad

ii $FileName;

######## END OF SCRIPT CODE #########

Sample Report Ouput clip_image002

Use the “Get-member” in order to get more properties values to use in the “Select”.  Have fun!

1月17日

Building a Windows Application in Powershell (converting C#)

 

C# code

Powershell code

this.button1 = new System.Windows.Forms.Button();

$button1 = new –object System.Windows.Forms.Button;

New

New-object

This.

$

()

Not needed

;

;  can stay or removed

>, <, =, !=…

-gt, -lt, -eq, -ne… (look in the PS reference sheet)

True, false…

$true, $false

this.comboBox1.Items.AddRange(new object[] {"AP Export","Sales Import",

"GL Export","Vendor Import"});

$CbValues1 = "AP Export","Sales Import";

$comboBox1.Items.AddRange($cbValues1);

this.comboBox1.Location = new System.Drawing.Point(131, 83);

$comboBox1.Location = new-object System.Drawing.Point  @(131, 83);

..Point(131,83);  or ..Size(121,21);

..Point  @(131,83);  or ..Size @(121,21);

this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);

$Form1.AutoScaleDimensions = new-object System.Drawing.SizeF @([double] 6, [double] 13);

..SizeF(6F,13F);

..SizeF @([double] 6, [double] 13);

this.SuspendLayout();

Not needed

this.ResumeLayout(false);

Not needed

this.PerformLayout();

Not needed

 

 

 

Order of building the Powershell Windows Script:

1.       Set-ExecutionPolicy –executionpolicy remotesigned     (might be needed)

2.       Load all General Assemblies Components (GAC’s).

3.       Initialize all Variables and Controls objects

4.       Create all NonFunction/Functions and/or Events ($button.Add_Click, $Combo1.Add_Selec…)

5.       Put together all the Controls objects

6.        Last lines should Activate the form

1月8日

Powershell Quick Tips: SQL Server 2008 differences vs SQL Server 2005 when loading SMO GAC's in PSscripts

First, I found SQL Server 2008 SMO is downward compatible with SQL Server 2005 and limited with SQL 2000.  So, when you build your Powershell SMO scripts, you need to load 2 SMO GAC's in order for your script work.

Normally, after installing your "Feature Pack for SQL Server 2005" you will have access to SQL SMO Assemblies that will help you manage you SQL Server using Powershell.  The following samples will show you how to basically create a collection of data from the database:

1. Create a collection from an SQL Server 2005, you need to load one GAC and then create the variable that will hold the data:

PS> [System.Reflection.Assembly]::LoadWithPartialName("Microsoft.SqlServer.Smo")

PS> $MySQL = new-object('Microsoft.SqlServer.Management.Smo.Server') "SQLServer2k5"

PS> $MySQL.Information   #access the SQL Server information collection

PS> $MySQL.Databases  #access the SQL Server database collection

By the way, the SMO GAC's are part of the SQL Server 2008 installation so you will be able to use it with Powershell.  So. if you install SQL Server 2008 in the same Desktop where SQL Server 2005 was installed, then you will be able to manage with SMO all your 2005, 2008 and partially 2000 SQL engines.

 

Powershell Quick Tips: Valid Folder name string when working with SMO .AddDevices()

When building a Powershell script with SMO to Backup/Restore databases I found an error when using folder names in the string.  The following foldername sample will show you what's correct (or not) when using the .AddDevice() method in either SQL Backup and Restore:

$Device1 = "C:\Temp\Sample.bak"

...AddDevice($Device1)   #procedure will run

$Device2 = "C:\Program Files\Microsoft SQL Server\MSSQL\Backup\Nw.bak"

...AddDevice($Device2)  #procedure will fail

$Device3 = "C:\'Program Files'\'Microsoft SQL Server'\MSSQL\Backup\Nw.bak"

...AddDevice($Device3)   #procedure will run

If the folder name includes spaces then your SMO procedure will not work.  You need to use the single quote in both beginning and end of the foldername string.  Keep in mind, You don't need to use the single quote in the string if you're using the DOS Copy, CD, and MD commands.  Always test you scripts!

12月4日

New Windows PowerShell 2.0 CTP (November 2008)

Download details: Windows PowerShell 2.0 CTP

  • Selected New Features in Windows PowerShell 2.0 CTP
    (Please refer to Release Notes and Help topics for more details)
  • PowerShell Remoting
  • Graphical PowerShell
  • ScriptCmdlets
  • Restricted Runspaces
  • RunspacePools
  • Background Jobs
  • Data Language
  • Script Internationalization
  • Script Debugging
  • 24 New Cmdlets
  • Parser Tokenizer API
  • New PowerShell Hosting APIs
  • Metadata APIs for Command and Parameters
  • 10月23日

    Converting C# code to Powershell syntax by sample

    For the last few months I've been learning how-to create Powershell scripts to help manage our servers and build
    solutions for our users. First, I will show a sample C# code that will display a more complex messagebox in action.
    You can build a windows form with a button control and then add the C# code to test that this code works.

    Here's the C# code:

    Here's the converted C# code to Powershell syntax:

    Make sure to add this Powershell code to a *.ps1 file to run it. Or, just copy/paste code to the shell to run interactive.
    Now, you might asked the question, Can I build and convert a simple Windows form(s) solution to a Powershell syntax?
    The answer is YES.  Happy Powershell coding!

    7月31日

    Using Powershell "Start-Transcript/Stop-Transcript" commands

    These two Powershell commands can help you capture and save what you have type during your Powershell session:

    Start-Transcript and Stop-Transcript.

     

    Start Powershell

    PS>

     

    At the prompt, type:

    PS> Start-Transcript c:\temp\CaptureDemo.txt

    {this command need a filename to store you sesion data}

     

    Now, type any command:

    PS> Get-Service

     

    And:

    PS> Get-Service | Get-member

     

    Then, stop the transcript:

    PS> Stop-Transcript

     

    To view the result change directory to C:\Temp then use the Powershll command "ii":

    PS> CD C:\Temp

    PS> ii C:\Temp\capturedemo.txt

     

    This command "ii" will open notepad and display the content of the file.

    5月10日

    Problem executing PowerShell script after download

    In brief, you finished downloading a PowerShell script from the Internet, you open PowerShell as Administrator, and have use the "SET-ExecutionPolicy RemoteSigned".  Now, everything should work... Right!!  But, "NO" it would work.  Somehow, on Vista, still knows the script was download from somewhere else and is a block status.  You need to right-click on the script and select "Properties".  Then, look for the "UnBlock" button.  Only, then you will be able to execute the script.  Look at the sample pic.
     

    PowerShell presentation went well.

    With only 15 people attend and with very little problems my presentaiton went well.  The book was given away and everyone got a  bootlegged  with my presentation.  I will start posting more about PowerShell in the next few days.
    4月27日

    PowerShell first cmdlets to remember...

     To start using PowerShell you most remember the following cmdlets:

    1.       Get-Command

    2.       Get-Help

    3.       Get-PSDrive

    4.       Get-Member

    5.       Get-Alias

    GetGet-Variable

    GetThese are very power commands and can get you going pretty fast.  When using the Get-Help will give you a list of what you can do with this command.  Then, with the Get-Alias you will see a list cmdlets shortcuts and you will recognized some like DIR, CD, ECHO, and DEL to name a few.

    Also,  you  can use the powerful  TAB key which will help you search and/or complete your cmdlet.  Go ahead and try it:

    PS> Get-P ->press the TAB key, then keep pressing the TAB key until you find the command to execute.

    PS> Get-Process

    And, wildcards are allow when executing the cmdlets, such as:

    PS> dir a*

    PS>dir  [a-e]* {WIldcard is needed}

    PS> dir *a*

    Of course, there’s a lot more you can do with wildcards.  So, I recommend you to execute;

    PS> Get-Help Get-Content   {because DIR is really an alias of Get-Content}

    I hope this will get you all started.

    4月3日

    Set and Ready to speak...

    My First Presentation: "Scripting Tools and Intro to PowerShell", May 8th, Miramar Florida.

    Now, to the Florida .NET User Group many thanks to ComputerWays "Dave Noderer" and Devry University "Ed Hill" for making my first presentation a reality. My presentation is scheduled for Tuesday, May 8th, 6:30pm. This event is now official, check it out at: www.fladotnet.net

    About the Topic: "Scripting Tools and Intro to PowerShell". I will be showing some free scripting tools available for either people with or without any coding experience. Then, I will give an introduction to PowerShell but enough to open some interest. Both command line and scripting sample will be shown. Then, at the end, I will be giving away a book "Windows PowerShell in Action" by Bruce Payette. Also, every attendee will receive a CD with useful resource material.

    By the way, the give away book is provided by my sponsor Data-Corp "Hugo Perez".

    This is only the beginning...

    DevConnections, Orlando, Florida. (March 2007)

    I just attented the DevConnections in Orlando Florida and it was a great conference. Here, I met many wonderful speakers from both local and out of state. All the sessions provided valuable information that sometimes its hard to retain. A special thank to both Microsoft Developer Evangelist "Joe Healy" and MSDN Developer Community Champion "Russ Fustino" for giving me the motivation to become a technical speaker for our Florida .NET community. Please, if you see these names in any of your local MSDN Event, go and attend their sessions... is full of information and suprises. Also, I don't forget another great speaker SteelBlue Solutions "Miguel Castro"... I hope to see you back in South Florida.

    Some additional links:
    http://www.devfish.net/
    http://www.russtoolshed.net/
    http://www.steelbluesolutions.com/