Affichage des articles dont le libellé est Powershell. Afficher tous les articles
Affichage des articles dont le libellé est Powershell. Afficher tous les articles

mardi 2 juin 2015

Control servo motor with Powershell GUI




Cet article à pour but d'expliquer comment réaliser un GUI via Powershell dans le but de passer des commandes à L'arduino.

Pour réaliser le GUI je me sers du programme Powershell Studio de Sapien ( https://www.sapien.com/software/powershell_studio ).

Ce software permet de réaliser facilement une interface graphique en faisant du drag and drop d’élément.
La code derrière est entièrement en Powershell. La force de ce logiciel c'est qu'une fois le code testé on peut exporter en .exe.

Ce programme devient alors exécutable avec comme seul prérequis d'avoir Powershell d'installé.

Voici à quoi ressemble l'interface :

Et la démo en vidéo :





Au niveau des branchement, 
- le servo est  branché sur l'entée 2.
- Une LED s'allume lorsque le servo tourne, elle est branché sur la pin 8

Voici pour le code de l'Arduino :
#include 
Servo monServo;
int led = 8;

void setup() { 
  pinMode(led, OUTPUT); // Set pin 13 as digital out
  // Start up serial connection
  Serial.begin(9600); // baud rate
  Serial.flush();
   
  gostop();
}
void gostop()
{
  monServo.detach();
}

void loop() {
  // put your main code here, to run repeatedly:
  String input = "";
     
    // Read any serial input
    while (Serial.available() > 0)
    {
        input += (char) Serial.read(); // Read in one char at a time
        delay(5); // Delay for 5 ms so the next char has time to be received
    }
     
    if (input == "left")
    {
        digitalWrite(led, HIGH); // on
        Serial.println("on");
        monServo.attach(2);
        monServo.write(180);
        delay(50);
        gostop();
        digitalWrite(led, LOW); // off
    }
    else if (input == "right")
    {
        digitalWrite(led, HIGH); // on
        Serial.println("on");
        monServo.attach(2);
        monServo.write(-180);
        delay(50);
        gostop();
        digitalWrite(led, LOW); // off
    }
      else if (input == "fullright")
    {
        digitalWrite(led, HIGH); // on
        Serial.println("on");
        monServo.attach(2);
        monServo.write(-180);
        digitalWrite(led, LOW); // off
    }
      else if (input == "fullleft")
    {
        digitalWrite(led, HIGH); // on
        Serial.println("on");
        monServo.attach(2);
        monServo.write(180);
        digitalWrite(led, LOW); // off
    }
      else if (input == "stop")
    {
        digitalWrite(led, HIGH); // on
        gostop();
        digitalWrite(led, LOW); // off
    }
}
Et voici la partie de Powershell Studio :

function OnApplicationLoad {
 return $true #return true for success or false for failure
}


function OnApplicationExit {
 $script:ExitCode = 0 #Set the exit code for the Packager
}

$form1_Load={
 #TODO: Initialize Form Controls here
 $port= new-Object System.IO.Ports.SerialPort COM3,9600,None,8,one
}

$buttonLEFT_Click={
 #TODO: Place custom script here
 
 $port.open()
 $port.Write("left")
 $port.close()
}

$buttonRIGHT_Click={
 #TODO: Place custom script here
 $port.open()
 $port.Write("right")
 $port.close()
}

$buttonFULLLEFT_Click={
 #TODO: Place custom script here
 $port.open()
 $port.Write("fullright")
 $port.close()
}

$buttonSTOP_Click={
 #TODO: Place custom script here
 $port.open()
 $port.Write("stop")
 $port.close()
}

$buttonFULLRIGHT_Click={
 #TODO: Place custom script here
 $port.open()
 $port.Write("fullright")
 $port.close()
}

mardi 18 juin 2013

SAPIEN : Powershell Studio 2012

Cette article à pour but de vous présenter un produit qui permet facilement ( et j'insiste sur le facilement ) de créer des interfaces GUI pour Powershell.
Il ya un an j'ai eu l'idée de faire une interface pour mes collègues qui sont allergiques au prompt.

J'avais découvert cette société qui propose un module ASP.NET qui permet d’interagir avec Powershell. ( http://www.powershellserver.com/ ).
Voici le genre d'interface WEB que l'on peut créer avec cette méthode :



Mon principale problème avec ce genre d'interface est qu'il faut de bonne connaissance en ASP pour que celle-ci soit modulable.

je me suis donc tourné vers une solution GUI Powershell Studio 2012.

Voici à quoi ressemble l'interface du soft :


Et le resultat : cette interface permet de lister les process en cours sur ma machine et de faire une recherche.

Mon but ici est de créer une interface générale permettant de :
- Pinguer une liste de machine
- Faire des query SQL
- Automatiser certaines actions dans l'AD.

Si vous êtes interessé par le produit et que vous souhaitez plus d'info ou que vous avez des questions, les commentaires sont là ;-)



dimanche 16 juin 2013

[WMI] Désactiver un service

IN : Fichier .txt qui contient un nom de machine par ligne ( path du fichier ici : c:\x.txt)

ACTION : Stop & Disable une service sur un server distant
Le credential sont donnés via la variable $cred
$cred = get-credential

RETURN : Retourne un hashtable avec le resultat.

In this script I want to disable the service "V-Locity" on the machine name list in c:\x.txt :
Cat c:\x.txt | % 
$disabled = (Get-WmiObject win32_service -ComputerName $_ -Credential $cred | ? { $_.name -match "V-locity"}).InvokeMethod("ChangeStartMode","Disabled")
$stop = (Get-WmiObject win32_service -ComputerName $_ -Credential $cred | ? { $_.name -match "V-locity"}).stopservice()
$object = new-object psobject -property @{
Name = $_
Disabled = $disabled
stop = $stop
}

$object
}

lundi 28 novembre 2011

Envoie d'un mail en HTML


Cette fonction permet d'envoyer par mail un hashtable :

Exemple d'utilisation :
get-process | send-htmlemail - from test@test.com -to toto@test.com -subject "Process List"


function Send-HTMLEmail { 
#Requires -Version 2.0 
[CmdletBinding()] 
 Param  
   ([Parameter(Mandatory=$True, 
               Position = 1, 
               ValueFromPipeline=$true, 
               ValueFromPipelineByPropertyName=$true)] 
    $InputObject, 
    [Parameter(Mandatory=$True, 
               Position = 2, 
               HelpMessage="Please enter the To address")]     
    [Array]$To,     
    [Parameter(Mandatory=$True, 
               Position = 3, 
               HelpMessage="Please enter the Subject")] 
    [String]$Subject,                   
    [String]$From = "user@domain.org",     
    # Pretty table CSS is available for download 
    # http://gallery.technet.microsoft.com/scriptcenter/c63025ef-645d-4efe-a4c3-bc126cb939e8 
    [String]$CSS = "C:\PwShell\Html_Report.css", 
    [String]$SmtpServer ="smtp.server.com" 
   )#End Param 
 
$HTMLDetails = @{ 
    Title = $Subject 
    Head = (get-content -Path $CSS) 
    } 
    $htmlinfo = $InputObject | ConvertTo-Html @HTMLDetails 
 
$Splat = @{ 
    To         =$To 
    Body       ="$htmlinfo" 
    Subject    =$Subject 
    SmtpServer =$SmtpServer 
    From       =$From 
    BodyAsHtml =$True 
    } 
 
    Send-MailMessage @Splat 
     
}
Fichier CSS :
  Ma première page avec du style
  

vendredi 25 novembre 2011

[AD] LIster les membres d'un groupe



La difficulté quant on veut lister les membres d'un groupe dans l'AD est de prendre en compte la recursivité.

Ce script liste les membres d'un groupe et decompose les groupes qu'il contient. Le resultat est mis en forme automatiquement dans Excell.

Prérequis : ADCmdlets & Powershell


#################################################################################################
#      Script to retrieve users of all groups in a group       #
#################################################################################################



#################### Return the group name ####################
function GetGroupName ([string] $CNToGroup) {
 $end = $CNToGroup.IndexOf(",")
 $start = $CNToGroup.IndexOf("=") + 1
 $CNToGroup = $CNToGroup.Substring($start,$($end - $start))
 return $CNToGroup
}

####################  Recursive function to retrieve users and groups ####################
function recurseMemberOf ([string] $CN) {
 
 $GroupName = GetGroupName($CN)
 $members = Get-QADGroupMember -Identity $CN | where {$_.AccountIsDisabled -notmatch 'null' -and ($_.Type -eq 'user' -or $_.Type -eq 'group' -or $_.Type -eq 'contact')}
 
 if ($members -ne $NULL) { 
  foreach ($member in $members) {
   if ($member.Type -eq "user") {
    $script:Row += 1
    $wSheet.Cells.Item($script:Row,1) = $GroupName
    $GroupType = (Get-QADGroup -Identity $CN).GroupType
    if ($GroupType -ne $null) {
     $wSheet.Cells.Item($script:Row,2) = $GroupType.ToString()
    }
    $GroupMail = (Get-QADGroup -Identity $CN).email
    if ($GroupMail -ne $null) {
     $wSheet.Cells.Item($script:Row,3) = $GroupMail.ToString()
    }
    if ($member.FirstName -ne $null) {
     $wSheet.Cells.Item($script:Row,4) = $member.FirstName.ToString()
    }
    if ($member.LastName -ne $null) {
     $wSheet.Cells.Item($script:Row,5) = $member.LastName.ToString()
    }
    if ($member.SamAccountName -ne $null)
    {
     $wSheet.Cells.Item($script:Row,6) = $member.SamAccountName.ToString()
    }
    if ($member.email -ne $null)
    {
     $wSheet.Cells.Item($script:Row,7) = $member.email.ToString()
    }
    $ManagedBy = (Get-QADGroup -Identity $CN).ManagedBy
    if ($ManagedBy)
    {
     $wSheet.Cells.Item($script:Row,8) = $ManagedBy.ToString()
    }
   } else {
    if ($member.Type -eq "contact") {
     $script:Row += 1
     $wSheet.Cells.Item($script:Row,1) = $GroupName
     $GroupType = (Get-QADGroup -Identity $CN).GroupType
     if ($GroupType -ne $null) {
      $wSheet.Cells.Item($script:Row,2) = $GroupType.ToString()
     }
     $GroupMail = (Get-QADGroup -Identity $CN).email
     if ($GroupMail -ne $null) {
      $wSheet.Cells.Item($script:Row,3) = $GroupMail.ToString()
     }
     if ($member.type -ne $null)
     {
      $wSheet.Cells.Item($script:Row,6) = $member.type.ToString()
     }
     if ($member.name -ne $null)
     {
     $wSheet.Cells.Item($script:Row,7) = $member.name.ToString()
     }
    }
    else
    {
     #recurseMemberOf $member.DN
     $script:Row += 1
     $wSheet.Cells.Item($script:Row,1) = $GroupName
     $GroupType = (Get-QADGroup -Identity $CN).GroupType
     if ($GroupType -ne $null) {
      $wSheet.Cells.Item($script:Row,2) = $GroupType.ToString()
     }
     $wSheet.Cells.Item($script:Row,3) = $member.groupname.ToString()
     if ($member.type -ne $null)
     {
      $wSheet.Cells.Item($script:Row,6) = $member.type.ToString()
     }
     $groupmember = (Get-QADGroupMember $member).count
     if ($member.type -ne $null)
     {
      $wSheet.Cells.Item($script:Row,7) = $groupmember.ToString()
     }
    }
   }  
  } 
 }
 else
 {
  # Liste les groupes vide
  $script:Row += 1
  $wSheet.Cells.Item($script:Row,1) = $GroupName
  $GroupMail = (Get-QADGroup -Identity $CN).email
  if ($GroupMail -ne $null) {
   $wSheet.Cells.Item($script:Row,2) = $GroupMail.ToString()
  }
  $notmember = "Groupe Vide"
  $wSheet.Cells.Item($script:Row,2) = $notmember.ToString()
 }
}

#################### Main ####################

# Connect to AD
$credential = Get-Credential
Connect-QADService -service "DOMAIN" -Credential $credential

# Create Excel object
$Excel = New-Object -Com Excel.Application
$Excel.visible = $True
$Excel = $Excel.Workbooks.Add()
$wSheet = $Excel.Worksheets.Item(1)
$wSheet.Cells.Item(1,1) = "Group" 
$wSheet.Cells.Item(1,2) = "GroupType"
$wSheet.Cells.Item(1,3) = "GroupMail" 
$wSheet.Cells.Item(1,4) = "FirstName"
$wSheet.Cells.Item(1,5) = "LastName"
$wSheet.Cells.Item(1,6) = "Account"
$wSheet.Cells.Item(1,7) = "Email"
$wSheet.Cells.Item(1,8) = "ManagedBy"


# static variable
# Your static variable will also affect the console if you replace the prefix "script:" by "global:."
$script:Row = 1
$CNAME = "CNAME OF THE GROUP"
recurseMemberOf $CNAME

$range = $wsheet.usedRange
$range.EntireColumn.AutoFit() | out-null

Se connecter a une DB SQL et executer une query

Cette fonction se connecte a une DB SQL et retourne le resultat d'une query


Une fois configuré il suffit d'ajouter un alias dans son profils pour y avoir acces plus facilement ;-)


New-item -path alias:get-cmdb -value 


Script :

# Description : Ce script permet de faire des recherches dans une DB ( en l'occurence ici 
#
# Instructions: Copier sur un dossier de votre PC ( exemple c:\pwshell\get-cmdb.ps1 )
#    Ajouter cette ligne à votre fichier Profil : New-item -path alias:get-cmdb -value "PATH DE VOTRE SCRIPT"
#    Redemarrer votre session Powershell.
#
# Exemple : get-cmdb | ? {$_.name -match "toto"}
#
#
# ENTREE :  Nom du serveur
# SORTIE :  Hash Table


function sql_to_hash ([string]$query){
 $Database = NOM_DE_LA_DB
 $Server = SERVER
 $pwd = PASSWORD
 $Username = USERNAME
 $query = $query
 
 # Connect to SQL and query data, extract data to SQL Adapter
 $SqlQuery = $query
 $SqlConnection = New-Object System.Data.SqlClient.SqlConnection
 $SqlConnection.ConnectionString = "Data Source=$Server;Initial Catalog=$Database;Trusted_Connection=False;User Id=$Username;Password=$pwd"
 $SqlCmd = New-Object System.Data.SqlClient.SqlCommand
 $SqlCmd.CommandText = $SqlQuery
 $SqlCmd.Connection = $SqlConnection
 $SqlAdapter = New-Object System.Data.SqlClient.SqlDataAdapter
 $SqlAdapter.SelectCommand = $SqlCmd
 $DataSet = New-Object System.Data.DataSet
 $nRecs = $SqlAdapter.Fill($DataSet)
 $nRecs | Out-Null
 
 #Populate Hash Table
 $objTable = $DataSet.Tables[0]
 $object = New-Object psobject
 $object = $objTable
 $object
}

$Server = $args[0]

if ($Server)
{
 $server = $Server.replace("*","%")   # Permet de faire des recherches groupes
}
if ( $Server -eq $null)
{
 $query = "
#AJOUTER UNE QUERY SQL LISTANT TOUT LES SERVEURS DE LA DB
}
else
{
$query = "
#AJOUTER UNE QUERY SQL EN AJOUTANT UNE CONDITION POUR QUE LE NOM DU SERVEUR SOIT EGALE A LA VARIABLE $server 

}

 sql_to_hash $query 

Trouver pourquoi un PC a redemarrer

Cette fonction sert a trouver pourquoi une machine a rebooté :
IN : MachineName

# Return all events about shutdown
#
# http://gallery.technet.microsoft.com/scriptcenter/496332b0-0e2d-4875-bcae-db8384512812

function Get-ShutdownReason { 
#Requires -Version 2.0             
[CmdletBinding()]             
 Param              
   (                        
    [Parameter(Mandatory=$true, 
               Position=1,                           
               ValueFromPipeline=$false,             
               ValueFromPipelineByPropertyName=$false)]             
    [Array]$Computer, 
    [Int]$Count = 4 
   )#End Param 
 
Begin             
{             
 Write-Host "`n Checking logs . . . " 
 $i = 0             
}#Begin           
Process             
{ 
 
$Computer | % { 
Get-EventLog -ComputerName $_ -LogName system -Source USER32 -Newest $Count | select TimeWritten, Username, Message # | fl 
} 
 
}#Process 
End 
{ 
 
}#End 
 
}
Get-ShutdownReason $args[0]

vendredi 4 juin 2010

Personnaliser sa console Powershell

- Modify the size :
Screen Buffer Size :
Width = 180
Heigth = 300
Windows Size :
Width = 180
Heigth =80

- Chargement des ADCmdlets
Add-PSSnapin Quest.ActiveRoles.ADManagement -ErrorAction SilentlyContinue        


- Definier vos alias
New-item -path alias:nmap -value 'c:\Program Files\Nmap\nmap.exe'

( ici j'ai installé l'outils nmap)

- Voici comment avoir un prompt Unix-Like
function prompt()
{
   #$num = (get-history -count 1).id + 1
   $path2 = (Get-Location).path
   $promptText = (get-content env:\username) + '@' + (Connect-QADService).domain.name + ':' + $path2
   $promptText = "$promptText>"
   write-host $promptText -NoNewline -foregroundcolor "green"
   $host.UI.rawUI.WindowTitle = (get-location).Path;
   return ' '
}


- et un petit peu de custo :
cls
write-host "__________                                 .__           .__  .__   "
write-host "\______   \______  _  __ ___________  _____|  |__   ____ |  | |  |  "
write-host "|     ___/  _ \ \/ \/ // __ \_  __ \/  ___/  |  \_/ __ \|  | |  |  "
write-host " |    |  (  <_> )     /\  ___/|  | \/\___ \|   Y  \  ___/|  |_|  |__"
write-host " |____|   \____/ \/\_/  \___  >__|  /____  >___|  /\___  >____/____/"
write-host "                            \/           \/     \/     \/              "
write-host "Command :"
write-host "nmap "
cd c:\pwshell

jeudi 3 juin 2010

Pour bien commencer en Powershell


Ce post à pour but de vous présenter le site Scripting Operations Framework.

Ce site est un bon début pour ceux qui veulent se lancer dans l'aventure du Powershell. Les vidéos qui sont présentées sont en français et très bien expliquées :-)

Liens des vidéos
Formation PowerShell #01 : les bases
Formation PowerShell #02 : Son SI en ligne de commande
Formation PowerShell #03 : Automatisation et sécurité
Formation PowerShell #04 : Exchange Management Shell