PREGUNTES FREQÜENTS POWERSHELL EN VALENCIÀ

By | May 28, 2015

translated-valencian


Concepte : Les preguntes més freqüents sobre PowerShell.

Podeu utilitzar este llistat de les diferents formes :

  • Per a copiar / enganxar controls en un script.
  • Per a vore ràpidament la sintaxi d’un control específic.
  • Per a millorar el seu coneixement tècnic.
  • Per a descobrir nous ordres.
  • Per a preparar una entrevista de treball.

Actualitzat
2015/28/06
Autor powershell-guru.com
Font valencian.powershell-guru.com
Categories
75
Preguntes
610

ACL
Active Directory
Alias
Arrays
Browsers
Certificates
Characters
CIM
Comments
COM Objects
Compare
Computer
Credentials
CSV
Culture
Date
Drives
Environment
Errors
Event Viewer
Files
Folders
Format Operator (-f)
Functions
GPO
GUI
Hardware
Hashtables
Help
History
Jobs
Keyboard
Loops
Math
Memory
Messages
Modules
Microsoft Excel
Microsoft Exchange
Microsoft Outlook
Microsoft SharePoint
Networking
Openfiles
Operators
Parameters
Password
Powershell ISE
Printers
Processes
PSObject
Quest
Random
RDP
Regedit
Regex
Remote
Restore
Scheduled Tasks
Search
SCCM
Services
SMTP
Snapins
Sounds
Static .NET Methods
Strings
System
Try/Catch
Variables
Symantec Vault
Windows10
Windows 2012
Windows Azure
Windows Forms
WMI
XML

System

Com determinar la meua versió de PowerShell?

Com eixecutar PowerShell en una altra versió de compatibilitat amb versions anteriors?
powershell.exe -Version 2.0

Com requerir una versió PowerShell mínima (3.0 i superior) en un guió amb PowerShell?
#Requires -Version 3.0

Com requerir privilegis d’administració per a un guió amb PowerShell?

Comprovar els paràmetres d’un guió amb PowerShell?
help -Name .\Get-ExchangeEnvironmentReport.ps1 -Full

Com obtindre informacions per a l’usuari actual amb PowerShell?
[Security.Principal.WindowsIdentity]::GetCurrent()

Com crear, editar i tornar a carregar un perfil amb PowerShell?

Com fer una pausa de 5 segons / minuts en un guió amb PowerShell?
Start-Sleep -Seconds 5
Start-Sleep -Seconds 300 # 5 minutes

Com conseguir l’última arrencada amb PowerShell?
(Get-CimInstance -ClassName win32_operatingsystem).LastBootUpTime

Com conseguir diferents tipus d’acceleradors amb PowerShell?

Com enumerar els programes d’inici amb PowerShell?

Com desinstal·lar una aplicació amb PowerShell?

Com traure una captura de pantalla de tot l’escriptori o d’una finestra activa amb PowerShell?
Take-ScreenShot -Screen -File 'C:\scripts\screenshot.png' -Imagetype JPEG
Repository : Take-ScreenShot

Com obtindre el numero de missatges de cues MSMQ amb PowerShell?

Com configurar la política d’execució de PowerShell?

Com crear un accés directe amb PowerShell?

Com fixar o lliberar un programa a la barra de tasques amb PowerShell?

Com obrir una finestra de Windows Explorer amb PowerShell?
[Diagnostics.Process]::Start('explorer.exe')
Invoke-Item -Path C:\Windows\explorer.exe

Com enumerar els controladors de dispositiu amb PowerShell?
Get-WmiObject -Class Win32_PnPSignedDriver
Get-WindowsDriver -Online -All
driverquery.exe

Com crear un GUID amb PowerShell?

Com obtindre la ubicació del directori temporal per a l’usuari actual amb PowerShell?
[System.IO.Path]::GetTempPath()

Com unir-se a un camí i una ruta secundària en un sol camí amb PowerShell?
Join-Path -Path C:\ -ChildPath \windows

Com llistar tots els cmdlets “Obtenció *” amb PowerShell?
Get-Command -Verb Get

Com llistar carpetes especials del sistema amb PowerShell?

Com montar fitxers / VHD ISO amb PowerShell?
Mount-DiskImage 'D:\ISO\file.iso' # ISO
Mount-DiskImage 'D:\VHD\file.vhd' # VHD

Com comprovar les versions de .NET Framework instal·lades amb PowerShell?

Com comprovar si la versió de .NET Framework 4.5 s’instal·la amb PowerShell?
(Get-ItemProperty -Path 'HKLM:\Software\Microsoft\NET Framework Setup\NDP\v4\Full' -EA 0).Version -like '4.5*'

Com iniciar i parar una transcripció (per crear un registre de la sessió del Windows PowerShell) amb PowerShell?
Start-Transcript -Path 'C:\scripts\transcript.txt
Stop-Transcript

Com canviar el directori actual a una ubicació específica amb PowerShell?
Set-Location -Path 'C:\scripts'

Com netejar la pantalla amb PowerShell?
Clear-Host
cls # Alias

Com canviar la resolució de pantalla amb PowerShell?
Set-DisplayResolution -Width 1280 -Height 1024 -Force # Windows 2012

Com configurar la finestra de pantalla completa amb PowerShell?
mode.com 300

Com obtindre les dimensions (amplada i alçada) d’una imatge amb PowerShell?

Com obtindre la clau de producte de Windows amb PowerShell?

Perfmon

Com conseguir l’actual “% temps de processador” (mitjana) en els últims 5 segons (10 vegades) amb PowerShell?
(Get-Counter '\Processor(_total)\% Processor Time' -SampleInterval 5 -MaxSamples 10).CounterSamples.CookedValue

Assemblies

Com carregar conjunts amb PowerShell?

Com comprovar els conjunts .NET actuals carregats amb PowerShell?

Com trobar la (memòria cau de acoblats global) Ruta GAC ??amb PowerShell?

