Searching columns by type

16 06 2009

Today I went to review the SQL Server 2008 enhancements on XML support. To test the queries on AdventureWorks, the first thing I needed to know was: “Where are the XML data columns?”

I don’t actually have the graphic on the database model to search for and wasn’t on the mood to create the database diagram to search visually for the XML columns.

Then, I’ve got the idea of searching on the catalog for that. It should be simple to do (and it was!) but worth the post, as many people may have the need to use the same thing, not only on AdventureWorks, but on large (I mean many tables) databases:

Here is the script:

SELECT t.name, c.name, ty.name
  FROM sys.tables t INNER JOIN sys.columnsON
          (t.object_id = c.object_id)
      INNER JOIN sys.systypes ty ON
          (c.system_type_id = ty.xtype)
WHERE ty.name = ‘xml’

With this script, you can create a procedure that returns the table name and the column name that uses a type that’s passed by a parameter. Or even create a PowerShell function to achieve this. Let’s see the latter:

param([string] $typeName, [string] $server, [string] $database)
$sqlConnection = New-Object System.Data.SqlClient.SqlConnection "server=$server;database=$database;Integrated Security=sspi"
$sqlConnection.Open()
$sqlCommand = $sqlConnection.CreateCommand()
$sqlCommand.CommandText = "SELECT t.name [Table], c.name [Column]
                                                  FROM sys.tables t INNER JOIN sys.columns c
                                                          ON (t.object_id = c.object_id) 
                                                                           INNER JOIN sys.systypes ty 
                                                          ON (c.system_type_id = ty.xtype)
                                               WHERE ty.name = ‘$typename ‘"
$sqlReader = $sqlCommand.ExecuteReader()
$dataTable = New-Object System.Data.DataTable
$dataTable.Load($sqlReader);
$sqlConnection.Close()
Write-Output $dataTable

Interesting, huh?





Powershell.com Videos

16 04 2009

PowerShell.com is promoting some videos ‘bout Windows PowerShell there are very interesting to see. Is a list of five videos (the fifth is in being built still) that shows the use of PowerShell into some environments that Microsoft had integrated with. Here’s the list:

  1. Getting To Know PowerShell;
  2. PowerShell for Active Directory;
  3. PowerShell for Exchange Server 2007;
  4. PowerShell for SQL Server 2008;
  5. PowerShell for Windows Servers & Clients.

Worth to see! [here to go]





Dir by file age

28 01 2009

This is a simple tip. Sometimes is needed to select files in a folder by it’s age. Then (as far as I could see) the dir command can’t do this by a simple command line. I’ve written then a script that can do this by filtering a dir result:


function Get-TodayFiles{
    $day = New-Object System.TimeSpan(1,0,0,0,0)
    $today = Get-Date
    $result = New-Object System.Collections.ArrayList
	for($i = 0; $i -lt $files.Length; $i++){
        if ($today.Subtract($files[$i].LastWriteTime).CompareTo($day) -eq -1) {
            $result.Add($files[$i].FullName)
        }
    }
    return $result
}

This is a very programmer solution. PowerShell.com has made a new solution, easier than mine.

 Filter Select-FileAge {
       param($days)
       # is it a folder? Then omit:
       If ($_.PSisContainer) {
              # do not return folders effectively filtering them out
       } ElseIf ($_.LastWriteTime -lt (Get-Date).AddDays($days * -1)) {
              $_
       }
} 

This new one is used as a filter to the dir command, and is used in this way:

dir $env:windir *.log | Select-FileAge 20





Emails e Powershell

14 01 2009

Para algumas tarefas de manutenção, é chato estar indo nas máquinas e verificando se as tarefas estão sendo realmente feitas. Imagine por exemplo se você tem alguns servidores diferentes pra ficar monitorando algumas vezes no mês ou na semana. É incômodo ir fazendo Remote Desktop na máquina 1, ver o que tem de ser visto, deslogar, e assim por diante.

Um workaround para isso pode ser o envio de e-mails qnd a tarefa for concluída, com algum feedback se a tarefa foi feita com sucesso ou não.

Com o código abaixo, podemos enviar e-mails a partir de um script PowerShell. Este código é um ajuste com relação ao script postado em [1], adicionando as credenciais, e dando forma de função.

function Send-Mail{
	param([string]$to, [string]$subject, [string]$body)
	$smtp = New-Object System.Net.Mail.SmtpClient("your server here");
	$mailMessage = New-Object System.Net.Mail.MailMessage;
	$credential = New-Object System.Net.NetworkCredential("sender username", "sender password", "sender domain");
	$mailMessage.From = "sender mail";
	$mailMessage.To.Add($to);
	$mailMessage.Subject = $subject;
	$mailMessage.Body = $body;
	$smtp.Credentials = $credential;
	$smtp.Send($mailMessage);
}

 

[1] http://www.searchmarked.com/windows/how-to-send-an-email-using-a-windows-powershell-script.php

[2] http://www.brokenhaze.com/article.php?story=20080228214713878

[3] Windows Powershell





Meu shell aprendeu a falar!/ My shell has just learned how to talk!

14 11 2008

Bem o título é meio exagerado, mas é bem a surpresa de quem vê o resultado do que foi feito pela equipe desenvolvedora do Powershell Comunity Extensions (PSCX). O PSCX é um conjunto de scripts que são adicionados ao ambiente de execução do Powershell, e possui várias coisas interessantes/úteis.

Uma das coisas interessantes e que deixa todos que vêem de queixo no chão, é o comando Out-Speech. E é exatamente isso que você está pensando. Dada uma string passada como parâmetro, o comando usa a Speech API do .NET Framework e fala (isso mesmo fala) o texto. A sintaxe é bem simples:

