|
|
Ligne 173 : |
Ligne 173 : |
|
| |
|
| # concaténation de string | | # concaténation de string |
| echo 'Text1 - ' + "Text2: ${Var1}, $Var2" | | echo 'Text1 - ' + "Text2: $Var1, $(Var2.Prop1)" |
| echo "Text: $(command)" | | echo "Text: $(command)" |
|
| |
|
Version du 28 octobre 2021 à 14:56
Liens
Script template
À placer au début du script (en dessous de Param).
|
Set-StrictMode -Version Latest
$ErrorActionPreference = "Stop"
$PSDefaultParameterValues['*:ErrorAction'] = 'Stop'
|
Astuces
|
command -option1 `
-option2
command1; command2
Commande -WhatIf
powershell -file MonFichier.ps1
C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe -command "& 'C:\dossier\script.ps1' args"
& 'C:\dossier\script.ps1' args
sp file.txt IsReadOnly $false
ii .
$ie = New-Object -ComObject InternetExplorer.Application
$ie.Navigate2("http://www.google.com")
$ie.Visible = $true
[bool](([System.Security.Principal.WindowsIdentity]::GetCurrent()).groups -match "S-1-5-32-544")
$PSVersionTable
|
Variables
|
Pas de - dans les noms des variables. |
|
$my_var = "value"
|
|
Get-Childitem env:
|
$env:userprofile |
C:\Users\<user>
|
$env:appdata |
C:\Users\<user>\AppData\Roaming
|
$env:ProgramFiles |
C:\Program Files
|
[environment]::getfolderpath("mydocuments") |
C:\Users\<user>\Documents
|
$_ |
the current object in the pipeline
|
$home |
C:\Users\<user>
|
$Pwd |
full path of the current directory
|
$PSCommandPath |
path of the script file that is being executed
|
$PSScriptRoot |
path of the script directory that is being executed
|
echo, Write-Host
|
echo 'my text'
echo line1 line2
echo line1`nline2
echo line1([system.environment]::newline)line2
Write-Host -foregroundcolor green -backgroundcolor black Mon Message
Write-Error "Error!"
|
Couleurs disponibles
Black |
Blue |
Cyan |
DarkBlue
|
DarkCyan |
DarkGray |
DarkGreen |
DarkMagenta
|
DarkRed |
DarkYellow |
Gray |
Green
|
Magenta |
Red |
White |
Yellow
|
|
echo is an alias of Write-Output |
|
Install-Module -Name PSWriteColor
Import-Module PSWriteColor
Write-Color "Red ", "Green ", "Yellow " -Color Red, Green, Yellow
wc "Red ", "Green ", "Yellow " -C Red, Green, Yellow
|
Read input
|
$input = Read-Host 'Question?'
Write-Host -NoNewLine 'Press any key to continue...';
$null = $Host.UI.RawUI.ReadKey('NoEcho,IncludeKeyDown');
|
GridView
|
New-Object Net.Webclient | Get-Member | Out-GridView
Get-Service |
Where Status -eq Stopped |
Out-GridView -PassThru |
Start-Service
|
Types
String
|
echo "Escape `"double-quotes`" `$1"
echo "Retour à la ligne `r`n"
echo 'Text1 - ' + "Text2: $Var1, $(Var2.Prop1)"
echo "Text: $(command)"
echo @"
First line
Second line
"Quotes don't need to be escaped"
Plus, you can include variables: $MyVar
"@
'ABC' -replace 'B','X'
'ABC' -replace '\w$','X'
'ABC' -replace '^(\w)(.+)(\w)$','$3$2$1'
'ABC' -replace '^(?<first>\w)(.+)(?<last>\w)$','${last}$1${first}'
'ABC' -replace 'B'
'ABC'.replace('B', '')
'abc'.toupper()
|
Test string
|
$MyString -like 'xxx*'
$MyString -match 'xxx.+'
$MyString.startswith('xxx')
if ($MyString)
if (!$MyString)
|
Date
|
Get-Date -Format 'yyyy-MM'
|
Tableau / array
|
$myArray = @()
$myArray = 1, 2, 3
$myArray += 4
$myArray[1..2]
$myArray[-1]
$myArray -ne 2
$myArray -gt 2
[array]::Reverse($myArray)
$one, $two, $rest = $myArray
|
|
$myHashTable = @{}
$myHashTable = @{
Key1 = 'Value1'
}
$myHashTable = [ordered]@{
Key1 = 'Value1'
}
$myHashTable.Key1 = "Value1"
$myHashTable["Key2"] = "Value2"
echo $myHashTable
$myValue = $myHashTable.Key1
$myValue = $myHashTable["Key1"]
$myValue = $myHashTable.$myKey
"All keys: $($myHashTable.keys)"
"All values: $($myHashTable.values)"
if (!$myHashTable.contains($myKey))
|
PSObject
|
$obj = New-Object PSObject -Property @{
Prop1 = "Value1"
Prop2 = "Value2"
}
|
if else
|
$nombre = 10
if ($nombre -eq 10) {
"Le nombre est 10."
}
elseif (($nombre -gt 5) -and ($nombre -lt 10) -or ($nombre -eq 222)) {
"Le nombre est entre 5 et 10 ou égal à 222."
}
elseif (!($nombre -eq 333)) {
"Le nombre est différent de 333."
}
else { "Surement 333" }
|
Opérateur
|
Description
|
Opérateur
|
Description
|
-eq |
== |
-ceq |
== case senstivie
|
-ne |
!=
|
-lt |
< |
-le |
<=
|
-gt |
> |
-ge |
>=
|
-not ! |
!
|
-and |
&& |
-or |
||
|
-band |
& |
-bor |
|
|
Test string
|
if ([string]::IsNullOrEmpty($monString))
|
The String’s the Thing
|
switch ($var)
{
'value1' { echo $var }
'value2' { echo $var }
default { echo 'unknown value' }
}
$result = switch ($var)
{
'Word1' { 'Value1' }
'Word2' { 'Value2' }
default { 'Default Value' }
}
|
|
command | select UnePropriété
(command).UnePropriété
command | select -exp UnePropriété
command | select -first 10
|
|
1..4 | ? {$_ % 2 -eq 0}
|
|
Alias: Where-Object where ? |
ForEach %
|
1..4 | % { $_ * 2 }
1..4 | % {
$_ * 2
}
|
|
function TestName {
param(
[Parameter(Mandatory=$true, ValueFromPipeline=$true)]
[string] $nom
)
if ($nom -eq "moi")
{
return $true
}
return $false
}
TestName "moi"
|
|
La fonction doit être déclarée avant son utilisation. |
Paramètres et Arguments
|
param (
[string] $Name = "initial value",
[Parameter(Mandatory = $true, Position = 0)]
[string] $Name,
[Parameter(Position = 1)]
[bool] $BooleanValue,
[switch] $SwitchValue,
[Alias('e','ef')]
[string] $excludeFolder
)
.\MonScript.ps1 -Name MyName -BooleanValue $false -SwitchValue
.\MonScript.ps1 MyName $false
if (!$PSBoundParameters.ContainsKey('excludeFolder')) { }
|
|
Mandatory = $true , demande de manière interactive les paramètres s'ils ne sont pas spécifiés. |
|
$args fonctionne avec les arguments passés à une fonction mais pas avec ceux passés à un script. |
Exclusive groups of mandatory elements
|
[CmdletBinding(DefaultParameterSetName='Env')]
Param (
[Parameter(ParameterSetName = 'Env', Mandatory = $true)]
[string] $Environment,
[Parameter(ParameterSetName = 'Srv', Mandatory = $true)]
[string] $Server
[Parameter(ParameterSetName = 'Srv', Mandatory = $true)]
[string] $Database
)
echo $PSCmdlet.ParameterSetName
|
Parameter
|
-Debug
|
-ErrorAction
|
-ErrorVariable
|
-OutBuffer
|
-OutVariable
|
-Verbose
|
-WarningAction
|
-WarningVariable
|
|
[CmdletBinding()]
Param ()
if ($PSBoundParameters['Verbose'])
|
Help content
|
param (
[Alias('h')]
[switch] $help,
)
if ($help) {
get-help $MyInvocation.MyCommand.Path -detailed
exit
}
MonScript.ps1 -h
get-help MonScript.ps1 -detailed
man MonScript.ps1 -detailed
|
Files and folders
|
ls C:\Dossier -Name
ls C:\Dossier | % FullName
ls C:\Dossier | % BaseName
ls C:\Dossier *.txt
ls C:\Dossier -exclude *.txt, *.dll
ls C:\Dossier | ? Name -Match "\.txt$"
ls C:\Dossier | ? Name -Like "*.txt"
ls *.dll,*.exe | % { "{0}`t{1}" -f $_.Name, [System.Diagnostics.FileVersionInfo]::GetVersionInfo($_).FileVersion }
|
|
ls dir gci are aliases of Get-ChildItem |
|
filter et exclude ne fonctionnent pas en même temps.
Utiliser * dans le chemin à la place de filter |
|
-exclude only applies to basenames of items myfile.txt, not the fullname C:\folder\myfile.txt |
|
ls C:\Dossier | sort
ls C:\Dossier | sort -property LastWriteTime -Descending
|
Search by name
|
ls -r -ErrorAction SilentlyContinue "*.txt"
|
Search by file content
|
ls -r C:\Dossier | sls "xxx" | group path | % name
ls -r C:\Dossier | sls "xxx" -context 2
'123' | sls -quiet '2'
|
|
sls is an alias of Select-String |
|
context ne semble plus fonctionner |
|
$content = Get-Content .\file.txt
$content = Get-Content .\file.txt -raw
Get-Content .\file.txt -Wait -Tail 1
|
|
Set-Content -Encoding UTF8 -Path .\file.txt -Value 'Text'
|
Replace content
|
The default encoding is UTF-8 without BOM |
|
(Get-Content .\file.txt) -replace 'Text', 'Content' | Set-Content .\file.txt
(Get-Content .\file.txt) -replace 'var=(\w+);', "var=$new_value;" | Set-Content .\file.txt
(Get-Content .\file.txt -raw) -replace '(?s)<tag>.+</tag>' | Set-Content .\file.txt
(Get-Content .\file.txt) -replace '(\d{3})', "`r`n`$1" | Set-Content .\file.txt
(Get-Content .\file.txt -raw) -replace 'regex', 'xxx' -join "`r`n" | Set-Content .\file.txt -NoNewline
|
XPath
|
$path = 'C:\file.xml'
[xml]$xml_content = Get-Content $path
select-xml -path $path `
-xpath '/root/node[@attribute="value"]' `
| select -exp node `
| select value
$node = $xml_content.SelectSingleNode('/root/node[@attribute="value"]')
$node.Value = 'xxx'
$xml_content.save($path)
$xml_content.save([Console]::Out)
|
Delete files based on pattern
|
ls *.txt | Remove-Item
|
|
Install-Module -Name Recycle
Remove-ItemSafely [FileName|FolderName]
New-Alias trash 'Remove-ItemSafely'
|
|
rm -r -fo C:\Dossier
if (test-path C:\Dossier) { rm -r C:\Dossier }
ni C:\Dossier -type directory | Out-Null
ni C:\Dossier -type directory -force
|
|
Alias de Remove-Item: del, erase, rd, ri, rm, rmdir
Alias de New-Item: ni |
Remove-Item
Path
|
join-path dossier1 dossier2
join-path -path dossier1 -childpath dossier2
join-path -path dossier1\ -childpath \dossier2\
join-path -path dossier1 -childpath (join-path -path dossier2 -childpath dossier3)
[System.IO.Path]::Combine("C:\Dossier1", "Dossier2", "Dossier3")
if (Test-Path C:\Dossier -PathType Container) { }
if (Test-Path C:\Dossier\file.txt -PathType Leaf) { }
|
|
cp C:\Dossier\Fichier.txt C:\Dossier2\Fichier2.txt
cp -recurse C:\Dossier C:\Dossier2
cp C:\Dossier C:\Dossier2 -recurse -filter *.txt
cp C:\Dossier\*.txt C:\Dossier2 -exclude *.bak.txt
$from = convert-path (join-path $Path1 '..\Dossier')
ls -r $from -exclude *.pdb, *.xml | % {
cp $_.FullName (join-path $to $_.FullName.Substring($from.length))
}
|
|
Alias Copy-Item copy cp cpi |
|
Exclude ne fonctionne pas avec les répertoires |
Measure / Count
|
ls | measure
(ls | measure).Count;
|
Log
|
Start-Transcript -path $PSCommandPath.replace('.ps1', '.log')
|
|
echo '$dollar'
echo `$dollar
|
Encoding
Si la sortie affiche des caractères inattendus, utiliser l'encodage UTF-8 avec BOM.
Shutdown - Restart
|
Stop-Computer
Restart-Computer
|
Batch commands
SQL server
|
Import-Module activedirectory
Get-ADUser -filter *
|
Process
|
ps | ? name -eq 'firefox'
Get-Process | ? { $_.ProcessName -like "*git*" }
ps | ? Path -match 'firefox.exe$'
Get-Process -Id (Get-NetTCPConnection -LocalPort 135).OwningProcess
$firefox = Get-Process firefox -ErrorAction SilentlyContinue
if ($firefox) {
echo 'firefox is running'
}
start-process powershell -ArgumentList "-NoProfile -NoExit -Command echo $var"
|
|
get-service 'SQLBrowser'
$ServiceName = 'MSSQL$SQLEXPRESS'
if ((get-service $ServiceName).Status -eq 'Stopped') {
start-service $ServiceName -PassThru
}
else {
echo "$ServiceName est déjà démarré."
}
|
MessageBox
|
[void][Reflection.Assembly]::LoadWithPartialName("System.Windows.Forms")
[void][System.Windows.Forms.MessageBox]::Show("Hello !")
|
Web
|
Invoke-RestMethod http://www.domain.net/api/values | % { $_ | select Prop1, Prop2 | Out-GridView }
Invoke-RestMethod http://localhost:111/api/values -Method POST -Body @{value='2'}
Invoke-WebRequest http://localhost:111/api/values -H @{"accept"="application/xml"} | Select-Object -Expand Content
$content = (New-Object Net.WebClient).DownloadString("http://www.google.fr")
wget http://www.domain.net/file.txt -outfile folder\file.txt
|
Target HTML
|
$url = "http://www.domain.net"
$result = Invoke-WebRequest $url
$result.AllElements |
Where Class -eq "some css class" |
Select -First 1 -ExpandProperty innerText
|
|
$RegKey ="HKCU:\Control Panel\Cursors"
Get-ItemProperty -Path "HKCU:\Control Panel\Cursors" | select -ExpandProperty IBeam
Set-ItemProperty -Path $RegKey -Name IBeam -Value "%SystemRoot%\cursors\beam_r.cur"
|
Use C# code
|
Add-Type -TypeDefinition @"
public class Compute {
public int Add(int n1, int n2) {
return n1 + n2;
}
}
"@
Add-Type -Path C:\Folder\Compute.dll
$compute = New-Object Compute
$compute.Add(6, 4)
|
Exemples
Recherche de texte dans tous les fichiers - rg - ripgrep
|
afficherFunction rg {
param(
[Parameter(Mandatory=$true, ValueFromPipeline=$true)]
[string]
$pattern
)
ls -r | sls $pattern -context 2 |
foreach {
"{0} : {1:00}" -f $_.Path, $_.LineNumber
if ($_.Context.PreContext) {" {0}" -f $_.Context.PreContext }
"> {0}" -f $_.Line
if ($_.Context.PostContext) { " {0}" -f $_.Context.PostContext }
""
}
}
|
|
afficher
$Password = "Password123!@#"
$SecurePassword = $Password | ConvertTo-SecureString -AsPlainText -Force
$SecurePassword = Read-Host -Prompt "Enter password" -AsSecureString
$Credential = Get-Credential -Message "Enter password" -Username "-"
$SecurePassword = $Credential.Password
$SecureStringAsPlainText = $SecurePassword | ConvertFrom-SecureString
Set-Content "C:\Dossier\Password.txt" $SecureStringAsPlainText
$SecureStringAsPlainText = Get-Content "C:\Dossier\Password.txt"
$SecurePassword = $SecureStringAsPlainText | ConvertTo-SecureString
$Credential = New-Object PSCredential "user",$SecurePassword
$PlainPassword = $Credential.GetNetworkCredential().Password
|
|
afficher
$RegKey ="HKCU:\Control Panel\Cursors"
Set-ItemProperty -Path $RegKey -Name IBeam -Value "%SystemRoot%\cursors\beam_r.cur"
$CSharpSig = @'
[DllImport("user32.dll", EntryPoint = "SystemParametersInfo")]
public static extern bool SystemParametersInfo(
uint uiAction,
uint uiParam,
uint pvParam,
uint fWinIni);
'@
$CursorRefresh = Add-Type -MemberDefinition $CSharpSig -Name WinAPICall -Namespace SystemParamInfo –PassThru
$CursorRefresh::SystemParametersInfo(0x0057,0,$null,0)
|
|
function sha1 {
param(
[Parameter(Mandatory=$true, ValueFromPipeline=$true)]
[string]
$file
)
(Get-FileHash -Algorithm SHA1 "$file")."Hash"
}
|
|
Add-Type -TypeDefinition @"
using System.Runtime.InteropServices;
namespace WinAPI {
public class DesktopWallpaper
{
public const int SetDesktopWallpaper = 0x14;
public const int UpdateIniFile = 0x01;
public const int SendWinIniChange = 0x02;
[DllImport("user32.dll", SetLastError=true, CharSet=CharSet.Auto)]
public static extern int SystemParametersInfo (int uAction,
int uParam,
string lpvParam,
int fuWinIni);
public static void SetWallpaper(string path)
{
SystemParametersInfo(SetDesktopWallpaper, 0, path, UpdateIniFile | SendWinIniChange);
}
}
}
"@
[WinAPI.DesktopWallpaper]::SetWallpaper('C:\image.jpg')
|
find
|
Get-ChildItem -Filter "*filename*" -Recurse -File
ls -r -file *filename*
|
sed
|
File encoding is changed to UTF-8 without BOM |
|
(Get-Content file.txt) -replace 'txt_to_replace', 'replacement_text' | Set-Content file.txt
(Get-Content file.txt) -replace '^(group1).*(group2)$', '$1 text $2' | Set-Content file.txt
|
grep
|
ls | % fullname | findstr -i "\.txt\>"
ls | out-string -stream | sls "\.txt"
|
which
|
(Get-Command notepad).Source
function which($name) {
Get-Command $name | Select-Object -ExpandProperty Definition
}
|