Clipboard

Com copiar els resultats al porta-retalls amb PowerShell?

Com obtindre el contingut del portapapers amb PowerShell?
Add-Type -AssemblyName PresentationCore
[Windows.Clipboard]::GetText()

Hotfixes

Com obtindre les revisions instal·lades amb PowerShell?
Get-HotFix -ComputerName $computer

Com obtindre les revisions instal·lades abans / despres d’una data específica amb PowerShell?
Get-HotFix | Where-Object -FilterScript { $_.InstalledOn -lt ([DateTime]'01/01/2015') } # Before 01/01/2015
Get-HotFix | Where-Object -FilterScript {$_.InstalledOn -gt ([DateTime]'01/01/2015')} # After 01/01/2015

Com comprovar si una revisió s’instal·la amb PowerShell?
Get-HotFix -Id KB2965142

Com obtindre les revisions instal·lades en un equip remot amb PowerShell?
Get-HotFix -ComputerName $computer

Pagefile

Com obtindre les informacions PAGEFILE amb PowerShell?
Get-WmiObject -Class Win32_PageFileusage | Select-Object -Property Name, CurrentUsage, AllocatedBaseSize, PeakUsage, InstallDate

Com obtindre la mesura recomanada (MB) per al fitxer de pàgina amb PowerShell?
[Math]::Truncate(((Get-WmiObject -Class Win32_ComputerSystem).TotalPhysicalMemory) / 1MB) * 1.5

Com crear un fitxer de pàgina (4096 MB) en D: conduir amb PowerShell?

Com borrar un fitxer de pàgina en la unitat C: amb PowerShell?

Maintenance

Com comprovar la fragmentació d’una unitat amb PowerShell?

Com comprovar l’espai en disc de les unitats amb PowerShell?

Up


Files

Com obrir un fitxer amb PowerShell?
Invoke-Item -Path 'C:\scripts\file.txt'
.'C:\scripts\file.txt'

Com llegir un fitxer amb PowerShell?
Get-Content -Path 'C:\scripts\file.txt'
gc "C:\scripts\file.txt" # Alias

Com escriure l’eixida a un fitxer amb PowerShell?
'Line1', 'Line2', 'Line3' | Out-File -FilePath 'C:\scripts\file.txt'
'Line1', 'Line2', 'Line3' | Add-Content -Path file.txt

Com obtindre el nom complet del fitxer de script actual amb PowerShell?
$MyInvocation.MyCommand.Path

Com comprimir / zip fitxers amb PowerShell?
Add-Type -AssemblyName 'System.IO.Compression.Filesystem'
[System.IO.Compression.ZipFile]::CreateFromDirectory($folder,$fileZIP)

Com descomprimir / unzip fitxers amb PowerShell?
Add-Type -AssemblyName 'System.IO.Compression.Filesystem'
[System.IO.Compression.ZipFile]::ExtractToDirectory($fileZIP, $folder)

Com vore els fitxers en un fitxers ZIP amb PowerShell?
Add-Type -AssemblyName 'System.IO.Compression.Filesystem'
[System.IO.Compression.ZipFile]::OpenRead($fileZIP)

Com visualitzar la mida d’un fitxers en KB amb PowerShell?
(Get-ChildItem -Path .\winsrv.dll).Length /1KB
(Get-ChildItem -Path .\winsrv.dll).Length /1MB
(Get-ChildItem -Path .\winsrv.dll).Length /1GB

Com cercar arxius de més o menys d’1 GB amb PowerShell?

Com visualitzar el nom d’un fitxers sense l’extensió amb PowerShell?
[System.IO.Path]::GetFileNameWithoutExtension('C:\Windows\system32\calc.exe') # Return calc

Com mostrar l’extensió d’un fitxers amb PowerShell?
[System.IO.Path]::GetExtension('C:\scripts\file.txt') # Return .txt

Com obtindre la versió d’un fitxer d’un fitxer amb PowerShell?

Com obtindre el hash d’un fitxer PowerShell?
(Get-FileHash $file).Hash

Com obtindre la suma de comprovació MD5 / SHA1 d’un fitxers amb PowerShell?
Get-FileHash $file -Algorithm MD5
Get-FileHash $file -Algorithm SHA1

Com mostrar els fitxers ocults amb PowerShell?

Com comprovar si un fitxer té una extensió amb PowerShell?

Com configurar un fitxer com de només lectura amb PowerShell?
Set-ItemProperty -Path .\file.txt -Name IsReadOnly -Value $true

Com canviar l’atribut LastWriteTime a la setmana passada per un fitxer amb PowerShell?
Set-ItemProperty -Path .\file.txt -Name LastWriteTime -Value ((Get-Date).AddDays(-7))
If not working, use Nirsoft tool: BulkFileChanger.

Com crear un nou fitxers amb PowerShell?
New-Item -ItemType File -Path 'C:\scripts\file.txt' -Value 'FirstLine'

Com canviar el nom d’un fitxers amb PowerShell?
Rename-Item -Path 'C:\scripts\file.txt' -NewName 'C:\scripts\powershellguru2.txt'

Com incrementa / expandeix canviar el nom de diversos fitxers amb PowerShell?
Get-ChildItem -Path C:\scripts\txt | Rename-Item -NewName { $_.Name -replace ' ', '_' }

Com borrar un fitxer amb PowerShell?
Remove-Item -Path 'C:\scripts\file.txt'

Com visualitzar les 10 últimes línies d’un fitxer amb PowerShell?
Get-Content -Path 'C:\scripts\log.txt' -Tail 10

Com desbloquejar diversos fitxer d’una carpeta amb PowerShell?
Get-ChildItem -Path 'C:\scripts\Modules' | Unblock-File

Com suprimir les línies buides d’un fitxer amb PowerShell?
(Get-Content -Path file.txt) | Where-Object -FilterScript {$_.Trim() -ne '' } | Set-Content -Path file.txt

Com comprovar si existeix un arxiu amb PowerShell?

