Comunidade do SQL ServerSe você for novo na Comunidade, visite a página de introdução. Você também pode:
Blogs do SQL Server criados por funcionários da Microsoft .gif)
SQL Server PerformanceBest Practices, Tips, Benchmarks, Troubleshooting and Monitoring - SQL Server, ADO.NET, Analysis Services, and SSIS
Postagens recentes dos blogs do SQL Server .gif)
Experimenting with PowerShellPowershell is a command line interface for Windows that offers a very powerful and flexible model. It is now a feature included with Windows 7 and Windows Server 2008 R2, not an optional download as before. In this post, I show some sample commands that can help you understand some of the basic features and a few more complex ones. If you never played with it before, try running some commands in a PowerShell prompt.
| Shows a list of commands: |
Get-Command |
| Shows the help overview: |
Get-Help |
| Show the help for “Dir”: |
Get-Help Dir |
Let's use the Dir command now (actually an alias for Get-ChildItem) and a number of ways to transform the output using pipeline functions:
| Shows Directory: |
Dir |
| Shows Directory in list format (two ways): |
Dir | Format-List Dir | FL |
| Shows Directory sorted by file length: |
Dir | Sort Length |
| Shows Directory sorted by file length in descending order: |
Dir | Sort Length –Descending |
| Shows all the methods and properties for the objects resulting from Dir (files and folders): |
Dir | Get-Member |
| Shows a selected list of properties instead of the default list: |
Dir | Select Directory, Name, Extension, Length |
| Shows directory in HTML format (not much use going to the console like this, though): |
Dir | ConvertTo-Html |
| Output the Directory listing to a file: |
Dir | Out-File psfilelist.txt |
| All together now: Shows selected list of properties, sorted, in HTML, going to a file. You need to open the file yourself: |
Dir | Select Directory, Name, Extension, Length | Sort Length -Descending | ConvertTo-Html | Out-File psfilelist.htm |
Now exploring other “drives” in PowerShell, including the certificate store and the registry.
| Get list of PowerShell “drives”: |
Get-PSDrive |
| Shows environment variables: |
Dir ENV:\ |
| Shows the certiticate store: |
Dir CERT:\ |
| Shows root certificates for the machine: |
Dir CERT:\LocalMachine\Root | Select FriendlyName, NotAfter |
| Shows “HK Local Machine” portion of the registry |
Dir HKLM: |
| Shows specified part of the registry: |
Dir HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion |
Another easy way to get interesting data is with Get-Process.
| List running processes: |
Get-Process |
| Shows all the methods and properties for the process objects: |
Get-Process | Get-Member |
| Shows selected list of properties of running processes, formatted as table: |
Get-Process | Select Id, Name, Product, CPU, WorkingSet | Format-Table –autosize |
Combining PowerShell with WMI is also very interesting. You can leverage any WMI provider on the box using Get-WmiObject. You can get a list of WMI Classes from http://msdn.microsoft.com/en-us/library/aa394554(VS.85).aspx
| Shows disk partitions: |
Get-WmiObject Win32_DiskPartition | Select Name, Size, BootPartition |
| Shows logical disks: |
Get-WmiObject Win32_LogicalDisk | Select DeviceID, DriveType, Size, FreeSpace |
| Shows mapped drives (with NET USE command): |
Get-WmiObject Win32_MappedLogicalDisk | Select Name, ProviderName, FileSystem, Size, FreeSpace | Format-Table |
PowerShell also lets you call the .NET Framework, which is a huge library. You need to use a syntax where the full class name (library.class) is mentioned in [], followed by a :: and the method name.
You can find a reference for it at http://msdn.microsoft.com/en-us/library/ms229335.aspx
| Shows network interfaces: |
[System.Net.NetworkInformation.NetworkInterface]::GetAllNetworkInterfaces() | Select Name, Speed, OperationalStatus |
| Shows identity of the current logged user: |
[System.Security.Principal.WindowsIdentity]::GetCurrent() | Select Name, AuthenticationType, IsAuthenticated, IsSystem |
| Shows drive information: |
[System.IO.DriveInfo]::GetDrives() | Select Name, DriveType, IsReady, TotalSize, TotalFreeSpace, RootDirectory | Format-Table -autosize |
It’s also interesting to iterate through the list of resulting objects, to perform additional actions. You use the foreach construct, which allows you to run something for each item. The item is referred to as $_.
| Change to the user home folder, which is obtained from the environment variables: |
Dir Env:\HOMEPATH | ForEach { CD $_.Value } |
| Show all text files enumerated by the Dir command: |
Dir *.TXT | ForEach { Type $_ } |
| Show root directory for all drives enumerated by GetDrives: |
[System.IO.DriveInfo]::GetDrives() | foreach { Dir $_ } |
A similar syntax is used for Where (actually an alias for Where-Object), which can be used to filter objects in the pipeline.
| Show selected properties of processes using more than 10MB of memory, in descending order, formatted as table: |
Get-Process | Select Id, Name, Product, CPU, WorkingSet | Where { $_.WorkingSet -gt 10*1024*1024} | Sort WorkingSet -Descending | Format-Table –autosize |
| Shows all services that are stopped: |
Get-Service | Where { $_.Status -eq "Stopped" } |
Now let's focus on the DFS-Namespaces service, which is something I’m working on (these will only work if the box is a Windows Server file server with the DFS-N role service installed):
| Shows all 2000 mode domain namespaces on the current computer, using the registry: |
Dir HKLM:\Software\Microsoft\DFS\Roots\Domain |
| Shows all 2008 mode domain namespaces on the current computer, using the registry: |
Dir HKLM:\Software\Microsoft\DFS\Roots\DomainV2 |
| Shows all standalone namespaces on the current computer, using the registry: |
Dir HKLM:\Software\Microsoft\DFS\Roots\Standalone |
| Shows all namespaces of all types on the current computer, using the registry: |
Dir HKLM:\Software\Microsoft\DFS\Roots –Recurse | Select PSChildName, ValueCount, Property |
| Shows properties of the DFS-N service in the registry: |
Dir HKLM:\System\CurrentControlSet\Services\Dfs |
| Starts the DFS-N service (two ways): |
Get-Service DFS | Start-Service Get-Service DFS | ForEach { $_.Start } |
| Shows DFS Targets on the current computer, using WMI: |
Get-WmiObject Win32_DFSTarget |
| Shows selected properties of DFS nodes on the current computer, including it's a root and its state, using WMI: |
Get-WmiObject Win32_DFSNode | Name, Root, State | Format-Table –autosize |
I hope that has helped you see how interesting PowerShell can be. Here are a few links for additional information and tutorials:
Quote of the Day: On Keeping Ease in its PlaceI admire people who have overcome difficulties to achieve. I find so few people today that can stand any adversity - people whine and complain at the slightest inconvenience. In the past character seemed to matter more, and Helen Keller was one such person of character. She said: "Character cannot be developed in ease and quiet. Only through experiences of trial and suffering can the soul be strengthened, vision cleared, ambition inspired and success achieved." - Helen Keller
Use WPC Connect today to connect with your peers and Microsoft at Worldwide Partner ConferenceEarlier today in my, “Connect with your peers in the Yellow Lounge at Worldwide Partner Conference,” post, I mentioned how one of the greatest values Partners tell us they get from conferences such as #wpc09 is the peer to peer and Partner to Microsoft connections they make while at the conference. To help foster this and make it even easier for you to make these invaluable connections, we have WPC Connect available to all attendees, and here is a quick overview (click images for full size) on how you can make connections right now using WPC Connect: - Log on to Digital WPC and click on “Connect” (you will be prompted to sign in with your Windows Live ID if you haven’t yet).
|  | - Click on WPC Connect & then Click on My Opt-In Status
| | - Select Yes & Click on Save
| | Now, let’s update your profile so that others can find you more effectively and so that people know more about you when you request a meeting with them: - Click on WPC Connect
- Click on My Profile
|  | - Review and Update your profile information to enable others to connect with you
- Click Update
| | That’s it! You are read to start scheduling sessions! Don’t hesitate any longer. Get out to the Digital WPC site today and opt in to WPC Connect so that you can start setting up your connections for next week’s #WPC09! I look forward to seeing you there. Also, be sure to catch up on some of the pre-WPC networking taking place already by joining WPC09 on Facebook or following #WPC09 on Twitter or on LinkedIn. Thank you and have a wonderful day, Eric Ligman – Follow me on  Global Partner Experience Lead Microsoft Worldwide Partner Group This posting is provided "AS IS" with no warranties, and confers no rights
digg_skin = 'compact';
digg_window = 'new';
Bookmark on: MSDN , TechNet, and Expression
Technorati Tags: Microsoft, Yellow Lounge, SBSC, Small Business Specialist, Partners, MSPP, SMB, Eric Ligman, networking, social networking, WPC09, Worldwide Partner Conference, New Orleans, WPC Connect del.icio.us Tags: Microsoft, Yellow Lounge, SBSC, Small Business Specialist, Partners, MSPP, SMB, Eric Ligman, networking, social networking, WPC09, Worldwide Partner Conference, New Orleans, WPC Connect
| Conheça os MVPs do SQL Server .gif) Os Most Valuable Professionals (MVPs) da Microsoft oferecem sua experiência prática de anos e gostam de ajudar outras pessoas.
Soluções de MVPs recentes para o SQL Server .gif) |
DestinosComunidades relacionadas- SQL Server Magazine
Dos criadores da Windows e .NET Magazine, a SQL Server Magazine oferece aos administradores e desenvolvedores de bancos de dados as informações e técnicas necessárias à implantação do SQL Server como uma plataforma de desenvolvimento. - Mergulhe no SQL Server
Localize links de recursos, scripts de conferência, próximos eventos e dicas e truques sobre o SQL Server no site SQLskills
| Outras comunidades Microsoft |
Mais recursos- Conhecer as práticas recomendadas do SQL Server
Obtenha diretrizes do mundo real, dicas de especialistas e orientação sólida para levar a sua implementação do SQL Server para o próximo nível. - Avaliação de habilidades: você está pronto para o SQL Server 2005?
Obtenha avaliações gratuitas de habilidades e acesso a nove cursos Microsoft e-Learning para administradores de banco de dados, desenvolvedores de banco de dados e desenvolvedores de business intelligence para verificar se você está pronto para o SQL Server 2005. - SQL Server: atualize as suas habilidades para o 2005
Junte-se aos especialistas da Microsoft no assunto para que eles mostrem a você todos os principais recursos e aprimoramentos do SQL Server 2005 e demonstrem como é possível trazer essas vantagens para a sua organização. Registre-se agora! - Webcasts e bate-papos
Mantenha as suas habilidades e seu conhecimento em dia com webcasts e chats interativos gratuitos. Assista a apresentações ao vivo usando o Microsoft Office Live Meeting ou pesquise transcrições nos arquivos.
Início da página
| |