Out-Speech "texto a ser lido"

É possível usar o comando em combinação com o Get-Content e fazê-lo ler um arquivo texto completo.

Um pequeno problema é que a fonética é inglesa, então não fica legal mandar textos em português ou em outras linguas serem pronunciados.

===================================================

Well, the title is a bit exaggerated, but is exactly the surprise of someone who has seen the result of what was done by the Powershell Comunity Extensions (PSCX) developer team. The PSCX is a set of scripts that are added to the Powershell’s execution environment and it has many interesting/useful things.

One of the interesting things that let everyone astonished is the command Out-Speech. And that’s exactly what you are thinking! Given a string as a parameter, the command uses the Speech API from .NET Framework e talks (yes, that’s really what i’d written, talks) the text. The sintax is very simple:

Out-Speech "text to be read"

It’s possible then to use the command ‘in combo’ with the Get-Content and make it read an whole textfile.

One little problem is the english phonetic. As so, it’s not good to make it read texts in other languages.

[1] PowerShell Community Extensions





Twitter by Powershell

2 11 2008

O Twitter é uma rede social de microblogs. É bem interessante, mas tem um formato que pessoalmente só passei a usar por conta das ferramentas para a interação, pois toda a dinâmica do Twitter se passa dentro do site, mas suas mensagens são curtas, o que leva a passar pouco tempo para enviar mensagens, mas muito tempo pra ficar observando as mensagens dos outros chegarem. É um site que se teria de ficar aberto o dia inteiro pra ver o que os seus amigos (followers) estão postando.

Resolvi esse problema usando TwitterFox, um plugin pro FireFox, que praticamente reduz o Twitter a um chat, minimizado no canto inferior direito do navegador. Bem mais prático, pois sempre que chega uma mensagem, o plugin dá um aviso suave, e também é possível através dele enviar mensagens de forma bem prática e rápida.

Isso me fez investigar sobre o acesso ao Twitter via API, e vi que existem inclusive “traduzida” para várias linguagems de programação. Quando vi que entre essas havia uma tradução para .NET, bateu logo a vontade de tentar usá-la via Powershell. A API se chama Yedda e o código do script ficou bem simples:

#########################################################################################
# Script: Send-TwitterMsg.ps1								#
# Pourpose: Send a twitter message using powershell					#
# Author: Fábio Chicout (fabio.cesar.medeiros@gmail.com)				#
# Usage: Send-TwitterMsg -login #your_login# -password #your_password# -text #your_text##
#########################################################################################

param(
	[string] $login,
	[string] $password,
	[string] $text
)

[System.Reflection.Assembly]::LoadFile("C:\scripts\Yedda.Twitter.dll");
$tw = New-Object Yedda.Twitter;
$tw.UpdateAsXML($login, $password, $text);

É importante que a dll da api esteja especificada com o caminho completo no parâmetro da função LoadFile.

Fiquei imaginando as possibilidades de usar isso na automatização de coisas numa rede… após terminar uma determinada tarefa, enviar uma mensagem, por exemplo.





PowerShell e Arquivos INI/PowerShell and INI Files

16 10 2008

Mais uma dica. Com o .NET Framework há uma tendência de ir jogando configurações para arquivos XML ao contrário de arquivos INI, como antigamente muito se usou. Mas como sempre é possível ter a necessidade de usar/configurar programas antigos, em [1] são mostrados 3 scripts que juntos ajudam na tarefa de manipular arquivos INI.

O primeiro (Invoke-WindowsApi.ps1) é um workaround para se usar a API Windows no PowerShell. Não há no .NET Framework uma classe que lide com arquivos INI diretamente, então nos dois scripts seguintes (Get-PrivateProfileString.ps1 e Set-PrivateProfileString.ps1) é possível usar passando somente os parâmetros necessários.

Segue o código dos scripts (Thanks Lee!):

=============================================

One more tip. With .NET Framework there is a tendency to throw application settings for XML files as opposed to INI files, as much has been used previously. But as you can always have the need to use/configure older programs, in [1] are shown 3 scripts that together help in the task of manipulating INI.

The first (Invoke-WindowsApi.ps1) is a workaround to use the Windows API into PowerShell. There is no .NET Framework a class that deals with INI files directly, then in the following two scripts (Get-PrivateProfileString.ps1 and Set-PrivateProfileString.ps1) you can use only those passing the required parameters.

Below goes the code of scripts (Thanks Lee!):

 

==================================

 

[1] Managing INI Files with PowerShell





Bateria restante – Powershell

30 06 2008

Às vezes, quando reinicio o note, some da barra de tarefas o ícone com a carga da bateria. Já tentei dizer pro vista que é pra ele sempre ser mostrado, mas nem sempre esse SO obedece a gente. Sendo assim, busquei uma forma de conseguir essa informação de outro jeito, e como estou mexendo um bocadinho em PowerShell, aqui vai a dica.

O segredo é usar WMI (Windows Management Interface). Segue o código:

$info = get-WmiObject win32_battery -computer
"Remaing Battery: "+ $info.EstimatedChargeRemaining

Agora, pra ficar mais fácil, crie um arquivo de nome Get-BatteryLevel.ps1, ponha as linhas abaixo e salve:

$info = get-WmiObject win32_battery -computer $Args[0]
"Remaing Battery: "+ $info.EstimatedChargeRemaining

Com isso é possível saber o nível da bateria chamando no PowerShell:

& Get-BatteryLevel.ps1 <nome_do_computador>

o que já é ligeiramente mais simples.