Com a descarregar el fitxer més nou / antic creat en una carpeta amb PowerShell?

Com suprimir les línies duplicades d’un fitxer amb PowerShell?

Com obtindre els fitxers creats més / menys d’1 mes en una carpeta amb PowerShell?

Com obtindre els fitxers creats de fa més / o menys 1 any en una carpeta amb PowerShell?

Com exportar el valor d’una variable en un fitxer amb PowerShell?
Set-Content -Path file.txt -Value $variable

Com comptar el nombre de fitxers (* .txt) en una carpeta amb PowerShell?

Com cercar una cadena dins de diversos arxius amb PowerShell?
Select-String -Path 'C:\*.txt' -Pattern 'Test'

Com visualitzar la primera / última línia / d’un arxiu amb PowerShell?

Com mostrar un numero de línia específica d’un arxiu amb PowerShell?

Com comptar el numero de línies d’un fitxer amb PowerShell?

Com comptar el numero de caràcters i paraules d’un fitxer amb PowerShell?

Com descarregar un arxiu amb PowerShell?
Invoke-WebRequest -Uri 'http://www.nirsoft.net/utils/searchmyfiles.zip' -OutFile 'C:\tools\searchmyfiles.zip'

Com mostrar la ruta completa d’un arxiu amb PowerShell?
Resolve-Path -Path .\script.ps1 # Return C:\Scripts\script.ps1

Copy

Com copiar un fitxer a una carpeta amb PowerShell?
Copy-Item -Path 'C:\source\file.txt' -Destination 'C:\destination'

Com copiar un arxiu a diverses carpetes en PowerShell?

Com copiar diversos arxius a una carpeta en PowerShell?
Get-ChildItem -Path 'C:\source' -Filter *.txt | Copy-Item -Destination 'C:\destination'

Up


Active Directory

Domain & Forest

Computers

Groups

Organizational Unit (OU)

Users

Domain & Forest

Com trobar servidors de catàleg global a l’Active Directory amb PowerShell?
[System.DirectoryServices.ActiveDirectory.Forest]::GetCurrentForest().GlobalCatalogs

Com cercar llocs a l’Active Directory amb PowerShell?
[System.DirectoryServices.ActiveDirectory.Forest]::GetCurrentForest().Sites

Com cercar el controlador de domini actual amb PowerShell?
(Get-ADDomainController).HostName

Com cercar tots els controladors de domini en un domini amb PowerShell?

Com cercar els errors de replicació AD amb PowerShell?
Get-ADReplicationFailure dc02.domain.com # Windows 8 and 2012

Com cercar el periòde de rebuig per al bosc de l’Active Directory amb PowerShell?

Com obtindre detalls del un bosc / domini a l’Active Directory amb PowerShell?

Com obtindre la ruta del contenidor dels “Objectes suprimits” de l’Active Directory amb PowerShell?
(Get-ADDomain).DeletedObjectsContainer

Com habilitar la característica AD de la Paperera de reciclatge a l’Active Directory amb PowerShell?

Com restaurar un compte AD de la Paperera de reciclatge a l’Active Directory amb PowerShell?
Get-ADObject -Filter 'samaccountname -eq "powershellguru"' -IncludeDeletedObjects | Restore-ADObject

Com cercar les funcions FSMO amb PowerShell?

Com establir connexió a un controlador de domini específic amb PowerShell?
Get-ADUser -Identity $user -Server 'serverDC01'

Com conseguir el servidor d’inici de sessió actual amb PowerShell?

Com fer “gpupdate” en un equip amb PowerShell?
Invoke-GPUpdate -Computer $computer -Force -RandomDelayInMinutes 0 # Windows 2012

Groups

Com crear un nou grup a l’Active Directory amb PowerShell?

Com suprimir un grup a l’Active Directory amb PowerShell?
Remove-ADGroup -Identity 'PowershellGuru'

Com afegir un usuari a un grup a l’Active Directory amb PowerShell?
Add-ADGroupMember "Powershell Guru" -Members powershellguru

Com suprimir un usuari d’un grup a l’Active Directory amb PowerShell?
Remove-ADGroupMember 'Powershell Guru' -Members powershellguru

Com cercar grups buits (sense membres) a l’Active Directory amb PowerShell?
Get-ADGroup -Filter * -Properties Members | Where-Object -FilterScript {-not $_.Members}

Com comptar els grups buits (sense membres) a l’Active Directory amb PowerShell?
(Get-ADGroup -Filter * -Properties Members | Where-Object -FilterScript {-not $_.Members}).Count

Com arribar als membres d’un grup a l’Active Directory amb PowerShell?

Com arribar als membres d’un grup amb participants recursius a l’Active Directory amb PowerShell?

Com comptar el nombre de membres d’un grup amb / o sense participants recursius a l’Active Directory amb PowerShell?

Users

Com utilitzar un comodí en el filtre de “Get-ADUser” a l’Active Directory amb PowerShell?

Com moure un usuari a un altre OU en Active Directory amb PowerShell?
Move-ADObject -Identity $dn -TargetPath 'OU=myOU,DC=domain,DC=com'

Com cercar tota la MemberOf (imbricada) per a un usuari amb PowerShell?
Get-ADGroup -LDAPFilter "(member:1.2.840.113556.1.4.1941:=$($dn))"

Com obtindre el MemberOf (nom curt / truncat) per a un usuari amb PowerShell?
(Get-ADUser $user -Properties MemberOf).MemberOf | ForEach-Object -Process {($_ -split ',')[0].Substring(3)} | Sort-Object

Com renombrar (fullname), DisplayName, GivenName (FirstName) i Cognom (Cognom) per un compte d’usuari a l’Active Directory amb PowerShell?

Com modificar la descripció, Oficina i (Tele) número de telèfon per un compte d’usuari a l’Active Directory amb PowerShell?
Set-ADUser $samAccountName -Description 'IT Consultant' -Office 'Building B' -OfficePhone '12345'

