Installation de Powershell
Download Windows Management Framework 4.0
https://www.microsoft.com/fr-ch/download/details.aspx?id=40855
Si:
cannot be loaded because the execution of scripts is disabled on this system
Alors exécuter dans la console ps
Set-ExecutionPolicy RemoteSigned
A mettre dans un cmd pour lancer le fichier ps1
set currentpath=%~dp0
cd "%currentpath%"
powershell.exe -WindowStyle hidden -file "%currentpath%MonSuperScript.ps1"
if exist avec affichage box
cls
write-host [Vérification des fichiers] #Commentaire dans la console
If ((Test-Path $Fichier)-eq $false)
{
$Temp="Fichier "+$Fichier+" non trouvé"
[System.Windows.MessageBox]::Show($Temp)
}
Exemple de lecture d'un fichier ini contenant plusieurs fois 7 lignes
write-host [Chargement des données du Fermetures_Campings.txt]
[int]$CursCamp=1
[int]$SousLigne=0
$fichier = Get-Content $FichierFermeture
Foreach ( $ligne in $fichier )
{
$SousLigne=$SousLigne+1
if ($SousLigne -gt 7)
{
$SousLigne=0
$CursCamp=$CursCamp+1
}
if ($SousLigne -eq 1) { $CC[$CursCamp] = $ligne }
if ($SousLigne -eq 2) { $NomCamping[$CursCamp] = $ligne }
if ($SousLigne -eq 3)
{
$DateFichier=[int]$ligne
$DateActuelle = Get-Date -format "yyyyMMdd"
$DateActuelle = [int] $DateActuelle
if ( $DateFichier -lt $DateActuelle)
{
$DateOuverture[$CursCamp] = $false
}else{
$DateOuverture[$CursCamp] = $true
}
}
if ($SousLigne -eq 4) { $Log[$CursCamp] = $ligne }
if ($SousLigne -eq 5) { $Sap[$CursCamp] = $ligne }
if ($SousLigne -eq 6) { $TPE[$CursCamp] = $ligne }
if ($SousLigne -eq 7) { $NomPoste[$CursCamp] = $ligne }
}
Ecriture d'une page web
write-host [Ecriture de la page web]
If ((Test-Path "Header.html")-eq $true) { Remove-Item "Header.html" }
ADD-content -path "Header.html" -value ""
ADD-content -path "Header.html" -value ""
Import d'une page web
$wc=new-object system.net.webclient
$wc.UseDefaultCredentials = $true
$wc.downloadfile("https://tcsit.service-now.com/sys_report_display.do?sysparm_report_id=4ef638f76f91460098a5d107eb3ee41b","incident.html")
Transfert FTP
$ftp = "ftp://wge3as045p/"
$user = "publitest"
$pass = "Publitest1"
$webclient = New-Object System.Net.WebClient
$webclient.Credentials = New-Object System.Net.NetworkCredential($user,$pass)
foreach($item in (dir $ScriptPath "incident.html")){
"Uploading $item..."
$uri = New-Object System.Uri($ftp+$item.Name)
$webclient.UploadFile($uri, $item.FullName)
}
Bouton GUI de compression ZIP
# Bouton ZIP Dropbox
$ZIPdrop = New-Object System.Windows.Forms.Button
$ZIPdrop.Location = New-Object System.Drawing.Size(10,35)
$ZIPdrop.Size = New-Object System.Drawing.Size(100,23)
$ZIPdrop.Text = "ZIP Dropbox"
$ZIPdrop.Add_Click({ZIPdropboxNouvelleMethode})
$objForm.Controls.Add($ZIPdrop)
Function ZIPdropboxNouvelleMethode
{
#Bla-bla
$Heure=Get-Date -format 'HH:mm'
write-host "Début de la compression dropbox à $Heure (Durée 10 min. environ)"
$objLabel.Text = "En cours..."
#Effacer fichier si existant
If (Test-Path "C:\Sauvegarde_Dropbox\Dropbox_Nicolas_*"){
Remove-Item "C:\Sauvegarde_Dropbox\Dropbox_Nicolas_*"
}
sleep 4
#Compression - Attention. Suspission de faire planter le PC
$source = "C:\Users\sn04028\Dropbox"
$dd=(get-date).tostring(‘dd-MM-yyyy’)
$destination = "C:\Sauvegarde_Dropbox\Dropbox_Nicolas_$dd.zip"
Add-Type -assembly "system.io.compression.filesystem"
[io.compression.zipfile]::CreateFromDirectory($Source, $destination)
#Bla-bla<br>
$Heure=Get-Date -format 'HH:mm'
write-host "Compression terminée à $Heure"
$objLabel.Text = "OK"
}
On peut rajouter de simples commande DOS, comme ici l'import d'un fichier par Putty SCP
.\pscp.exe -2 -i Private-symon01.ppk symon01@lge3as221p:/opt/nsa/lge3as221p.txt lge3as221p.txt
Bête boucle for next
#Déclarer variables
[int]$i
[Boolean[]]$DateOuverture = $true,$true,$true,$true,$true,$true,$true,$true,$true
# Boucle
for ($i = 1; $i -lt $CursCamp; $i++)
{
if ( $DateOuverture[$i] -eq $true )
{
ADD-content -path "Data.html" -value ""
}else{
ADD-content -path "Data.html" -value ""
}
}
Exemple de librairie (libNSA.ps1) avec fonction "EcrireLog"
<#
------------------------------------------------------------------------------
Librairie Standard
Nicolas Salamin
------------------------------------------------------------------------------
#>
function EcrireLog
{
<#
.SYNOPSIS
Writes the specified message of the specified message type to the PowerShell console.
.DESCRIPTION
Writes the specified message of the specified message type to the PowerShell console.
.PARAMETER Message
Specifies the actual message to be written to the console.
.PARAMETER MessageType
Specifies the type of message to be written of either "Error", Warning,
"Debug", "Verbose", or "Information". The message type simply changes the
background and foreground colors so that the type of message is known
at a glance.
.PARAMETER MessageType
Specifies the type of message to be written of either "Error", Warning,
"Debug", "Verbose", or "Information". The message type simply changes the
background and foreground colors so that the type of message is known
at a glance.
.EXAMPLE
PS C:\> WriteConsoleMessage -Message "This is an error message" -MessageType Error
.EXAMPLE
PS C:\> WriteConsoleMessage -Message "This is a warning message" -MessageType Warning
.EXAMPLE
PS C:\> WriteConsoleMessage -Message "This is a debug message" -MessageType Debug
.EXAMPLE
PS C:\> WriteConsoleMessage -Message "This is a verbose message" -MessageType "Verbose"
.EXAMPLE
PS C:\> WriteConsoleMessage -Message "This is an information message" -MessageType Information
.INPUTS
System.String
.OUTPUTS
A message is written to the PowerShell console.
.NOTES
#>
[CmdletBinding()]
param
(
[Parameter(
Mandatory=$True,
ValueFromPipeline=$True,
ValueFromPipelineByPropertyName=$True,
Position=0,
HelpMessage="Specifies the actual message to be written to the console")]
[ValidateNotNullOrEmpty()]
[System.String] $Message,
[Parameter(
Mandatory=$True,
ValueFromPipeline=$True,
ValueFromPipelineByPropertyName=$True,
Position=1,
HelpMessage="Specifies the type of message to be written.")]
[ValidateSet("Error", "Warning", "Debug", "Verbose", "Information")]
[ValidateNotNullOrEmpty()]
[System.String] $MessageType,
[Parameter(
Mandatory=$False,
ValueFromPipeline=$True,
ValueFromPipelineByPropertyName=$True,
Position=2,
HelpMessage="Specifies the fileName to append message to a file.")]
[ValidateNotNullOrEmpty()]
[System.String] $fileName
)
Switch ($MessageType)
{
"Error"
{
if (![System.String]::IsNullOrEmpty($fileName)) {Add-Content -Path $fileName -Value ([System.String]::Format("ERROR: [{0}\{1}]`t{2}`t{3}", `
$env:USERDNSDOMAIN, $env:USERNAME, [System.DateTime]::Now.ToString('u'), $Message)) -Force -Confirm:$False}
$Message = "ERROR: {0}" -f $Message
Write-Host $Message -ForegroundColor White -BackgroundColor Red
}
Warning
{
if (![System.String]::IsNullOrEmpty($fileName)) {Add-Content -Path $fileName -Value ([System.String]::Format("WARNING: `t{0}`t{1}", `
[System.DateTime]::Now.ToString('u'), $Message)) -Force -Confirm:$False}
$Message = "WARNING: {0}" -f $Message
Write-Host $Message -ForegroundColor Yellow #-BackgroundColor Yellow
}
"Debug"
{
if (![System.String]::IsNullOrEmpty($fileName)) {Add-Content -Path $fileName -Value ([System.String]::Format("DEBUG: [{0}\{1}]`t{2}`t{3}", `
$env:USERDNSDOMAIN, $env:USERNAME, [System.DateTime]::Now.ToString('u'), $Message)) -Force -Confirm:$False}
$Message = "DEBUG: {0}" -f $Message
Write-Host $Message -ForegroundColor Green #-BackgroundColor Green
}
"Verbose"
{
if (![System.String]::IsNullOrEmpty($fileName)) {Add-Content -Path $fileName -Value ([System.String]::Format("VERBOSE: `t{0}`t{1}", `
[System.DateTime]::Now.ToString('u'), $Message)) -Force -Confirm:$False}
$Message = "VERBOSE: {0}" -f $Message
Write-Host $Message -ForegroundColor Cyan #-BackgroundColor Black
}
"Information"
{
if (![System.String]::IsNullOrEmpty($fileName)) {Add-Content -Path $fileName -Value ([System.String]::Format("Info: `t{0}`t{1}", `
[System.DateTime]::Now.ToString('u'), $Message)) -Force -Confirm:$False}
$Message = "Info: {0}" -f $Message
Write-Host $Message -ForegroundColor Gray #-BackgroundColor Black
}
default
{
if (![System.String]::IsNullOrEmpty($fileName)) {Add-Content -Path $fileName -Value ([System.String]::Format("`t{0}`t{1}", `
[System.DateTime]::Now.ToString('u'), $Message)) -Force -Confirm:$False}
Write-Host $Message -ForegroundColor Gray #-BackgroundColor Black
}
}
}
Exemple GUI
<#
------------------------------------------------------------------------------
Template
Nicolas Salamin
------------------------------------------------------------------------------
#>
# -----------------------------------------------------------------------------
# <<< Paramètres d'entrée du script. Ici "filename" >>>
[CmdletBinding()]
param(
[Parameter(
Mandatory=$false,
ValueFromPipeline=$true,
ValueFromPipelineByPropertyName=$true,
Position=1,
HelpMessage="Specifies the CSF file that contains information for the resource that will be migrated.")]
[ValidateNotNullOrEmpty()]
[System.String]$fileName = '.\Users.csv'
)
#-------------------------------------------------------------------------------
# Variables
$Error.Clear() # Effacer les logs d'erreurs d'avant
$ScriptPath = Split-Path $MyInvocation.MyCommand.Path; # Récupérer le path
$ScriptName = $MyInvocation.MyCommand.Name; # Récupérer le nom du script
$logFile = [System.String]::Format("{0}\{1}", (Get-Item -Path $ScriptPath).FullName, $ScriptName.Replace(".ps1","-$((Get-Date -uformat %Y-%m-%d).ToString()).log")) # Nom du log
.$Global:exbin"$ScriptPath\LibNSA.ps1" # Ajoute une librairie perso
$separator = ';'
# GUI
[void] [System.Reflection.Assembly]::LoadWithPartialName("System.Drawing")
[void] [System.Reflection.Assembly]::LoadWithPartialName("System.Windows.Forms")
# Création Form
$objForm = New-Object System.Windows.Forms.Form
$objForm.Text = "Data Entry Form"
$objForm.Size = New-Object System.Drawing.Size(600,400)
$objForm.StartPosition = "CenterScreen"
# Hook keys. [Esc=quitter]
$objForm.KeyPreview = $True
$objForm.Add_KeyDown({if ($_.KeyCode -eq "Escape") # Ou "Enter" par exemple, avec plusieurs appels comme {$x=$objTextBox.Text;$objForm.Close()}
{$objForm.Close()}})
# Bouton OK
$OKButton = New-Object System.Windows.Forms.Button
$OKButton.Location = New-Object System.Drawing.Size(75,120)
$OKButton.Size = New-Object System.Drawing.Size(75,23)
$OKButton.Text = "OK"
$OKButton.Add_Click({$x=$objTextBox.Text;$objForm.Close()})
$objForm.Controls.Add($OKButton)
# Bouton Cancel
$CancelButton = New-Object System.Windows.Forms.Button
$CancelButton.Location = New-Object System.Drawing.Size(150,120)
$CancelButton.Size = New-Object System.Drawing.Size(75,23)
$CancelButton.Text = "Cancel"
$CancelButton.Add_Click({$objForm.Close()})
$objForm.Controls.Add($CancelButton)
# Label
$objLabel = New-Object System.Windows.Forms.Label
$objLabel.Location = New-Object System.Drawing.Size(10,20)
$objLabel.Size = New-Object System.Drawing.Size(280,20)
$objLabel.Text = "Ajouter un texte ci-dessous:"
$objForm.Controls.Add($objLabel)
# Testbox
$objTextBox = New-Object System.Windows.Forms.TextBox
$objTextBox.Location = New-Object System.Drawing.Size(10,40)
$objTextBox.Size = New-Object System.Drawing.Size(260,20)
$objForm.Controls.Add($objTextBox)
# Toujours en premier plan
$objForm.Topmost = $True
#-------------------------------------------------------------------------------
# Main Script Execution
cls
EcrireLog -Message "Debut du script $ScriptName" -MessageType Information -fileName $logFile
EcrireLog -Message $objTextBox.Text -MessageType Information -fileName $logFile
#Affiche la form
$objForm.Add_Shown({$objForm.Activate()})
[void] $objForm.ShowDialog()
#-------------------------------------------------------------------------------
# Fin du script.
EcrireLog -Message "====================================" -MessageType Information -fileName $logFile
Exit 0
ActiveDirectory dans CSV
Import-Module ActiveDirectory # Module disponible sur admins tools d'un serveur.
Get-ADUser -Filter * -Properties * | Select -Property Name,Mail,Department | Export-CSV "AllADUsers.csv" -NoTypeInformation -Encoding UTF8
Import CSV
Le CSV en question:
ID;Prenom;Nom
1;Nicolas;Salamin
2;Guy;Tarre
3;Denis;Barre
# CSV
#Input
$Variable = Import-Csv .\Input.csv -Delimiter ";"
#Output
$Variable | select-object Nom,Prenom | export-csv Output.csv
#XML
#Input
$Data = [Xml] (Get-Content Input.xml)
#Output
$Data | Export-Clixml Output.xml
#Output CSV
$Data.database.record | export-csv OutputXML.csv
Classe de variable
Class toto
{
$Nom
$Prenom
$Genre
appel($Nom,$Prenom)
{
$DisplayName = "$($Nom.ToUpper()) $($Prenom.ToLower())"
Write-Host $DisplayName
}
}
$test = New-Object toto
$test.prenom = "LIVIO"
$test.nom = "jeangoudoux"
$test.appel($test.Nom,$test.Prenom)
Progress Bar
$Width = 400
$Height = 200
#create the form
$form1 = New-Object System.Windows.Forms.Form
$form1.Text = $title
$form1.Height = 200
$form1.Width = 400
$form1.BackColor = $color
$form1.FormBorderStyle = [System.Windows.Forms.FormBorderStyle]::FixedSingle
#display center screen
$form1.StartPosition = [System.Windows.Forms.FormStartPosition]::CenterScreen
# create label
$label1 = New-Object system.Windows.Forms.Label
$label1.Text = "not started"
$label1.Left=5
$label1.Top= 10
$label1.Width= $width - 20
#adjusted height to accommodate progress bar
$label1.Height=15
$label1.Font= "Verdana"
#optional to show border
#$label1.BorderStyle=1
#add the label to the form
$form1.controls.add($label1)
$progressBar1 = New-Object System.Windows.Forms.ProgressBar
$progressBar1.Name = 'progressBar1'
$progressBar1.Value = 0
$progressBar1.Style="Continuous"
$System_Drawing_Size = New-Object System.Drawing.Size
$System_Drawing_Size.Width = $width - 40
$System_Drawing_Size.Height = 20
$progressBar1.Size = $System_Drawing_Size
$progressBar1.Left = 5
$progressBar1.Top = 40
#Finally, like the other controls, the progress bar needs to be added to the form.
$form1.Controls.Add($progressBar1)
#Now I can show the form and start the main part of my PowerShell script.
$form1.Show()| out-null
#give the form focus
$form1.Focus() | out-null
#update the form
$label1.text="Preparing to analyze $path"
$form1.Refresh()
start-sleep -Seconds 5
#run code and update the status form
#get top level folders
$top = Get-ChildItem -Path $path -Directory
#initialize a counter
$i=0
foreach ($folder in $top) {
#calculate percentage
$i++
[int]$pct = ($i/$top.count)*100
#update the progress bar
$progressbar1.Value = $pct
$label1.text="Measuring size: $($folder.Name)"
$form1.Refresh()
start-sleep -Milliseconds 300
$stats = Get-ChildItem -path $folder -Recurse -File |
Measure-Object -Property Length -Sum -Average
[pscustomobject]@{
Path=$folder.Name
Files = $stats.count
SizeKB = [math]::Round($stats.sum/1KB,2)
Avg = [math]::Round($stats.average,2)
}
} #foreach
$form1.Close()
Sympathique petit script de recherche dans un fichier
#-------------------------------------------------------------------------------
# Variables
$Error.Clear() # Effacer les logs d'erreurs d'avant
$ScriptPath = Split-Path $MyInvocation.MyCommand.Path; # Récupérer le path
$ScriptName = $MyInvocation.MyCommand.Name; # Récupérer le nom du script
$logFile = [System.String]::Format("{0}\{1}", (Get-Item -Path $ScriptPath).FullName, $ScriptName.Replace(".ps1","-$((Get-Date -uformat %Y-%m-%d).ToString()).log")) # Nom du log
.$Global:exbin"$ScriptPath\LibNSA.ps1" # Ajoute une librairie perso
# GUI
[void] [System.Reflection.Assembly]::LoadWithPartialName("System.Drawing")
[void] [System.Reflection.Assembly]::LoadWithPartialName("System.Windows.Forms")
# Création Form
$objForm = New-Object System.Windows.Forms.Form
$objForm.Text = "DAE finder"
$objForm.Size = New-Object System.Drawing.Size(210,235)
$objForm.StartPosition = "CenterScreen"
# Hook keys. [Esc=quitter]
$objForm.KeyPreview = $True
$objForm.Add_KeyDown({if ($_.KeyCode -eq "Escape") # Ou "Enter" par exemple, avec plusieurs appels comme {$x=$objTextBox.Text;$objForm.Close()}
{$objForm.Close()}})
# Bouton Rechercher
$OKButton = New-Object System.Windows.Forms.Button
$OKButton.Location = New-Object System.Drawing.Size(10,160)
$OKButton.Size = New-Object System.Drawing.Size(75,23)
$OKButton.Text = "Rechercher"
$OKButton.Add_Click({RechercherCSV})
$objForm.Controls.Add($OKButton)
# Bouton Ouvrir
$OKButton = New-Object System.Windows.Forms.Button
$OKButton.Location = New-Object System.Drawing.Size(110,160)
$OKButton.Size = New-Object System.Drawing.Size(75,23)
$OKButton.Text = "Voir log"
$OKButton.Add_Click({VoirLog})
$objForm.Controls.Add($OKButton)
# Label 1
$objLabel = New-Object System.Windows.Forms.Label
$objLabel.Location = New-Object System.Drawing.Size(10,20)
$objLabel.Size = New-Object System.Drawing.Size(280,20)
$objLabel.Text = "DAE à rechercher:"
$objForm.Controls.Add($objLabel)
# Label 2
$objLabel = New-Object System.Windows.Forms.Label
$objLabel.Location = New-Object System.Drawing.Size(10,70)
$objLabel.Size = New-Object System.Drawing.Size(280,20)
$objLabel.Text = "Période:"
$objForm.Controls.Add($objLabel)
# Textbox 1
$objTextBox = New-Object System.Windows.Forms.TextBox
$objTextBox.Location = New-Object System.Drawing.Size(10,40)
$objTextBox.Size = New-Object System.Drawing.Size(175,20)
$objTextBox.Text="a1M57000007kHDNEA2"
$objForm.Controls.Add($objTextBox)
# Textbox 2
$objTextPeriode = New-Object System.Windows.Forms.TextBox
$objTextPeriode.Location = New-Object System.Drawing.Size(10,90)
$objTextPeriode.Size = New-Object System.Drawing.Size(175,20)
$objTextPeriode.Text="2016-06"
$objForm.Controls.Add($objTextPeriode)
#Progressbar
$progressBar1 = New-Object System.Windows.Forms.ProgressBar
$progressBar1.DataBindings.DefaultDataSourceUpdateMode = 0
$progressBar1.Step = 1
$progressBar1.Style="Continuous"
$progressBar1.Name = 'progressBar1'
$progressBar1.Top=125
$progressBar1.Left=10
$objForm.Controls.Add($progressBar1)
$progressBar1.Width = 175
$progressBar1.value=0 # en %
# Toujours en premier plan
$objForm.Topmost = $True
#-------------------------------------------------------------------------------
# Fonctions
Function RechercherCSV
{
$P=$objTextPeriode.Text
write-host "Un instant, je regarde le nombre de fichiers ..."
[int]$TotalCsv=(dir \\wge3in002p\Printshop_Prod$\Logs\SPS-CSV-Archive\*$P*.csv).count
write-host "Recherche dans $TotalCsv fichiers ..."
$TotalCsv=$TotalCsv+1
#Pour la Progressbar
[int]$Curs=0
[int]$Pourcent=100/$TotalCsv*($TotalCsv-($TotalCsv-$Curs))
ForEach ($file in Get-ChildItem \\wge3in002p\Printshop_Prod$\Logs\SPS-CSV-Archive\*$P*.csv) # Pour chaque fichiers trouvés dans le répertoire...
{
#Progressbar
$Curs=$Curs+1
$Pourcent=100/$TotalCsv*($TotalCsv-($TotalCsv-$Curs))
$progressBar1.value=$Pourcent
#Recherche du DAE
write-host Recherche dans $file.name -ForegroundColor Green;
$V=$objTextBox.Text
$Resultat=get-content "$file" | Select-String $V # Equivalent du " cat | grep "
if ($Resultat -ne $null) {EcrireLog -Message "Résultat trouvé dans $file" -MessageType Information -fileName $logFile}
}
write-host "Fin de la recherche."
}
Function VoirLog
{
If (Test-Path $logFile){
&"c:\Windows\System32\notepad.exe" $logFile
}else{
write-host "Fichier inexistant."
}
}
#-------------------------------------------------------------------------------
# Main Script Execution
#Affiche la form
$objForm.Add_Shown({$objForm.Activate()})
[void] $objForm.ShowDialog()
#-------------------------------------------------------------------------------
# Fin du script.
Exit 0