Com establir la data de caducitat a “31/12/2015” o “Mai” per un compte d’usuari a l’Active Directory amb PowerShell?

Com desbloquejar un compte d’usuari a l’Active Directory amb PowerShell?
Unlock-ADAccount $samAccountName

Com activar / desactivar un compte d’usuari a l’Active Directory amb PowerShell?

Com suprimir un compte d’usuari a l’Active Directory amb PowerShell?
Remove-ADUser $samAccountName

Com restablir una contrasenya per un compte d’usuari a l’Active Directory amb PowerShell?

Com restablir una contrasenya per a diversos comptes d’usuari (paquet) a l’Active Directory amb PowerShell?

Com cercar el propietari d’un arxiu a l’ Active Directory amb PowerShell?

Com cercar l’ OU (unitat organitzativa) per a un usuari a l’Active Directory amb PowerShell?
[regex]::match("$((Get-ADUser $user -Properties DistinguishedName).DistinguishedName)",'(?=OU=)(.*\n?)').value

Com cercar comptes d’usuaris amb discapacitat a l’Active Directory amb PowerShell?

Com cercar comptes d’usuaris expirats a l’Active Directory amb PowerShell?
Search-ADAccount -AccountExpired

Com cercar comptes d’usuaris bloquejats a l’Active Directory amb PowerShell?
Search-ADAccount -LockedOut

Com cercar el SID d’un compte d’usuari a l’Active Directory amb PowerShell?
(Get-ADUser $user -Properties SID).SID.Value

Com convertir un nom d’usuari a SID a l’Active Directory amb PowerShell?

Com convertir un SID de nom d’usuari en Active Directory amb PowerShell?

Com dividir el nom complet d’un compte d’usuari a l’ Active Directory amb PowerShell?

Com cercar la data de creació / modificació d’un compte d’usuari a l’ Active Directory amb PowerShell?
Get-ADUser -Identity $user -Properties whenChanged, whenCreated | Format-List -Property whenChanged, whenCreated

Com mostrar les propietats opcionals i obligatories per al “Usuari” classe amb Active Directory amb PowerShell?

Com obtindre la ruta LDAP per a un usuari a l’Active Directory amb PowerShell?

Com modificar el CN ??(Nom Canònic) per a un usuari a l’Active Directory amb PowerShell?
Rename-ADObject $((Get-ADUser $user -Properties DistinguishedName).DistinguishedName) -NewName 'Test Powershell'

Com conseguir la unitat organitzativa (OU) pare d’un usuari a l’Active Directory amb PowerShell?

Com conseguir el propietari d’un usuari (el qual va crear el compte) a l’Active Directory amb PowerShell?

Com convertir l’atribut pwdLastSet per a un usuari a l’Active Directory amb PowerShell?

Computers

Com provar el canal segur entre l’equip local i el domini amb PowerShell?
Test-ComputerSecureChannel

Com reparar el canal segur entre l’equip local i el domini amb PowerShell?
Test-ComputerSecureChannel -Repair

Com desactivar un compte d’equip en Active Directory amb PowerShell?
Disable-ADAccount $computer

Com cercar ordinadors amb un sistema operatiu específic a l’Active Directory amb PowerShell?

Organizational Unit (OU)

Com crear una unitat organitzativa (OU) a l’Active Directory amb PowerShell?
New-ADOrganizationalUnit -Name 'TEST' -Path 'DC=domain,DC=com'

Com aconseguir els detalls de la la unitat organitzativa (OU) a l’Active Directory amb PowerShell?
Get-ADOrganizationalUnit 'OU=TEST,DC=domain,DC=com' -Properties *

Com canviar la descripció d’una unitat organitzativa (OU) a l’Active Directory amb PowerShell?
Set-ADOrganizationalUnit 'OU=TEST,DC=domain,DC=com' -Description 'My description'

Com activar / desactivar una unitat organitzativa (OU) d’un esborrat accidental a l’Active Directory amb PowerShell?

Com habilitar l’eliminació accidental de tota la unitat organitzativa (OU) a l’Active Directory amb PowerShell?

Com suprimir una unitat organitzativa (OU), protegit de l’eliminació accidental en Active Directory amb PowerShell?

Com convertir un DistinguishedName d’unitat organitzativa (OU) per canonicalName amb Active Directory amb PowerShell?

Com llistar les unitats organitzatives (OU) buides amb PowerShell?

Com conseguir el gerent d’un grup amb PowerShell?
(Get-ADGroup $dn -Properties Managedby).Managedby

Up


Regex (Regular Expression)

Com extraure una direcció IP v4 (80.80.228.8) amb Regex amb PowerShell?
$example = 'The IP address is 80.80.228.8'
$ip = [regex]::match($example,'\b\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}\b').value

Com extraure una direcció MAC (C0-D9-62-39-61-2D) amb separador “-” amb Regex amb PowerShell?
$example = 'The MAC address is C0-D9-62-39-61-2D'
$mac = [regex]::match($example,'([0-9A-F]{2}[-]){5}([0-9A-F]{2})').value

Com extraure una direcció MAC (C0: D9: 62: 39: 61: 2D) amb separador “:” amb Regex amb PowerShell?
$example = 'The MAC address is C0:D9:62:39:61:2D'
$mac = [regex]::match($example,'((\d|([a-f]|[A-F])){2}:){5}(\d|([a-f]|[A-F])){2}').value

Com extraure una data (2015.02.10) amb Regex amb PowerShell?
$example = 'The date is 10/02/2015'
$date = [regex]::match($example,'(\d{2}\/\d{2}\/\d{4})').value

Com extraure un URL (www.powershell-guru.com) amb Regex amb PowerShell?
$example = 'The URL is www.powershell-guru.com'
$url = [regex]::match($example,'[a-z]+[:.].*?(?=\s)').value

Com extraure un correu electrònic (user@domain.com) amb Regex amb PowerShell?
$example = 'The email is user@domain.com'
$email = [regex]::match($example,'(?i)\b[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,4}\b').value

Com extraure “guru” de l’exemple de cadena amb Regex amb PowerShell?
$example = 'www.powershell-guru.com'
[regex]::match($example,'(?<=-)(.*\n?)(?=.com)').value

Com extraure “guru.com” l’exemple de cadena amb Regex amb PowerShell?
$example = 'www.powershell-guru.com'
[regex]::match($example,'(?<=-)(.*\n?)(?<=.)').value

Com extraure “powershell-guru.com” l’exemple de cadena amb Regex amb PowerShell?
$example = 'www.powershell-guru.com'
[regex]::match($example,'(?<=www.)(.*\n?)').value

Com extraure “123” en l’exemple de cadena amb Regex amb PowerShell?
$example = 'Powershell123'
[regex]::match($example,'(\d+)').value

Com extraure “$” (signe de dòlar) a partir de l’exemple de cadena amb Regex amb PowerShell?
$example = 'Powershell`$123'
[regex]::match($example,'(\$)').value

Com reemplaçar un caràcter (* .com) amb un altre (* .fr) en una cadena amb Regex amb PowerShell?
$example = 'www.powershell-guru.com'
[regex]::Replace($example, '.com','.fr')

Com escapar d’una cadena amb Regex amb PowerShell?
[regex]::Escape('\\server\share')

Up


Memory

Com forçar una col·lecció de memòria pel recol·lector d’escombraries amb PowerShell?
[System.GC]::Collect()
[System.GC]::WaitForPendingFinalizers()

Com obtindre la mida de la RAM d’un ordinador amb PowerShell?

Up


Date

Com obtindre la data actual amb PowerShell?
Get-Date
[Datetime]::Now

Com fer visible la data en diferents formats amb PowerShell?

Com convertir una data (data i hora) a la data (String) amb PowerShell?
$datetimeToString = '{0:dd/MM/yy}' -f (Get-Date 30/01/2015)
$datetimeToString = (Get-Date 31/01/2015).ToShortDateString()

Com convertir una data (String) fins a la data (data i hora) amb PowerShell?
$stringToDatetime = [Datetime]::ParseExact('30/01/2015', 'dd/MM/yyyy', $null)

Com calcular la diferència (nombre de dies, hores, minuts o segons) entre dues dates amb PowerShell?
(New-TimeSpan -Start $dateStart -End $dateEnd).Days
(New-TimeSpan -Start $dateStart -End $dateEnd).Hours
(New-TimeSpan -Start $dateStart -End $dateEnd).Minutes
(New-TimeSpan -Start $dateStart -End $dateEnd).Seconds

Com comparar dues dates amb PowerShell?
(Get-Date 2015-01-01) -lt (Get-Date 2015-01-30) # True
(Get-Date 2015-01-01) -gt (Get-Date 2015-01-30) # False

Com ordenar una sèrie de dates com a data i hora amb PowerShell?
$arrayDate | Sort-Object -Property {$_ -as [Datetime]}

Com iniciar i parar un cronòmetre amb PowerShell?
$chrono = [Diagnostics.Stopwatch]::StartNew()
$chrono.Stop()
$chrono

Com obtindre el dia actual de la setmana amb PowerShell?
(Get-Date).DayOfWeek #Sunday

Com obtindre la data d’ahir amb PowerShell?
(Get-Date).AddDays(-1)

Com obtindre el nombre de dies en un mes (al febrer de 2015) amb PowerShell?
[DateTime]::DaysInMonth(2015, 2)

Com saber si existeix un any de traspàs amb PowerShell?
[DateTime]::IsLeapYear(2015)

Com llistar zones horàries amb PowerShell?
[System.TimeZoneInfo]::GetSystemTimeZones()

Up


Networking

Com codificar (a format ASCII) i descodificar un URL amb PowerShell?

Quals són els equivalents dels controls de natius amb PowerShell?

Com obtindre les direccions IP amb PowerShell?
Get-NetIPAddress # Windows 8.1 & Windows 2012
Get-NetIPConfiguration # Windows 8.1 & Windows 2012

Com desactivar la direcció v6 IP (IPv6) amb PowerShell?

Com validar una direcció v4 IP (IPv4) amb PowerShell?
if([ipaddress]'10.0.0.1'){'validated'}

Com cercar la direcció IP externa amb PowerShell?

Com cercar el nom convidat d’una direcció IP amb PowerShell?
([System.Net.Dns]::GetHostEntry($IP)).Hostname

Com cercar la direcció a IP d’un nom de host amb PowerShell?
([System.Net.Dns]::GetHostAddresses($computer)).IPAddressToString

Com cercar el nom complet d’un nom convidat amb PowerShell?
[System.Net.Dns]::GetHostByName($computer).HostName

Com cercar la configuració de xarxa (IP, subxarxa, Gateway i DNS) amb PowerShell?

Com cercar la direcció MAC amb PowerShell?
Get-CimInstance win32_networkadapterconfiguration | Select-Object -Property Description, Macaddress
Get-WmiObject -Class win32_networkadapterconfiguration | Select-Object -Property Description, Macaddress

Com fer un so estrident a un ordinador amb PowerShell?

Com comprovar si un ordinador està connectat a Internet amb PowerShell?

Com fer una cerca “whois” per a una pàgina web amb PowerShell?
$whois = New-WebServiceProxy 'http://www.webservicex.net/whois.asmx?WSDL'
$whois.GetWhoIs('powershell-guru.com')

Com obtindre detalls d’IP pública (Geolocalització) amb PowerShell?

Com comprovar si un port està obert / tancat amb PowerShell?
New-Object -TypeName Net.Sockets.TcpClient -ArgumentList $computer, 135

Com fer tracert amb PowerShell?
Test-NetConnection www.google.com -TraceRoute

Com corregir el perfil de connexió de xarxa a casa amb PowerShell?
Get-NetAdapter | Format-Table -Property Name, InterfaceDescription, ifIndex -AutoSize # Windows 8.1
Set-NetConnectionProfile -InterfaceIndex 6 -NetworkCategory Private

Com mostrar les connexions del port TCP amb PowerShell?
netstat.exe -ano
Get-NetTCPConnection #Windows 8 and 2012

Com acurtar un URL llarga en una diminuta URL amb PowerShell?
$url = 'www.powershell-guru.com'
$tiny = Invoke-RestMethod -Uri "http://tinyurl.com/api-create.php?url=$url"

Com obtindre la configuració de proxy amb PowerShell?
Get-ItemProperty -Path HKCU:"Software\Microsoft\Windows\CurrentVersion\Internet Settings"

DNS

Com comprovar la memòria cau de DNS a l’equip local amb PowerShell?
ipconfig.exe /displaydns
Get-DnsClientCache #Windows 8 and 2012

Com esborrar la memòria cau DNS a l’equip local amb PowerShell?
ipconfig.exe /flushdns
Start-Process -FilePath ipconfig -ArgumentList /flushdns -WindowStyle Hidden
Clear-DnsClientCache #Windows 8 and 2012

Com esborrar la memòria cau DNS en equips remots amb PowerShell?
Invoke-Command -ScriptBlock {Clear-DnsClientCache} -ComputerName computer01, computer02

Com llegir el fitxer Hosts amb PowerShell?
Get-Content -Path 'C:\Windows\system32\drivers\etc\hosts'

Up


Password

Com generar una contrasenya aleatòria amb PowerShell?
[Reflection.Assembly]::LoadWithPartialName('System.Web')
[System.Web.Security.Membership]::GeneratePassword(30,2)

Com canviar la contrasenya d’administrador local per al servidor remot amb PowerShell?
$admin = [ADSI]('WinNT://server01/administrator,user')
$admin.SetPassword($password)
$admin.SetInfo()

Com cercar la data d’expiració de la contrasenya d’un compte en Active Directory amb PowerShell?

Up


Printers

Com llistar totes les impressores d’un servidor específic amb PowerShell?
Get-WmiObject -Query 'Select * From Win32_Printer' -ComputerName $computer

Com llistar tots els ports d’un servidor específic amb PowerShell?
Get-WmiObject -Class Win32_TCPIPPrinterPort -Namespace 'root\CIMV2' -ComputerName $computer

Com canviar el comentari / ubicació per a una impressora amb PowerShell?

Com suprimir (cancel·lar tots els treballs) a una impressora amb PowerShell?
$printer = Get-WmiObject -Class win32_printer -Filter "Name='HP Deskjet 2540 series'"
$printer.CancelAllJobs()

Com imprimir una pàgina de prova per a una impressora amb PowerShell?
$printer = Get-WmiObject -Class win32_printer -Filter "Name='HP Deskjet 2540 series'"
$printer.PrintTestPage()

Com conseguir les cues d’impressió per a impressores amb PowerShell?

Up


Regedit

Read

Com llistar seccions del Registre amb PowerShell?
Get-ChildItem -Path Registry::

Com obtindre els valors de registre i tipus de valor amb PowerShell?

Com llistar el registre de les subclaus de clau amb PowerShell?

Com llistar el registre de les subclaus de clau en forma recursiva amb PowerShell?
Get-ChildItem -Path 'HKLM:\SYSTEM' -Recurse -ErrorAction SilentlyContinue

Com cercar subclaus amb un nom específic amb PowerShell?
Get-ChildItem -Path 'HKLM:\SOFTWARE' -Include *Plugin* -Recurse -ErrorAction SilentlyContinue

Com tornar només el nom del registre de les subclaus amb PowerShell?
(Get-ChildItem -Path 'HKLM:\SYSTEM').Name # Return HKEY_LOCAL_MACHINE\SYSTEM\ControlSet
Get-ChildItem -Path 'HKLM:\SYSTEM' -Name # Return ControlSet

Com llistar els valors de registre amb PowerShell?
Get-ItemProperty -Path 'HKLM:\SOFTWARE\Microsoft\Windows NT\CurrentVersion'

Com llegir un valor de registre específic amb PowerShell?
(Get-ItemProperty -Path 'HKLM:\SOFTWARE\Microsoft\Windows NT\CurrentVersion').ProductName

Com llegir un valor específic del registre en l’equip remot amb PowerShell?

Write

Com crear una nova clau de registre amb PowerShell?
New-Item -Path 'HKCU:\Software\MyApplication'

Com crear un valor de registre amb PowerShell?
New-ItemProperty -Path 'HKCU:\Software\MyApplication' -Name 'Version' -Value '1.0'

Com modificar un valor de registre existent amb PowerShell?
Set-ItemProperty -Path 'HKCU:\Software\MyApplication' -Name 'Version' -Value '2.0'

Delete

Com suprimir un valor de registre amb PowerShell?
Remove-ItemProperty -Path 'HKCU:\Software\MyApplication' -Name 'Version'

Com suprimir una clau de registre amb PowerShell?
Remove-Item -Path 'HKCU:\Software\MyApplication' -Force

Test

Com provar si hi ha una clau del Registre amb PowerShell?
Test-Path -Path 'HKCU:\Software\MyApplication'

Com provar si hi ha un valor de registre amb PowerShell?
(Get-Item -Path 'HKCU:\Software\MyApplication').GetValueNames() -contains 'Version'

Up


Strings

Com suprimir caràcters d’espai en blanc des del principi d’una cadena amb PowerShell?
$string = ' PowershellGuru'
$string = $string.TrimStart()

Com suprimir caràcters d’espai en blanc del final d’una cadena amb PowerShell?
$string = 'PowershellGuru '
$string = $string.TrimEnd()

Com suprimir caràcters d’espai en blanc (començar i acabar) d’una cadena amb PowerShell?
$string = ' PowershellGuru '
$string = $string.Trim()

Com convertir una cadena a majúscules amb PowerShell?
$string = 'powershellguru'
$string = $string.ToUpper()

Com convertir una cadena a minúscules amb PowerShell?
$string = 'POWERSHELLGURU'
$string = $string.ToLower()

Com seleccionar la subcadena “PowerShell” de la cadena “PowershellGuru” amb PowerShell?
$string.Substring(0,10)

Com seleccionar la subcadena “guru” de la cadena “PowershellGuru” amb PowerShell?
$string.Substring(10)

Com seleccionar el nombre “123” de “Powershell123Guru” amb PowerShell?
$string = 'Powershell123Guru'
[regex]::match($string,'(\d+)').value

Com obtindre l’índex de base zero de “Guru” del “PowershellGuru” cadena amb PowerShell?
$string.IndexOf('Guru') # 10

Com comprovar si una cadena és nula o buida amb PowerShell?
$string = $null
$string = ''
[string]::IsNullOrEmpty($string)

Com comprovar si una cadena nul·la, buida, o es compon només de caràcters d’espai en blanc amb PowerShell?
$string = $null
$string = ''
$string = ' '
[string]::IsNullOrWhiteSpace($string)

Com comprovar si una cadena conté una carta específica amb PowerShell?
$string = 'PowershellGuru'
$string.Contains('s')
[regex]::match($string,'s').Success

Com retornar la longitud d’una cadena amb PowerShell?
$string.Length

Com conectar dues cadenes amb PowerShell?

Com fer coincidir un o diversos suports “[]” en una cadena amb PowerShell?
$string = '[PowershellGuru]'
$string -match '\[' # Only 1
$string -match '\[(.*)\]' # Several

Com fer coincidir un o diversos parèntesi “()” en una cadena amb PowerShell?
$string = '(PowershellGuru)'
$string -match '\(' # Only 1
$string -match '\((.*)\)' # Several

Com fer coincidir una o diverses claus “{}” en una cadena amb PowerShell?
$string = '{PowershellGuru}'
$string -match '\{' # Only 1
$string -match '\{(.*)\}' # Several

Com fer coincidir un o diversos suports d’angle “& lt; & gt;” en una cadena amb PowerShell?
$string = ''
$string -match '\<' # Only 1
$string -match "\<(.*)\>" # Several

Com fer coincidir les lletres minúscules (abc) en una cadena amb PowerShell?
$string = 'POWERSHELLGURU'
$string -cmatch "^[a-z]*$" #False

Com fer coincidir letras majúscules (ABC) en una cadena amb PowerShell?
$string = 'powershellguru'
$string -cmatch "^[A-Z]*$" #False

Com fer coincidir “[p” (p minúscula) en una cadena amb PowerShell?
$string = '[powershellGuru]'
$string -cmatch '\[[a-z]\w+' #True

Com fer coincidir (P majúscula) “[P” en una cadena amb PowerShell?
$string = '[PowershellGuru]'
$string -cmatch '\[[A-Z]\w+' #True

Com reemplaçar una línia amb una altra línia amb PowerShell?
$a = 'Line A'
$b = 'Line B'
$a = $a -replace $a, $b

Com transformar una operació de divisió a una cadena (Percentatge) amb PowerShell?
(1/2).ToString('P')

Com ordenar cadenes que contenen nombres amb PowerShell?

Com seleccionar l’última paraula d’una frase amb PowerShell?
$sentence = 'My name is Test Powershell'
$sentence.Split(' ')[-1] # Returns Powershell

Com conseguir la paraula més gran d’una frase amb PowerShell?
$sentence = 'My name is Test Powershell'
$sentence.Split(' ') | Sort-Object -Property Length | Select-Object -Last 1 # Returns Powershell

Com comptar el nombre de vegades que una cadena és present dins d’una frase amb PowerShell?
$sentence = 'test test test Powershell'
[regex]::Matches($sentence, 'test').Count # Returns 3

Com copiar cada caràcter en una cadena a una matriu de caràcters amb PowerShell?

Com convertir la primera lletra en majúscules d’una cadena amb PowerShell?

Com afegir el control de l’encoixina (esquerra o dreta) una cadena amb PowerShell?

Com codificar i descodificar una cadena de base 64 amb PowerShell?

Com convertir un nombre a binari (de i des de) amb PowerShell?

Com tornar només a la carpeta principal a un camí amb PowerShell?

Com tornar només l’últim element d’un camí amb PowerShell?

Up


Math

Com llistar els mètodes de la classe System.Math amb PowerShell?
[System.Math] | Get-Member -Static -MemberType Method

Com retornar el valor absolut amb PowerShell?
[Math]::Abs(-12) #Returns 12
[Math]::Abs(-12.5) # Returns 12.5

Com retornar l’angle el si és el nombre especificat amb PowerShell?
[Math]::ASin(1) #Returns 1,5707963267949

Com retornar el sostre amb PowerShell?
[Math]::Ceiling(1.4) #Returns 2
[Math]::Ceiling(1.9) #Returns 2

Com retornar el pis amb PowerShell?
[Math]::Floor(1.4) #Returns 1
[Math]::Floor(1.9) #Returns 1

Com retornar la (base e) natural del logaritme d’un nombre específic amb PowerShell?
[Math]::Log(4) #Returns 1,38629436111989

Com retornar el logaritme en base 10 d’un nombre específic amb PowerShell?
[Math]::Log10(4) #Returns 0,602059991327962

Com retornar un màxim de dos valors amb PowerShell?
[Math]::Max(2,4) #Returns 4
[Math]::Max(-2,-4) #Returns -2

Com retornar un mínim de dos valors amb PowerShell?
[Math]::Min(2,4) #Returns 2
[Math]::Max(-2,-4) #Returns -4

Com retornar un nombre elevat a la potència especificada amb PowerShell?
[Math]::Pow(2,4) #Returns 16

Com retornar un valor decimal en el valor integral propera amb PowerShell?
[Math]::Round(3.111,2) #Returns 3,11
[Math]::Round(3.999,2) #Returns 4

Com retornar la part entera d’un nombre decimal especificat amb PowerShell?
[Math]::Truncate(3.111) #Returns 3
[Math]::Truncate(3.999) #Returns 3

Com retornar l’arrel quadrada d’un nombre especificat amb PowerShell?
[Math]::Sqrt(16) #Returns 4

Com retornar la constant PI amb PowerShell?
[Math]::Pi #Returns 3,14159265358979

Com retornar la base logaritme natural (constant i) amb PowerShell?
[Math]::E #Returns 2,71828182845905

Com comprovar si un nombre és parell o senar amb PowerShell?
[bool]($number%2)

Up


Hashtables

Com crear una taula buida hash amb PowerShell?
$hashtable = @{}
$hashtable = New-Object -TypeName System.Collections.Hashtable

Com crear una taula buida hash amb elements amb PowerShell?

Com crear una taula hash ordenada per clau / nom (diccionari ordenat) amb elements amb PowerShell?

Com afegir elements (parell clau-valor) a una taula hash amb PowerShell?
$hashtable.Add('Key3', 'Value3')

Com obtindre un valor específic d’una taula hash amb PowerShell?
$hashtable.Key1
$hashtable.Get_Item('Key1')

Com obtindre el valor mínim d’una taula hash amb PowerShell?

Com obtindre el màxim valor d’una taula hash amb PowerShell?

Com modificar els elements d’una taula hash amb PowerShell?
$hashtable.Set_Item('Key1', 'Value1Updated')

Com suprimir elements en una taula hash amb PowerShell?
$hashtable.Remove('Key1')

Com esborrar una taula hash amb PowerShell?
$hashtable.Clear()

Com comprovar la presència d’una clau / valor específic en una taula hash amb PowerShell?
$hashtable.ContainsKey('Key3')
$hashtable.ContainsValue('Value3')

Com ordenar per clau / valor en una taula hash amb PowerShell?
$hashtable.GetEnumerator() | Sort-Object -Property Name
$hashtable.GetEnumerator() | Sort-Object -Property Value -Descending

Up


Arrays

Com crear una matriu buida amb PowerShell?
$array = @()
$array = [System.Collections.ArrayList]@()

Com crear una matriu amb elements amb PowerShell?
$array = @('A', 'B', 'C')
$array = 'A', 'B', 'C'
$array = 'a,b,c'.Split(',')
$array = .{$args} a b c
$array = echo a b c

Com afegir elements a una matriu amb PowerShell?
$array += 'D'
[void]$array.Add('D')

Com modificar un element d’una matriu amb PowerShell?
$array[0] = 'Z' # 1st item[0]

Com comprovar la mesura d’una matriu amb PowerShell?
$array = 'A', 'B', 'C'
$array.Length # Returns 3

Com recuperar un element / diversos / tots els elements d’una matriu amb PowerShell?
$array = @('A', 'B', 'C')
$array[0] # One item (A)
$array[0] + $array[2] # Several items (A,C)
$array # All items (A,B,C)

Com suprimir elements buits en una matriu amb PowerShell?
$array = @('A', 'B', 'C', '')
$array = $array.Split('',[System.StringSplitOptions]::RemoveEmptyEntries) | Sort-Object # A,B,C

Com comprovar si hi ha un element d’una matriu amb PowerShell?
$array = @('A', 'B', 'C')
'A' | ForEach-Object -Process {$array.Contains($_)} # Returns True
'D' | ForEach-Object -Process {$array.Contains($_)} # Returns False

Com trobar el número d’índex d’un element d’una matriu amb PowerShell?
$array = @('A', 'B', 'C')
[array]::IndexOf($array,'A') # Returns 0

Com invertir l’ordre dels elements d’una matriu amb PowerShell?
$array = @('A', 'B', 'C')
[array]::Reverse($array) # C,B,A

Com generar un element d’atzar d’una matriu amb PowerShell?
$array | Get-Random

Com ordenar una matriu en ordre ascendent / descendent amb PowerShell?
$array = @('A', 'B', 'C')
$array | Sort-Object # A,B,C
$array | Sort-Object -Descending # C,B,A

Com comptar el nombre d’elements d’una matriu amb PowerShell?
$array.Count

Com afegir una matriu per una altra amb PowerShell?
$array1 = 'A', 'B', 'C'
$array2 = 'D', 'E', 'F'
$array3 = $array1 + $array2 # A,B,C,D,E,F

Com trobar duplicacions d’una matriu amb PowerShell?
$array = 'A', 'B', 'C', 'C'
($array | Group-Object | Where-Object -FilterScript {$_.Count -gt 1}).Values # Returns C

Com eliminar duplicacions d’una matriu amb PowerShell?
$array = 'A', 'B', 'C', 'C'
$array = $array | Select-Object -Unique
$array # Returns A,B,C

Com crear una matriu amb els elements a partir d’un prefix (“user01”, “user02”, …, “user10”) amb PowerShell?
$array = 1..10 | ForEach-Object -Process { "user$_" }

Up


ACL

Com llistar ACL d’un usuari d’AD amb PowerShell?
(Get-Acl -Path "AD:\$dn").Access

Com llistar ACL d’una carpeta amb PowerShell?
(Get-Acl -Path C:\scripts).Access

Com llistar específiques entrades de permisos d’ACL (usuaris o grups) d’un usuari d’AD amb PowerShell?

Up


Variables

Quins són els tipus de dades més comuns en PowerShell?

Com trobar els valors mínims i màxims per a algunes variables de tipus amb PowerShell?

Com provar el tipus de dades amb PowerShell?

Com crear una-Aquí variable encadenada amb PowerShell?

Com crear una variable amb PowerShell?
$powershellGuru = 'Hello'

Com crear una variable constant amb PowerShell?
Set-Variable -Name powershellGuru -Value 2015 -Option Constant

Com crear una variable global amb PowerShell?