مفهوم: سؤالات رایج درباره پاور شل
میتوانید از این لیست به طرق مختلف استفاده کنید:
جهت کپی/پیست کردن دستورات در اسکریپت
جهت دیدن سینتکس یک دستور خاص
جهت ارتقای دانش تکنیکی خود
جهت کشف دستورات جدید
جهت آماده سازی برای مصاحبه کاری
2015 ژوئیه 7 |
به روز شده
|
powershell-guru.com | نویسنده |
persian.powershell-guru.com | منبع |
75 |
دسته
|
610 |
سوالات
|
System
چگونه ورژن پاور شل خود را تشخیص دهیم؟
1 2 3 4 5 6 7 8 9 |
# via Powershell $PSVersionTable.PSVersion.Major # via Registry (Get-ItemProperty -Path 'HKLM:\SOFTWARE\Microsoft\PowerShell\1\PowerShellEngine').PowerShellVersion # Versions 1 and 2 (Get-ItemProperty -Path 'HKLM:\SOFTWARE\Microsoft\PowerShell\3\PowerShellEngine').PowerShellVersion # Versions 3 and 4 # via Remote Invoke-Command -ComputerName $computer -ScriptBlock { $PSVersionTable.PSVersion.Major } |
چگونه پاور شل را در ورژن دیگری جهت سازگاری با ورژنهای قدیمی اجرا کنیم؟
powershell.exe -Version 2.0
چگونه در یک اسکریپت پاور شل، به کمترین ورژن پاور شل (سه یا بالاتر) نیاز داشته باشیم؟
#Requires -Version 3.0
چگونه برای یک اسکریپت پاور شل، از مزایای ادمین استفاده کنیم؟
1 2 3 4 5 |
# Solution 1 #Requires -RunAsAdministrator # Solution 2 [bool]((whoami.exe /all) -match 'S-1-16-12288') |
چگونه پارامترهای یک اسکریپت پاور شل را چک کنیم؟
help -Name .\Get-ExchangeEnvironmentReport.ps1 -Full
چگونه اطلاعات یک کاربر موجود را با استفاده از پاور شل بدست آوریم؟
[Security.Principal.WindowsIdentity]::GetCurrent()
چگونه یک پروفایل را با استفاده از پاور شل ایجاد، تصحیح، و یا دوباره بارگذاری کنیم؟
1 2 3 4 5 6 7 8 9 |
# Create New-Item -Type file -Force $profile # Edit notepad.exe $profile # Reload (without restarting Powershell) & $profile .$profile |
چگونه یک وقفه پنج ثانیه/دقیقه ای در یک اسکریپت پاور شل ایجاد کنیم؟
Start-Sleep -Seconds 5
Start-Sleep -Seconds 300 # 5 minutes
چگونه زمان آخرین بوت را با استفاده از پاور شل بدست آوریم؟
(Get-CimInstance -ClassName win32_operatingsystem).LastBootUpTime
چگونه با کمک پاور شل تسریع کننده تایپ بدست آوریم؟
1 |
[PSObject].Assembly.GetType('System.Management.Automation.TypeAccelerators')::Get.GetEnumerator() | Select-Object -Property @{Name='Key'; Expression={$_.Key}},@{name='Value'; Expression={$_.Value}} | Sort-Object -Property Key | Format-Table -AutoSize |
چگونه برنامه های استارت آپ را با استفاده از پاور شل لیست کنیم؟
1 |
Get-WmiObject -Class Win32_StartupCommand | Sort-Object -Property Caption | Format-Table -Property Caption, Command, User -AutoSize |
چگونه یک اپلیکشن را با پاور شل پاک کنیم؟
1 2 |
$application = Get-WmiObject -Query "SELECT * FROM Win32_Product WHERE Name LIKE 'HP Recovery Manager'" $application.Uninstall() |
چگونه با استفاده از پاور شل، از کل صفحه دسکتاپ یا ویندوز در حال کار عکس بگیریم؟
Take-ScreenShot -Screen -File 'C:\scripts\screenshot.png' -Imagetype JPEG
Repository : Take-ScreenShot
چگونه با استفاده از پاور شل، شمارنده پیغام برای صفوف “ام-اس-ام-کیو” بسازیم؟
1 |
Get-WmiObject -Class Win32_PerfRawData_MSMQ_MSMQQueue -ComputerName $computer | Format-Table -Property Name, MessagesInQueue -AutoSize |
چگونه با استفاده از پاور شل، سیاست اجرایی تعیین کنیم؟
1 2 3 4 5 6 7 8 9 10 11 |
# Restricted - No scripts can be run. Windows PowerShell can be used only in interactive mode. Set-ExecutionPolicy -ExecutionPolicy Restricted # AllSigned - Only scripts signed by a trusted publisher can be run. Set-ExecutionPolicy -ExecutionPolicy AllSigned # RemoteSigned - Downloaded scripts must be signed by a trusted publisher before they can be run. Set-ExecutionPolicy -ExecutionPolicy RemoteSigned # Unrestricted - No restrictions - All Windows PowerShell scripts can be run. Set-ExecutionPolicy -ExecutionPolicy Unrestricted |
چگونه با پاور شل، شرتکات بسازیم؟
1 2 3 4 |
$shell = New-Object -ComObject WScript.Shell $shortcut = $shell.Createshortcut("$HOME\Desktop\Procexp.lnk") $shortcut.TargetPath = 'C:\SysinternalsSuite\procexp.exe' $shortcut.Save() |
چگونه با پاور شل یک برنامه را به تسک بار افزوده یا پاک کنیم؟
1 2 3 4 |
$shell = New-Object -ComObject shell.application $program = $shell.Namespace($env:windir).Parsename('notepad.exe') $program.Invokeverb('TaskbarPin') $program.Invokeverb('TaskbarUnpin') |
چگونه با پاور شل یک ویندوز اکسپلورر باز کنیم؟
[Diagnostics.Process]::Start('explorer.exe')
Invoke-Item -Path C:\Windows\explorer.exe
چگونه درایورهای دستگاه را با پاور شل لیست کنیم؟
Get-WmiObject -Class Win32_PnPSignedDriver
Get-WindowsDriver -Online -All
driverquery.exe
چگونه با پاور شل “جی یو آی دی” ایجاد کنیم؟
1 2 3 4 5 6 7 8 9 10 11 |
# Empty GUID $guid = [GUID]::Empty # New GUID (lower case by default) $guid = [GUID]::NewGuid() # New GUID (upper case) $guid = ([GUID]::NewGuid()).ToString().ToUpper() # New GUID with a specific value $guid = [GUID]('bc4ad3d3-d704-4bd0-843f-d607fbbc4cd7') |
چگونه با پاور شل، مکان دایرکتوری موقت را برای یک کاربر موجود بیابیم؟
[System.IO.Path]::GetTempPath()
چگونه با پاور شل یک مسیر و یک مسیر زیر مجموعه را به مسیری یکتا پیوند زنیم؟
Join-Path -Path C:\ -ChildPath \windows
cmdlets “Get-*” چگونه تمام دستورهای روبرو را با پاور شل لیست کنیم؟
Get-Command -Verb Get
چگونه تمام فولدرهای سیستمی خاص را با پاور شل لیست کنیم؟
1 |
[System.Enum]::GetNames([System.Environment+SpecialFolder]) | ForEach-Object -Process { $_ + " [System.Environment]::GetFolderPath($_)" } |
ISO/VHD چگونه فایلهای روبرو را با پاور شل سوار کنیم؟
Mount-DiskImage 'D:\ISO\file.iso' # ISO
Mount-DiskImage 'D:\VHD\file.vhd' # VHD
چگونه ورژنهای در قالب دات نت را که با پاور شل نصب شده اند چک کنیم؟
1 |
Get-ChildItem -Path 'HKLM:\SOFTWARE\Microsoft\NET Framework Setup\NDP' -Recurse | Get-ItemProperty -Name Version -EA 0 | Where-Object -FilterScript { $_.PSChildName -match '^(?!S)\p{L}' } | Select-Object -Property PSChildName, Version |
چگونه میتوان چک کرد که قالبهای دات نت ورژن 4.5 با پاور شل نصب شده اند؟
(Get-ItemProperty -Path 'HKLM:\Software\Microsoft\NET Framework Setup\NDP\v4\Full' -EA 0).Version -like '4.5*'
چگونه میتوان یک کد را (جهت ضبط پاورشل ویندوز) با استفاده از پاور شل شروع و تمام کرد؟
Start-Transcript -Path 'C:\scripts\transcript.txt
Stop-Transcript
چگونه دایرکتوری موجود را با استفاده از پاور شل، به جای مشخصی تغییر مکان دهیم؟
Set-Location -Path 'C:\scripts'
چگونه با پاور شل صفحه را خالی کنیم؟
Clear-Host
cls # Alias
چگونه با پاور شل کیفیت تصویر را تغییر دهیم؟
Set-DisplayResolution -Width 1280 -Height 1024 -Force # Windows 2012
چگونه پنجره را با پاور شل به حالت تمام صفحه درآوریم؟
mode.com 300
چگونه با استفاده از پاور شل، ابعاد (طول و عرض) یک تصویر را بدست آوریم؟
1 2 3 4 5 6 7 |
$picture = New-Object -ComObject Wia.ImageFile $picture.LoadFile('C:\screenshot.jpg') [PSCustomObject] @{ Width = $picture.Width Height = $picture.Height } |
چگونه با پاور شل کلید رمز ویندوز را بدست آوریم؟
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 |
function Get-WindowsKey { ## function to retrieve the Windows Product Key from any PC ## by Jakob Bindslet (jakob@bindslet.dk) param ($targets = '.') $hklm = 2147483650 $regPath = 'Software\Microsoft\Windows NT\CurrentVersion' $regValue = 'DigitalProductId' Foreach ($target in $targets) { $productKey = $null $win32os = $null $wmi = [WMIClass]"\\$target\root\default:stdRegProv" $data = $wmi.GetBinaryValue($hklm,$regPath,$regValue) $binArray = ($data.uValue)[52..66] $charsArray = 'B', 'C', 'D', 'F', 'G', 'H', 'J', 'K', 'M', 'P', 'Q', 'R', 'T', 'V', 'W', 'X', 'Y', '2', '3', '4', '6', '7', '8', '9' ## decrypt base24 encoded binary data For ($i = 24; $i -ge 0; $i--) { $k = 0 For ($j = 14; $j -ge 0; $j--) { $k = $k * 256 -bxor $binArray[$j] $binArray[$j] = [math]::truncate($k / 24) $k = $k % 24 } $productKey = $charsArray[$k] + $productKey If (($i % 5 -eq 0) -and ($i -ne 0)) { $productKey = '-' + $productKey } } $win32os = Get-WmiObject -Class Win32_OperatingSystem -ComputerName $target $obj = New-Object -TypeName Object $obj | Add-Member -MemberType Noteproperty -Name Computer -Value $target $obj | Add-Member -MemberType Noteproperty -Name Caption -Value $win32os.Caption $obj | Add-Member -MemberType Noteproperty -Name CSDVersion -Value $win32os.CSDVersion $obj | Add-Member -MemberType Noteproperty -Name OSArch -Value $win32os.OSArchitecture $obj | Add-Member -MemberType Noteproperty -Name BuildNumber -Value $win32os.BuildNumber $obj | Add-Member -MemberType Noteproperty -Name RegisteredTo -Value $win32os.RegisteredUser $obj | Add-Member -MemberType Noteproperty -Name ProductID -Value $win32os.SerialNumber $obj | Add-Member -MemberType Noteproperty -Name ProductKey -Value $productKey $obj } } |
Perfmon
چگونه با استفاده از پاور شل، “درصد زمان پردازش” (میانگین) را برای پنج ثانیه آخر (ده برابر) محاسبه کنیم؟
(Get-Counter '\Processor(_total)\% Processor Time' -SampleInterval 5 -MaxSamples 10).CounterSamples.CookedValue
Assemblies
چگونه اسمبلی ها را با پاور شل بارگذاری کنیم؟
1 2 3 4 5 6 |
Add-Type -AssemblyName 'System.Windows.Forms' Add-Type -Path 'C:\Windows\Microsoft.Net\assembly\GAC_MSIL\System.Windows.Forms\v4.0_4.0.0.0__b77a5c561934e089\System.Windows.Forms.dll' # Deprecated [System.Reflection.Assembly]::LoadFrom('C:\Windows\Microsoft.Net\assembly\GAC_MSIL\System.Windows.Forms\v4.0_4.0.0.0__b77a5c561934e089\System.Windows.Forms.dll') |
چگونه اسمبلی های موجودی که در قالب دات نت هستند و با پاور شل لود شده اند را میتوان چک کرد؟
1 2 3 4 5 |
# Check All [System.AppDomain]::CurrentDomain.GetAssemblies() # Check specific one [System.AppDomain]::CurrentDomain.GetAssemblies() | Where-Object -FilterScript { $_.FullName -like '*forms*' } |
چگونه میتوان مسیر “جی ای سی” (حافظه سراسری اسمبلی) را با استفاده از پاور شل تعیین نمود؟
1 |
(New-Object -TypeName Regex -ArgumentList '(?<=file:///)(.*)(?=\/GAC)', 'IgnoreCase').Match(([PSObject].Assembly.Evidence | Where-Object -FilterScript { $_.Value -ne $null }).Value).Value -replace '/', '\' |
Clipboard
چگونه میتوان نتایج را با استفاده از پاور شل به کلیپ بورد کپی کرد؟
1 |
Get-Process | clip.exe |
چگونه میتوان محتوای کلیپ بورد را با استفاده از پاور شل بدست آورد؟
Add-Type -AssemblyName PresentationCore
[Windows.Clipboard]::GetText()
Hotfixes
چگونه میتوان هات فیکس های نصب شده را با استفاده از پاور شل بدست آورد؟
Get-HotFix -ComputerName $computer
چگونه میتوان هات فیکس های نصب شده قبل/بعد از یک تاریخ مشخص را با استفاده از پاور شل بدست آورد؟
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
چگونه میتوان تشخیص داد که یک هات فیکس با پاور شل نصب شده است؟
Get-HotFix -Id KB2965142
چگونه میتوان هات فیکس هایی را که بر روی یک سیستم از راه دور نصب شده اند، با پاور شل بدست آورد؟
Get-HotFix -ComputerName $computer
Pagefile
چگونه میتوان اطلاعات فایل صفحه ای را با پاور شل بدست آورد؟
Get-WmiObject -Class Win32_PageFileusage | Select-Object -Property Name, CurrentUsage, AllocatedBaseSize, PeakUsage, InstallDate
چگونه میتوان با استفاده از پاور شل سایز مناسب (مگا بایت) را بدست آورد؟
[Math]::Truncate(((Get-WmiObject -Class Win32_ComputerSystem).TotalPhysicalMemory) / 1MB) * 1.5
چگونه میتوان با پاور شل یک فایل صفحه ای (4096 مگابایت) را در درایو دی ایجاد نمود؟
1 2 3 4 5 |
Set-WmiInstance -Class Win32_PageFileSetting -Arguments @{ Name = 'D:\pagefile.sys' InitialSize = 4096 MaximumSize = 4096 } |
چگونه میتوان با پاور شل یک فایل صفحه ای را در درایو سی ایجاد نمود؟
1 2 3 4 5 |
$privileges = Get-WmiObject -Class Win32_computersystem -EnableAllPrivileges $privileges.AutomaticManagedPagefile = $false $privileges.Put() $pagefile = Get-WmiObject -Query "select * from Win32_PageFileSetting where name='c:\\pagefile.sys'" $pagefile.Delete() # Reboot required |
Maintenance
چگونه میتوان با پاور شل گسستگی یک درایو را چک کرد؟
1 |
$drive = Get-WmiObject -Class Win32_Volume -Filter "DriveLetter = 'c:'" $defragReport = $drive.DefragAnalysis() $defragReport.DefragAnalysis |
چگونه فضای دیسک درایوها را با استفاده از پاور شل چک کنیم؟
1 2 3 4 5 6 7 8 9 10 11 12 13 |
Get-WmiObject -Class Win32_logicaldisk | Format-Table -Property @{ Name = 'Drive' Expression = {$_.DeviceID} }, @{ Name = 'Total size (GB)' Expression = {[decimal]('{0:N0}' -f($_.Size/1gb))} }, @{ Name = 'Free space(GB)' Expression = {[decimal]('{0:N0}'-f($_.Freespace/1gb))} }, @{ Name = 'Free (%)' Expression = {'{0,6:P0}' -f(($_.Freespace/1gb) / ($_.size/1gb))} } -AutoSize |
Files
چگونه یک فایل را با پاور شل باز کنیم؟
Invoke-Item -Path 'C:\scripts\file.txt'
.'C:\scripts\file.txt'
چگونه یک فایل را با پاور شل بخوانیم؟
Get-Content -Path 'C:\scripts\file.txt'
gc "C:\scripts\file.txt" # Alias
چگونه با استفاده از پاور شل، خروجی را در یک فایل بنویسیم؟
'Line1', 'Line2', 'Line3' | Out-File -FilePath 'C:\scripts\file.txt'
'Line1', 'Line2', 'Line3' | Add-Content -Path file.txt
چگونه میتوان با پاور شل نام کامل یک فایل اسکریپت را بدست آورد؟
$MyInvocation.MyCommand.Path
چگونه میتوان با استفاده از پاور شل فایلها را فشرده/زیپ کرد؟
Add-Type -AssemblyName 'System.IO.Compression.Filesystem'
[System.IO.Compression.ZipFile]::CreateFromDirectory($folder,$fileZIP)
چگونه با پاور شل فایلها را از حالت فشرده درآوریم؟
Add-Type -AssemblyName 'System.IO.Compression.Filesystem'
[System.IO.Compression.ZipFile]::ExtractToDirectory($fileZIP, $folder)
چگونه با پاور شل، فایلها را در یک آرشیو زیپ ببینیم؟
Add-Type -AssemblyName 'System.IO.Compression.Filesystem'
[System.IO.Compression.ZipFile]::OpenRead($fileZIP)
چگونه سایز یک فایل را در کیلو بایت با استفاده از پاور شل نمایش دهیم؟
(Get-ChildItem -Path .\winsrv.dll).Length /1KB
(Get-ChildItem -Path .\winsrv.dll).Length /1MB
(Get-ChildItem -Path .\winsrv.dll).Length /1GB
چگونه با کمک پاور شل، فایلهای کمتر یا بیشتر از یک گیگا بایت را پیدا کنیم؟
1 2 3 4 5 |
# Larger than 1 GB Get-ChildItem -Path C:\ -Recurse -ErrorVariable $errorsSearch | Where-Object -FilterScript {$_.Length -gt 1GB} # Less than 1 GB Get-ChildItem -Path C:\ -Recurse -ErrorVariable $errorsSearch | Where-Object -FilterScript {$_.Length -lt 1GB} |
چگونه با استفاده از پاور شل، نام یک فایل را بدون پسوند نمایش دهیم؟
[System.IO.Path]::GetFileNameWithoutExtension('C:\Windows\system32\calc.exe') # Return calc
چگونه پسوند یک فایل را با استفاده از پاور شل نمایش دهیم؟
[System.IO.Path]::GetExtension('C:\scripts\file.txt') # Return .txt
چطور میتوان ورژن یک فایل را با کمک پاور شل بدست آورد؟
1 2 |
(Get-Item -Path C:\Windows\System32\calc.exe).VersionInfo.FileVersion [System.Diagnostics.FileVersionInfo]::GetVersionInfo('C:\Windows\system32\calc.exe').FileVersion |
چطور هش یک فایل را با کمک پاور شل بدست آوریم؟
(Get-FileHash $file).Hash
چگونه با پاور شل، MD5/SHA1 چک سام یک فایل را بدست آوریم؟
Get-FileHash $file -Algorithm MD5
Get-FileHash $file -Algorithm SHA1
چگونه با پاور شل فایلهای مخفی را نمایش دهیم؟
1 2 3 4 5 |
# Display only hidden files Get-ChildItem -Hidden -File # Display all files (including hidden files) Get-ChildItem -Force -File |
چطور میتوان با کمک پاور شل تعیین نمود که آیا یک فایل دنباله دارد یا خیر؟
1 |
[System.IO.Path]::HasExtension('C:\hiberfil.sys') |
چطور با کمک پاور شل، یک فایل را بصورت “فقط خواندنی” تنظیم کنیم؟
Set-ItemProperty -Path .\file.txt -Name IsReadOnly -Value $true
چگونه با کمک پاور شل، ویژگی “آخرین زمان نوشتن” یک فایل را به هفته گذشته تغییر داد؟/
Set-ItemProperty -Path .\file.txt -Name LastWriteTime -Value ((Get-Date).AddDays(-7))
If not working, use Nirsoft tool: BulkFileChanger.
چگونه میتوان یک فایل جدید با استفاده از پاور شل ایجاد نمود؟
New-Item -ItemType File -Path 'C:\scripts\file.txt' -Value 'FirstLine'
چگونه میتوان با پاور شل نام یک فایل را تغییر داد؟
Rename-Item -Path 'C:\scripts\file.txt' -NewName 'C:\scripts\powershellguru2.txt'
چگونه نام فایلهای متعدد را با پاور شل تغییر دهیم؟
Get-ChildItem -Path C:\scripts\txt | Rename-Item -NewName { $_.Name -replace ' ', '_' }
چگونه میتوان با کمک پاور شل یک فایل را پاک کرد؟
Remove-Item -Path 'C:\scripts\file.txt'
چگونه با پاور شل ده خط پایانی یک فایل را نمایش دهیم؟
Get-Content -Path 'C:\scripts\log.txt' -Tail 10
چگونه با پاور شل، فایلهای متعدد یک فولدر را از حالت قفل خارج کنیم؟
Get-ChildItem -Path 'C:\scripts\Modules' | Unblock-File
چگونه خطوط خالی یک فایل را با پاور شل حذف کنیم؟
(Get-Content -Path file.txt) | Where-Object -FilterScript {$_.Trim() -ne '' } | Set-Content -Path file.txt
چگونه با استفاده از پاور شل موجودیت یک فایل را چک کنیم؟
1 |
Test-Path -Path 'C:\Windows\notepad.exe' # Return True |
چگونه با پاور شل، جدیدترین/قدیمیترین فایل ایجاد شده را در یک فولدر شناسایی نمود؟
1 2 |
Get-ChildItem | Sort-Object -Property CreationTime | Select-Object -Last 1 # Newest Get-ChildItem | Sort-Object -Property CreationTime | Select-Object -First 1 # Oldest |
چگونه خطوط تکراری در یک فایل را با استفاده از پاور شل حذف کنیم؟
1 2 |
Get-Content -Path .\file.txt | Select-Object -Unique # Display Get-Content -Path .\file.txt | Select-Object -Unique | Set-Content -Path .\testing.txt # Save |
1 2 3 |
$1MonthAgo = (Get-Date).AddMonths(-1) Get-ChildItem | ?{$_.LastWriteTime -lt $1MonthAgo} | Select-Object LastWriteTime,Name,DirectoryName # More Get-ChildItem | ?{$_.LastWriteTime -gt $1MonthAgo} | Select-Object LastWriteTime,Name,DirectoryName # Less |
1 2 3 |
$1YearAgo = (Get-Date).AddYears(-1) Get-ChildItem | ?{$_.LastWriteTime -lt $1YearAgo} | Select-Object LastWriteTime,Name,DirectoryName # More Get-ChildItem | ?{$_.LastWriteTime -gt $1YearAgo} | Select-Object LastWriteTime,Name,DirectoryName # Less |
چگونه مقدار یک متغیر را میتوان با کمک پاور شل در یک فایل خروجی نمایش داد؟
Set-Content -Path file.txt -Value $variable
چگونه با پاور شل تعداد فایلهای تکست را شمارش کنیم؟ (*.txt)
1 2 3 |
[System.IO.Directory]::GetFiles('C:\scripts', '*.txt').Count (Get-ChildItem -Path 'C:\scripts' -Filter *.txt).Count (Get-ChildItem -Path 'C:\scripts' -Filter *.txt -Recurse).Count # Recursive |
چگونه با پاور شل، یک دنباله را در بین فایلهای متعدد جستجو کنیم؟
Select-String -Path 'C:\*.txt' -Pattern 'Test'
چگونه اولین/آخرین خط یک فایل را با استفاده از پاور شل نمایش دهیم؟
1 2 3 4 5 6 7 8 9 |
'Line1', 'Line2', 'Line3' | Out-File -FilePath file.txt # First Line Get-Content -Path .\file.txt | Select-Object -First 1 # Returns Line1 (Get-Content -Path .\file.txt)[0] # Returns Line1 # Last Line Get-Content -Path .\file.txt | Select-Object -Last 1 # Returns Line3 (Get-Content -Path .\file.txt)[-1] # Returns Line3 |
چگونه شماره یک خط به خصوص از یک فایل را با پاور شل نمایش دهیم؟
1 2 3 |
'Line1', 'Line2', 'Line3' | Out-File -FilePath file.txt Get-Content -Path .\file.txt | Select-Object -Index 0 # Returns Line1 Get-Content -Path .\file.txt | Select-Object -Index 2 # Returns Line3 |
چگونه تعداد خطوط یک فایل را با پاور شل شمارش کنیم؟
1 2 |
'Line1', 'Line2', 'Line3' | Out-File -FilePath file.txt (Get-Content -Path .\file.txt | Measure-Object -Line).Lines # Returns 3 |
چگونه تعداد کاراکترها و کلمات یک فایل را با پاور شل شمارش کنیم؟
1 2 3 4 5 6 7 8 9 10 |
'Test', 'Powershell', 'Test Powershell' | Out-File -FilePath file.txt # Words (Return 4) (Get-Content -Path .\file.txt | Measure-Object -Word).Words # Characters (Return 23) (Get-Content -Path .\file.txt | Measure-Object -Character).Characters # Characters and ignore whitespaces (Return 22) (Get-Content -Path .\file.txt | Measure-Object -Character -IgnoreWhiteSpace).Characters |
چگونه یک فایل را با استفاده از پاور شل دانلود کنیم؟
Invoke-WebRequest -Uri 'http://www.nirsoft.net/utils/searchmyfiles.zip' -OutFile 'C:\tools\searchmyfiles.zip'
چگونه مسیر کامل یک فایل را با پاور شل نمایش دهیم؟
Resolve-Path -Path .\script.ps1 # Return C:\Scripts\script.ps1
Copy
چگونه یک فایل را با استفاده از پاور شل در فولدری دیگر کپی کنیم؟
Copy-Item -Path 'C:\source\file.txt' -Destination 'C:\destination'
چگونه یک فایل را با استفاده از پاور شل، در فولدرهای متعدد میتوان کپی کرد؟
1 2 |
$destination = 'C:\destination\Folder1', 'C:\destination\Folder2' $destination | Copy-Item -Path 'C:\source\file.txt' -Recurse -Destination {$_} |
چگونه میتوان فایلهای متعدد را در یک فولدر با پاور شل کپی کرد؟
Get-ChildItem -Path 'C:\source' -Filter *.txt | Copy-Item -Destination 'C:\destination'
Active Directory
Domain & Forest
چگونه میتوان سرورهای کاتالوگ عمومی را در یک دایرکتوری فعال، با استفاده از پاور شل، جستجو کرد؟
[System.DirectoryServices.ActiveDirectory.Forest]::GetCurrentForest().GlobalCatalogs
چگونه میتوان سایتها را در یک دایرکتوری فعال، با پاور شل پیدا کرد؟
[System.DirectoryServices.ActiveDirectory.Forest]::GetCurrentForest().Sites
چگونه کنترل کننده ی کنونی دامنه را با کمک پاور شل بیابیم؟
(Get-ADDomainController).HostName
چگونه میتوان تمام کنترل کننده های دامنه را در یک دامنه، با استفاده از پاور شل یافت؟
1 2 3 4 5 6 7 8 9 10 11 |
# Solution 1 Get-ADDomainController -Filter * | ForEach-Object -Process {$_.Name} # Solution 2 Get-ADGroupMember 'Domain Controllers' | ForEach-Object -Process {$_.Name} # Solution 3 Get-ADComputer -LDAPFilter '(&(objectCategory=computer)(userAccountControl:1.2.840.113556.1.4.803:=8192))' | ForEach-Object -Process {$_.Name} # Solution 4 [System.DirectoryServices.ActiveDirectory.Domain]::GetCurrentDomain() | ForEach-Object -Process {$_.DomainControllers} | ForEach-Object -Process {$_.Name} |
چگونه شکستهای مولد اد را با پاور شل بیابیم؟
Get-ADReplicationFailure dc02.domain.com # Windows 8 and 2012
چگونه زمان حیات تامب استون را برای فارست در دایرکتوری فعال، با پاور شل میتوان یافت؟
1 |
(Get-ADObject -Identity "cn=Directory Service,cn=Windows NT,cn=Services,$(([adsi]('LDAP://RootDSE')).configurationNamingContext)" -Properties tombstonelifetime).tombstonelifetime |
چگونه میتوان جزئیات فارست/دامنه را در دایرکتوری فعال، با پاور شل یافت؟
1 2 |
Get-ADDomain domain.com Get-ADForest domain.com |
چگونه مسیر یک کانتینر “شئ حذف شده” را در دایرکتوری فعال بیابیم؟
(Get-ADDomain).DeletedObjectsContainer
چگونه خاصیت “اد” ریساکل بین در یک دایرکتوری فعال را با پاور شل بیابیم؟
1 |
Enable-ADOptionalFeature -Identity 'CN=Recycle Bin Feature,CN=Optional Features,CN=Directory Service,CN=Windows NT,CN=Services,CN=Configuration,DC=domain,DC=com' -Scope ForestOrConfigurationSet -Target 'domain.com' |
چگونه با پاور شل، یک اکانت “اد” را از ریسایکل بین به دایرکتوری فعال بازیابی کنیم؟
Get-ADObject -Filter 'samaccountname -eq "powershellguru"' -IncludeDeletedObjects | Restore-ADObject
چگونه نقش FSMO را با پاور شل بیابیم؟
1 2 3 4 5 6 7 8 9 10 11 12 13 |
# Solution 1 Get-ADForest | Format-List -Property SchemaMaster, DomainNamingMaster Get-ADDomain | Format-List -Property PDCEmulator, RIDMaster, InfrastructureMaster # Solution 2 netdom query fsmo # Solution 3 [System.DirectoryServices.ActiveDirectory.Forest]::GetCurrentForest().SchemaRoleOwner [System.DirectoryServices.ActiveDirectory.Forest]::GetCurrentForest().NamingRoleOwner [System.DirectoryServices.ActiveDirectory.Domain]::GetCurrentDomain().InfrastructureRoleOwner [System.DirectoryServices.ActiveDirectory.Domain]::GetCurrentDomain().PdcRoleOwner [System.DirectoryServices.ActiveDirectory.Domain]::GetCurrentDomain().RidRoleOwner |
چگونه با پاور شل، به یک دامنه ی به خصوص وصل شویم؟
Get-ADUser -Identity $user -Server 'serverDC01'
چگونه یک سرور لاگ آن موجود را با پاور شل بدست آوریم؟
1 2 |
($env:LOGONSERVER).Substring(2) ([System.Environment]::GetEnvironmentVariable('logonserver')).Substring(2) |
چگونه “gpupdate” را در یک کامپیوتر دارای پاور شل اجرا کنیم؟
Invoke-GPUpdate -Computer $computer -Force -RandomDelayInMinutes 0 # Windows 2012
Groups
چگونه یک گروه جدید در دایرکتوری فعال، با پاور شل ایجاد کنیم؟
1 |
New-ADGroup -Name 'Powershell Guru' -SamAccountName powershellguru -GroupCategory Security -GroupScope Global -DisplayName 'Powershell Guru' -Path 'OU=MyOU,DC=domain,DC=com' -Description 'My account' |
چگونه یک گروه را از دایرکتوری فعال، با پاور شل پاک کنیم؟
Remove-ADGroup -Identity 'PowershellGuru'
چگونه یک کاربر را به یک گروه در دایرکتوری فعال، با استفاده از پاور شل اضافه کنیم؟
Add-ADGroupMember "Powershell Guru" -Members powershellguru
چگونه یک کاربر را از یک گروه در دایرکتوری فعال، با پاور شل، حذف کنیم؟
Remove-ADGroupMember 'Powershell Guru' -Members powershellguru
چگونه گروه های خالی (بدون عضو) را در دایرکتوری فعال، با پاور شل پیدا کنیم؟
Get-ADGroup -Filter * -Properties Members | Where-Object -FilterScript {-not $_.Members}
چگونه گروه های خالی (بدون عضو) را در دایرکتوری فعال، با پاور شل شمارش کنیم؟
(Get-ADGroup -Filter * -Properties Members | Where-Object -FilterScript {-not $_.Members}).Count
چگونه اعضای یک گروه را در دایرکتوری فعال، با پاور شل، بدست آوریم؟
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 |
# Solution 1 Get-ADGroupMember 'Powershell Guru' | ForEach-Object -Process {$_.DistinguishedName} Get-ADGroupMember 'Powershell Guru' | ForEach-Object -Process {$_.Samaccountname} # Solution 2 Get-ADGroup 'Powershell Guru' -Properties Members | Select-Object -Property Members -ExpandProperty Members | Sort-Object # Solution 3 function Get-ADGroupMemberFast { [CmdletBinding()] Param ( [Parameter(Mandatory = $true)] [string]$GroupName ) $de = New-Object -TypeName System.DirectoryServices.DirectoryEntry $ds = New-Object -TypeName System.DirectoryServices.DirectorySearcher $ds.SearchRoot = $de $ds.Filter = "(cn=$group)" $null = $ds.PropertiesToLoad.Add('member') $result = $ds.FindOne() if($result) { $account = $result.GetDirectoryEntry() $account.Properties['member'] | ForEach-Object -Process {$_} } } Get-ADGroupMemberFast -GroupName 'Powershell Guru' |
چگونه اعضای یک گروه با اعضای تکرار شونده را در دایرکتوری فعال، با استفاده از پاور شل، بدست آوریم؟
1 2 |
Get-ADGroupMember 'Powershell Guru' -Recursive | ForEach-Object -Process {$_.DistinguishedName} Get-ADGroupMember 'Powershell Guru' -Recursive | ForEach-Object -Process {$_.SamAccountName} |
چگونه تعداد اعضای یک گروه را با/بدون اعضای تکرار شونده، در دایرکتوری فعال، با پاور شل محاسبه کنیم؟
1 2 |
(Get-ADGroupMember 'Powershell Guru' | ForEach-Object -Process {$_.Samaccountname}).Count (Get-ADGroupMember 'Powershell Guru' -Recursive | ForEach-Object -Process {$_.Samaccountname}).Count |
Users
چگونه یک wildcard در فیلتر “Get-ADUser” در دایرکتوری فعال، با پاور شل استفاده کنیم؟
1 2 3 4 5 6 7 8 9 |
# Filter (Get-ADUser -SearchBase 'OU=myOU,DC=domain,DC=com' -Filter {name -like '*vip*'} -Properties Name).Name # LDAPFilter (Get-ADUser -SearchBase 'OU=myOU,DC=domain,DC=com' -LDAPFilter '(name=*vip*)' -Properties Name).Name # With a variable $user = '*vip*' (Get-ADUser -SearchBase 'OU=myOU,DC=domain,DC=com' -Filter {name -like $user} -Properties Name).Name |
چگونه یک کاربر را به یک OU دیگر در دایرکتوری فعال، با پاور شل انتقال دهیم؟
Move-ADObject -Identity $dn -TargetPath 'OU=myOU,DC=domain,DC=com'
چگونه با پاور شل، تمام اعضایی که برای یک کاربر (نست) شده اند را بیابیم؟
Get-ADGroup -LDAPFilter "(member:1.2.840.113556.1.4.1941:=$($dn))"
چگونه اعضای (نام کوتاه/مختصر شده) را برای یک کاربر، با استفاده از پاور شل بدست آوریم؟
(Get-ADUser $user -Properties MemberOf).MemberOf | ForEach-Object -Process {($_ -split ',')[0].Substring(3)} | Sort-Object
1 2 |
Set-ADUser $samAccountName -DisplayName 'DisplayName' -GivenName 'Test' -Surname 'Powershell' -DisplayName 'Test Powershell' Rename-ADObject $dn -NewName 'Test Powershell' #FullName |
چگونه مشخصات، دفتر کار، و شماره تلفن یک کاربر را در دایرکتوری فعال، با پاور شل تغییر دهیم؟
Set-ADUser $samAccountName -Description 'IT Consultant' -Office 'Building B' -OfficePhone '12345'
1 2 3 4 5 |
# 31/12/2015 Set-ADAccountExpiration $samAccountName -DateTime '01/01/2016' # Never Clear-ADAccountExpiration $samAccountName |
چگونه یک حساب کاربری را در دایرکتوری فعال، با استفاده از پاور شل قفل گشایی کنیم؟
Unlock-ADAccount $samAccountName
چگونه حساب کاربری را برای یک کاربر در دایرکتوری فعال، با استفاده از پاور شل، فعال/غیرفعال کنیم؟
1 2 |
Disable-ADAccount $samAccountName Enable-ADAccount $samAccountName |
چگونه یک حساب کاربری را در یک دایرکتوری فعال، با پاور شل حذف کنیم؟
Remove-ADUser $samAccountName
چگونه پسوورد یک کاربر را در دایرکتوری فعال، با پاور شل ریست کنیم؟
1 2 3 4 5 6 7 |
# Solution 1 : ask password $password = Read-Host -Prompt 'New Password' -AsSecureString # Solution 2 : specify password $password = ConvertTo-SecureString -String 'Q>9xYMw<3?' -AsPlainText -Force Get-ADUser -Filter "samaccountname -like 'helpdeskagent*'" | Set-ADAccountPassword -NewPassword $newpwd -Reset -PassThru | Set-ADuser -ChangePasswordAtLogon $true |
چگونه پسووردهای کاربران متعدد را در دایرکتوری فعال، با پاور شل ریست کنیم؟
1 2 3 4 5 6 7 |
# Solution 1 : ask password $password = Read-Host -Prompt 'New Password' -AsSecureString # Solution 2 : specify password $password = ConvertTo-SecureString -String 'Q>9xYMw<3?' -AsPlainText -Force Get-ADUser -Filter "samaccountname -like 'helpdeskagent*'" | Set-ADAccountPassword -NewPassword $newpwd -Reset -PassThru | Set-ADuser -ChangePasswordAtLogon $true |
چگونه صاحب یک فایل را در دایرکتوری فعال، با پاور شل بیابیم؟
1 2 3 |
$user = New-Object -TypeName System.Security.Principal.NTAccount -ArgumentList (Get-Acl -Path 'userFile.txt').Owner $sid = $user.Translate([System.Security.Principal.SecurityIdentifier]).Value Get-ADUser $sid |
چگونه OU (واحد سازمان یافته) را برای یک کاربر، در دایرکتوری فعال، با پاور شل، بیابیم؟
[regex]::match("$((Get-ADUser $user -Properties DistinguishedName).DistinguishedName)",'(?=OU=)(.*\n?)').value
چگونه حسابهای کاربری غیرفعال در دایرکتوری فعال را با پاور شل پیدا کنیم؟
1 2 |
Search-ADAccount -AccountDisabled Get-ADUser -Filter {Enabled -ne $true} |
چگونه حسابهای کاربری منقضی شده را در دایرکتوری فعال، با پاور شل بیابیم؟
Search-ADAccount -AccountExpired
چگونه حسابهای کاربری قفل شده را در دایرکتوری فعال، با پاور شل بیابیم؟
Search-ADAccount -LockedOut
چگونه SID را برای یک حساب کاربری در دایرکتوری فعال، با پاور شل بیابیم؟
(Get-ADUser $user -Properties SID).SID.Value
چگونه نام کاربری را در یک دایرکتوری فعال، با را در دایرکتوری فعال، با پاور شل، به SID تبدیل کنیم؟
1 2 |
$user = New-Object -TypeName System.Security.Principal.NTAccount -ArgumentList ('DOMAIN', 'user') $SID = ($user.Translate([System.Security.Principal.SecurityIdentifier])).Value |
چگونه SID را در یک دایرکتوری فعال، به نام کاربری تبدیل کنیم؟
1 2 |
$SID = New-Object -TypeName System.Security.Principal.SecurityIdentifier -ArgumentList ('SID') $user = ($SID.Translate( [System.Security.Principal.NTAccount])).Value |
چگونه نام یک حساب کاربری مشخص را در دایرکتوری فعال، با استفاده از پاور شل، جدا کنیم؟
1 2 3 |
$dn = 'CN=Powershell Test,OU=TEST,DC=domain,DC=com' $dn.Split(',')[0] # Returns "CN=Powershell Test" $dn.Split(',')[0].Split('=')[1] # Returns "Powershell Test" |
چگونه تاریخ ایجاد/ تغییر یک حساب کاربری را در دایرکتوری فعال، با پاور شل بیابیم؟
Get-ADUser -Identity $user -Properties whenChanged, whenCreated | Format-List -Property whenChanged, whenCreated
چگونه خواص انتخابی و اجباری را برای یک کلاس “کاربر” در دایرکتوری فعال، با پاور شل نمایش دهیم؟
1 2 3 |
$schema = [DirectoryServices.ActiveDirectory.ActiveDirectorySchema]::GetCurrentSchema() $schema.FindClass('user').mandatoryproperties | Format-Table $schema.FindClass('user').optionalproperties | Format-Table |
چگونه مسیر LDAP را برای یک کاربر در دایرکتوری فعال، با پاور شل بدست آوریم؟
1 2 3 4 |
$searcher = New-Object -TypeName DirectoryServices.DirectorySearcher -ArgumentList ([ADSI]'') $searcher.Filter = "(&(objectClass=user)(sAMAccountName= $user))" $searcher = $searcher.FindOne() $pathLDAP = $searcher.Path |
چگونه CN (نام کانونیکال) را برای یک کاربر در دایرکتوری فعال، با پاور شل تغییر دهیم؟
Rename-ADObject $((Get-ADUser $user -Properties DistinguishedName).DistinguishedName) -NewName 'Test Powershell'
چگونه واحد سازمان دهی (OU) والد یک کاربر را در دایرکتوری فعال، با پاور شل بیابیم؟
1 2 |
$dn = (Get-ADUser $user -Properties DistinguishedName).DistinguishedName $parent = $dn.Split(',',2)[1] |
چگونه صاحب یک کاربر (کسی که حساب را ایجاد کرده) را در دایرکتوری فعال، با پاور شل بیابیم؟
1 2 |
$dn = (Get-ADUser $user -Properties DistinguishedName).DistinguishedName $owner = (Get-Acl -Path "AD:$dn").Owner |
چگونه خاصیت PwdLastSet برای یک کاربر را در دایرکتوری فعال، با پاور شل بیابیم؟
1 2 3 4 5 |
# Solution 1 [DateTime]::FromFileTime((Get-ADUser $user -Properties pwdLastSet).pwdLastSet) # Solution 2 w32tm /ntte 130787549514737594 |
Computers
چگونه کانال امن را بین کامپیوتر محلی و دامنه، با پاور شل، تست کنیم؟
Test-ComputerSecureChannel
چگونه کانال امن بین کامپیوتر محلی و دامنه را با استفاده از پاور شل، تعمیر کنیم؟
Test-ComputerSecureChannel -Repair
چگونه یک اکانت کامپیوتری را با پاور شل غیر فعال کنیم؟
Disable-ADAccount $computer
چگونه کامپیوترهایی با سیستم عاملی به خصوص را در دایرکتوری فعال، با پاور شل بیابیم؟
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 |
Get-ADComputer -Filter 'OperatingSystem -eq "CentOS"' Get-ADComputer -Filter 'OperatingSystem -eq "GNU/Linux"' Get-ADComputer -Filter 'OperatingSystem -eq "Linux"' Get-ADComputer -Filter 'OperatingSystem -eq "Mac OS X"' Get-ADComputer -Filter 'OperatingSystem -eq "OnTap"' Get-ADComputer -Filter 'OperatingSystem -eq "Red Hat Enterprise Linux Server"' Get-ADComputer -Filter 'OperatingSystem -eq "redhat-linux-gnu"' Get-ADComputer -Filter 'OperatingSystem -eq "Samba"' Get-ADComputer -Filter 'OperatingSystem -eq "Ubuntu"' Get-ADComputer -Filter 'OperatingSystem -eq "Windows NT"' Get-ADComputer -Filter 'OperatingSystem -eq "Windows 2000 Professional"' Get-ADComputer -Filter 'OperatingSystem -eq "Windows 2000 Server"' Get-ADComputer -Filter 'OperatingSystem -eq "Windows XP Professional"' Get-ADComputer -Filter 'OperatingSystem -eq "Windows Server 2003"' Get-ADComputer -Filter 'OperatingSystem -eq "Windows Vista™ Business"' Get-ADComputer -Filter 'OperatingSystem -eq "Windows Vista™ Enterprise"' Get-ADComputer -Filter 'OperatingSystem -eq "Windows Vista™ Entreprise"' Get-ADComputer -Filter 'OperatingSystem -eq "Windows 7 Enterprise"' Get-ADComputer -Filter 'OperatingSystem -eq "Windows 7 Professional"' Get-ADComputer -Filter 'OperatingSystem -eq "Windows 7 Ultimate"' Get-ADComputer -Filter 'OperatingSystem -eq "Windows Server 2008 R2 Enterprise"' Get-ADComputer -Filter 'OperatingSystem -eq "Windows Server 2008 R2 Standard"' Get-ADComputer -Filter 'OperatingSystem -eq "Windows Server® 2008 Enterprise"' Get-ADComputer -Filter 'OperatingSystem -eq "Windows 8 Enterprise"' Get-ADComputer -Filter 'OperatingSystem -eq "Windows 8.1 Enterprise"' Get-ADComputer -Filter 'OperatingSystem -eq "Windows Server 2012 R2 Standard"' Get-ADComputer -Filter 'OperatingSystem -eq "Windows Server 2012 Standard"' |
Organizational Unit (OU)
چگونه یک واحد سازمان دهی (OU) را در دایرکتوری فعال، با پاور شل ایجاد کنیم؟
New-ADOrganizationalUnit -Name 'TEST' -Path 'DC=domain,DC=com'
چگونه جزئیات واحد سازمان دهی (OU) را در دایرکتوری فعال، با پاور شل بدست آوریم؟
Get-ADOrganizationalUnit 'OU=TEST,DC=domain,DC=com' -Properties *
چگونه توضیحات یک واحد سازماندهی (OU) را در دایرکتوری فعال، با پاور شل تغییر دهیم؟
Set-ADOrganizationalUnit 'OU=TEST,DC=domain,DC=com' -Description 'My description'
1 2 3 4 5 |
# Protection ON Set-ADOrganizationalUnit 'OU=TEST,DC=domain,DC=com' -ProtectedFromAccidentalDeletion $true # Protection OFF Set-ADOrganizationalUnit 'OU=TEST,DC=domain,DC=com' -ProtectedFromAccidentalDeletion $false |
چگونه با پاور شل، حذف تصادفی را برای تمام واحدهای سازماندهی در دایرکتوری فعال فعال کنیم؟
1 |
Get-ADOrganizationalUnit -Filter * -Property ProtectedFromAccidentalDeletion | Where-Object -FilterScript { $_.ProtectedFromAccidentalDeletion -eq $false } | Set-ADOrganizationalUnit -ProtectedFromAccidentalDeletion $true |
چگونه با پاور شل، یونیتی را که از حذف تصادفی، حفاظت شده در دایرکتوری فعال، حذف کنیم؟
1 2 |
Set-ADOrganizationalUnit 'OU=TEST,DC=domain,DC=com' -ProtectedFromAccidentalDeletion $false Remove-ADOrganizationalUnit 'OU=TEST,DC=domain,DC=com' |
چگونه با پاور شل نام به خصوص یک واحد سازماندهی را به نام کانونیکال، در دایرکتوری فعال تغییر دهیم؟
1 2 |
$parent = $dn.Split(',',2)[1] $parent = (Get-ADOrganizationalUnit $parent -Properties CanonicalName).CanonicalName |
چگونه با پاور شل، واحدهای نظم دهنده ی خالی را لیست کنیم؟
1 2 3 4 5 |
# Solution 1 Get-ADOrganizationalUnit -Filter * -Property 'msDS-Approx-Immed-Subordinates' | Where-Object -FilterScript {$_.'msDS-Approx-Immed-Subordinates' -eq 0} # Solution 2 ([adsisearcher]'(objectclass=organizationalunit)').FindAll() | Where-Object -FilterScript { (([adsi]$_.Path).PSbase.Children | Measure-Object).Count -eq 0 } |
چگونه با پاور شل، منیجر یک گروه را بدست آوریم؟
(Get-ADGroup $dn -Properties Managedby).Managedby
Regex (Regular Expression)
چگونه با پاور شل، آدرس آی پی ورژن 4 را (80.80.228.8) با استفاده از ریجکس بدست آوریم؟
$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
چگونه با پاور شل، آدرس مک (c0-D9-62-39-61-2D) را با جدا کننده ی “-“، با استفاده از ریجک بدست آوریم؟
$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
چگونه با پاور شل، آدرس مک (C0:D9:62:39:61:2D)، با جدا کننده ی “:” با استفاده از ریجکس بدست آوریم؟
$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
چگونه با پاور شل، تاریخ (10/02./2015) را با ریجکس بدست آوریم؟
$example = 'The date is 10/02/2015'
$date = [regex]::match($example,'(\d{2}\/\d{2}\/\d{4})').value
چگونه با پاور شل، یو آر ال (www.powershell-guru.com) را با ریجکس بدست آوریم؟
$example = 'The URL is www.powershell-guru.com'
$url = [regex]::match($example,'[a-z]+[:.].*?(?=\s)').value
چگونه با پاور شل، یک ایمیل (user@domain.com) را با ریجکس بدست آوریم؟
$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
چگونه با پاور شل، “guru” را از دنباله ی نمونه با ریجکس بدست آوریم؟
$example = 'www.powershell-guru.com'
[regex]::match($example,'(?<=-)(.*\n?)(?=.com)').value
چگونه با پاور شل، “guru.com” را از دنباله ی نمونه با ریجکس بدست آوریم؟
$example = 'www.powershell-guru.com'
[regex]::match($example,'(?<=-)(.*\n?)(?<=.)').value
چگونه با پاور شل، “powershell-guru.com” را از دنباله ی نمونه با ریجکس بدست آوریم؟
$example = 'www.powershell-guru.com'
[regex]::match($example,'(?<=www.)(.*\n?)').value
چگونه با پاور شل، “123” را با ریجکس از دنباله ی نمونه بدست آوریم؟
$example = 'Powershell123'
[regex]::match($example,'(\d+)').value
چگونه با پاور شل، “$” (علامت دلار) را با ریجکس از دنباله نمونه بدست آوریم؟
$example = 'Powershell`$123'
[regex]::match($example,'(\$)').value
چگونه با پاور شل، یک کاراکتر (*.com) را با کاراکتری دیگر (*.fr) در دنباله با ریجکس جایگزین کنیم؟
$example = 'www.powershell-guru.com'
[regex]::Replace($example, '.com','.fr')
چگونه با پاور شل، از یک دنباله با ریجکس گذر کنیم؟
[regex]::Escape('\\server\share')
Memory
چگونه با پاور شل، جمع آوری حافظه را با جمع آور گاربج تحمیل کنیم؟
[System.GC]::Collect()
[System.GC]::WaitForPendingFinalizers()
چگونه با پاور شل، سایز حافظه ی رم را برای یک کامپیوتر بیابیم؟
1 2 3 4 5 6 7 8 |
# Solution 1 Get-CimInstance -ClassName 'cim_physicalmemory' | ForEach-Object -Process {$_.Capacity /1GB} # Solution 2 (Get-WmiObject -Class Win32_ComputerSystem).TotalPhysicalMemory /1GB # Solution 3 (systeminfo.exe | Select-String -Pattern 'Total Physical Memory:').ToString().Split(':')[1].Trim() |
Date
چگونه با پاور شل، تاریخ کنونی را بیابیم؟
Get-Date
[Datetime]::Now
چگونه با پاور شل، تاریخ را در فرمتهای گوناگون نمایش دهیم؟
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 |
### DATETIME ### Get-Date -Format D : Tuesday, June 30, 2015 Get-Date -Format f : Tuesday, June 30, 2015 3:22 PM Get-Date -Format F : Tuesday, June 30, 2015 3:22:58 PM Get-Date -Format g : 6/30/2015 3:23 PM Get-Date -Format G : 6/30/2015 3:23:30 PM Get-Date -DisplayHint Date : Tuesday, June 30, 2015 Get-Date -DisplayHint DateTime : Tuesday, June 30, 2015 3:31:21 PM ### DATE ### Get-Date -Format d : 6/30/2015 Get-Date -Format yyyyMMdd : 20150630 Get-Date -UFormat '%d%m%Y' : 30062015 Get-Date -UFormat '%m%d%Y' : 06302015 Get-Date -UFormat '%Y%m%d' : 20150630 Get-Date -UFormat '%d.%m.%Y' : 30.06.2015 Get-Date -UFormat '%m.%d.%Y' : 06.30.2015 Get-Date -UFormat '%Y.%m.%d' : 2015.06.30 Get-Date -UFormat '%d-%m-%Y' : 30-06-2015 Get-Date -UFormat '%m-%d-%Y' : 06-30-2015 Get-Date -UFormat '%Y-%m-%d' : 2015-06-30 Get-Date -UFormat '%d/%m/%Y' : 30/06/2015 Get-Date -UFormat '%m/%d/%Y' : 06/30/2015 Get-Date -UFormat '%Y/%m/%d' : 2015/06/30 ### HOUR ### Get-Date -Format t : 3:23 PM Get-Date -Format T : 3:23:30 PM Get-Date -Format HH : 15 (Hour) Get-Date -Format mm : 28 (Minute) Get-Date -Format ss : 30 (Seconds) Get-Date -DisplayHint Time : 3:23:30 PM ### DAY ### Get-Date -Format dddd : Tuesday Get-Date -Format ddd : Tue Get-Date -Format dd : 30 ### MONTH ### Get-Date -Format MMMM : June Get-Date -Format MMM : Jun Get-Date -Format MM : 06 ### YEAR ### Get-Date -Format yyyy : 2015 |
چگونه با پاور شل، تاریخ (زمان تاریخ) را به یک دنباله تبدیل کنیم؟
1 2 3 4 5 6 7 8 9 10 11 12 13 |
# Solution 1 $datetimeToString = '{0:MM/dd/yy}' -f (Get-Date '07/15/2015') # Solution 2 $datetimeToString = (Get-Date '07/15/2015').ToShortDateString() # Check $datetimeToString 07/15/15 $datetimeToString.GetType().Name String |
چگونه با پاور شل، یک دنباله ی تاریخ را به تاریخ (زمان تاریخ) تبدیل کنیم؟
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
# Solution 1 $stringToDatetime = '07/15/2015' | Get-Date $stringToDatetime = '07-15-2015' | Get-Date # Solution 2 $stringToDatetime = [Datetime]::ParseExact('07/15/2015', 'MM/dd/yyyy', $null) # Solution 3 $stringToDatetime = [Datetime]"7/15/2015" # Check $stringToDatetime Wednesday, July 15, 2015 12:00:00 AM $stringToDatetime.GetType().Name Datetime |
چگونه با پاور شل، اختلاف بین دو تاریخ (روز، ساعت، دقایق، یا ثانیه ها) را محاسبه کنیم؟
(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
چگونه با پاور شل، دو تاریخ را مقایسه کنیم؟
(Get-Date 2015-01-01) -lt (Get-Date 2015-01-30) # True
(Get-Date 2015-01-01) -gt (Get-Date 2015-01-30) # False
چگونه با پاور شل، آرایه ای از تاریخهای را منظم کنیم؟
$arrayDate | Sort-Object -Property {$_ -as [Datetime]}
چگونه با پاور شل، یک زمان گیر را شروع و خاتمه دهیم؟
$chrono = [Diagnostics.Stopwatch]::StartNew()
$chrono.Stop()
$chrono
چگونه با پاور شل، روز هفته را بدست آوریم؟
(Get-Date).DayOfWeek #Sunday
چگونه با پاور شل، تاریخ دیروز را بدست آوریم؟
(Get-Date).AddDays(-1)
چگونه با پاور شل، تعداد روزهای ماه (در فوریه 2015) را بدست آوریم؟
[DateTime]::DaysInMonth(2015, 2)
چگونه با پاور شل، سال کبیثه را تشخیص دهیم؟
[DateTime]::IsLeapYear(2015)
چگونه با پاور شل، زمان های مختلف را لیست کنیم؟
[System.TimeZoneInfo]::GetSystemTimeZones()
Networking
چگونه با پاور شل، به فرمت ASCII انکد، و یک URL را دیکد کنیم؟
1 2 3 4 5 6 7 8 9 |
# Encode $url = 'http://www.powershell-guru.com' $encoded = [System.Web.HttpUtility]::UrlEncode($url) # Decode $decoded = [System.Web.HttpUtility]::UrlDecode($encoded) # Encoded : http%3a%2f%2fwww.powershell-guru.com # Decoded : http://www.powershell-guru.com |
دستورات معادل شبکه ی بومی با پاور شل چه هستند؟
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
# ipconfig Get-NetIPConfiguration Get-NetIPAddress # ping Test-NetConnection # tracert Test-NetConnection -TraceRoute # route Get-NetRoute # nslookup Resolve-DnsName # Windows 8.1 & Windows 2012 ([System.Net.Dns]::GetHostEntry($IP)).Hostname # IP > PC ([System.Net.Dns]::GetHostAddresses($computer)).IPAddressToString # PC > IP |
چگونه با پاور شل، آدرس آی پی را بگیریم؟
Get-NetIPAddress # Windows 8.1 & Windows 2012
Get-NetIPConfiguration # Windows 8.1 & Windows 2012
چگونه با پاور شل، آی پی ورژن شش را غیر فعال کنیم؟
1 |
New-ItemProperty -Path 'HKLM:\SYSTEM\CurrentControlSet\Services\Tcpip6\Parameters' -Name 'DisabledComponents' -Value '0xFFFFFFFF' -PropertyType"DWORD" # Reboot required |
چگونه با پاور شل، آی پی ورژن چهار را مقدار دهی کنیم؟
if([ipaddress]'10.0.0.1'){'validated'}
چگونه با پاور شل، آی پی را بیابیم؟
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
# Solution 1 (Invoke-WebRequest -Uri 'myexternalip.com/raw').Content (iwr -Uri 'myexternalip.com/raw').Content # Alias # Solution 2 $webClient = New-Object -TypeName System.Net.WebClient $webClient.DownloadString('http://myexternalip.com/raw') # Solution 3 while ($true) { Write-Output -InputObject "$(Get-Date) - $((Invoke-WebRequest -Uri 'http://myexternalip.com/raw' -Method Get).Content)" Start-Sleep -Seconds 300 } |
چگونه با پاور شل، نام هاست را از یک آدرس آی پی بیابیم؟
([System.Net.Dns]::GetHostEntry($IP)).Hostname
چگونه آدرس آی پی را از یک نام هاست با پاور شل بیابیم؟
([System.Net.Dns]::GetHostAddresses($computer)).IPAddressToString
چگونه با پاور شل، FQDN را از یک نام هاست بیابیم؟
[System.Net.Dns]::GetHostByName($computer).HostName
چگونه با پاور شل، مشخصات شبکه (IP, Subnet, Gateway, and DNS) را بیابیم؟
1 |
Get-WmiObject -Class Win32_NetworkAdapterConfiguration | Format-Table -Property Description, IpAddress, IPSubnet, DefaultIPGateway, DNSServerSearchOrder |
چگونه با پاور شل، آدرس مک را پیدا کنیم؟
Get-CimInstance win32_networkadapterconfiguration | Select-Object -Property Description, Macaddress
Get-WmiObject -Class win32_networkadapterconfiguration | Select-Object -Property Description, Macaddress
چگونه با پاور شل، یک کامپیوتر را پینگ کنیم؟
1 2 3 4 5 6 |
# Solution 1 Test-Connection -ComputerName $computer -Quiet # Returns True / False # Solution 2 $ping = New-Object -TypeName System.Net.Networkinformation.Ping $ping.Send($computer) |
چگونه با پاور شل، اطمینان حاصل کنیم که کامپیوتر به اینترنت متصل است؟
1 |
[Activator]::CreateInstance([Type]::GetTypeFromCLSID([Guid]'{DCB00C01-570F-4A9B-8D69-199FDBA5723B}')).IsConnectedToInternet |
چگونه با پاور شل، “whois” را برای یک وبسایت پیاده کنیم؟
$whois = New-WebServiceProxy 'http://www.webservicex.net/whois.asmx?WSDL'
$whois.GetWhoIs('powershell-guru.com')
چگونه با پاور شل، جزئیات یک آی پی عمومی را بدست آوریم؟
1 2 |
$externalIP = (Invoke-WebRequest -Uri 'myexternalip.com/raw').Content $detailsIP = ([xml](Invoke-WebRequest -Uri "http://freegeoip.net/xml/$externalIP" -UseBasicParsing).Content).Response |
چگونه با پاور شل، چک کنیم که یک پورت باز/بسته است؟
New-Object -TypeName Net.Sockets.TcpClient -ArgumentList $computer, 135
چگونه با پاور شل، یک “tracert” پیاده کنیم؟
Test-NetConnection www.google.com -TraceRoute
چگونه با پاور شل، اتصالات یک شبکه ی خانگی را تصحیح کنیم؟
Get-NetAdapter | Format-Table -Property Name, InterfaceDescription, ifIndex -AutoSize # Windows 8.1
Set-NetConnectionProfile -InterfaceIndex 6 -NetworkCategory Private
چگونه با پاور شل، اتصالات پورت TCP را نمایش دهیم؟
netstat.exe -ano
Get-NetTCPConnection #Windows 8 and 2012
چگونه با پاور شل، یک یو آر ال طویل را مختصر کنیم؟
$url = 'www.powershell-guru.com'
$tiny = Invoke-RestMethod -Uri "http://tinyurl.com/api-create.php?url=$url"
چگونه با پاور شل، تنظیمات پروکسی را ایجاد کنیم؟
Get-ItemProperty -Path HKCU:"Software\Microsoft\Windows\CurrentVersion\Internet Settings"
DNS
چگونه با پاور شل، DNS cache را برای یک کامپیوتر محلی چک کنیم؟
ipconfig.exe /displaydns
Get-DnsClientCache #Windows 8 and 2012
چگونه با پاور شل، DNS Cache را برای یک کامپیوتر محلی خالی کنیم؟
ipconfig.exe /flushdns
Start-Process -FilePath ipconfig -ArgumentList /flushdns -WindowStyle Hidden
Clear-DnsClientCache #Windows 8 and 2012
چگونه با پاور شل، DNS cache را برای یک کامپوتر غیر محلی خالی کنیم؟
Invoke-Command -ScriptBlock {Clear-DnsClientCache} -ComputerName computer01, computer02
چگونه با پاور شل، فایلهای هاست را بخوانیم؟
Get-Content -Path 'C:\Windows\system32\drivers\etc\hosts'
Password
چگونه با پاور شل، یک پسوورد تصادفی ایجاد کنیم؟
[Reflection.Assembly]::LoadWithPartialName('System.Web')
[System.Web.Security.Membership]::GeneratePassword(30,2)
چگونه با پاور شل، پسوورد محلی یک ادمین را روی سرور از راه دور، تغییر دهیم؟
$admin = [ADSI]('WinNT://server01/administrator,user')
$admin.SetPassword($password)
$admin.SetInfo()
چگونه با پاور شل، تاریخ انقضای پسوورد یک حساب را در دایرکتوری فعال بیابیم؟
1 2 3 4 5 6 7 8 |
# Solution 1 [DateTime]::FromFileTime((Get-ADUser -Identity $user -Properties 'msDS-UserPasswordExpiryTimeComputed').'msDS-UserPasswordExpiryTimeComputed') # Solution 2 Get-Date -Date ((Get-ADUser $user -Properties 'msDS-UserPasswordExpiryTimeComputed' | Select-Object -Property @{ Name = 'ExpiryDate' Expression = {[DateTime]::FromFileTime($_.'msDS-UserPasswordExpiryTimeComputed')} }).ExpiryDate)-Format 'F' |
Printers
چگونه با پاور شل، تمام پرینترهای یک سرور خاص را لیست کنیم؟
Get-WmiObject -Query 'Select * From Win32_Printer' -ComputerName $computer
چگونه با پاور شل، تمام پورتهای یک سرور خاص را لیست کنیم؟
Get-WmiObject -Class Win32_TCPIPPrinterPort -Namespace 'root\CIMV2' -ComputerName $computer
چگونه با پاور شل، توضیح/مکان یک پرینتر را تغییر دهیم؟
1 2 3 4 |
$printer = Get-WmiObject -Class win32_printer -Filter "Name='HP Deskjet 2540 series'" $printer.Location = 'Germany' $printer.Comment = 'Printer - Test' $printer.Put() |
چگونه با پاور شل، تمام کارهای یک پرینتر را کنسل کنیم؟
$printer = Get-WmiObject -Class win32_printer -Filter "Name='HP Deskjet 2540 series'"
$printer.CancelAllJobs()
چگونه با پاور شل، یک صفحه ی امتحانی از پرینتر چاپ کنیم؟
$printer = Get-WmiObject -Class win32_printer -Filter "Name='HP Deskjet 2540 series'"
$printer.PrintTestPage()
چگونه با پاور شل، صف چاپ ها را برای یک پرینتر بدست آوریم؟
1 2 3 4 |
Get-WmiObject -Class Win32_PerfFormattedData_Spooler_PrintQueue | Select-Object -Property Name, @{ Expression = {$_.jobs} Label = 'Current Jobs' } | Format-Table -AutoSize |
Regedit
Read
چگونه با پاور شل، هایوهای رجیستری را لیست کنیم؟
Get-ChildItem -Path Registry::
چگونه با پاور شل، مقادیر رجیستری و انواع آنها را بدست آوریم؟
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 |
function Get-RegistryValue { Param ( [Parameter(Mandatory = $true)] [string]$RegistryKey ) $key = Get-Item -Path "Registry::$RegistryKey" $key.GetValueNames() | Sort-Object | ForEach-Object -Process { $name = $_ $type = $key.GetValueKind($name) switch ($type) { 'String' {'REG_SZ'} 'Binary' {'REG_BINARY'} 'Dword' {'REG_DWORD'} 'Qword' {'REG_QWORD'} 'MultiString' {'REG_MULTI_SZ'} 'ExpandString'{'REG_EXPAND_SZ'} Default {$null} } [PSCustomObject]@{ Name = $name Type = $type Data = $key.GetValue($name) } } } |
چگونه با پاور شل، کلیدهای رجیستری را لیست کنیم؟
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
#HKEY_CLASSES_ROOT New-PSDrive -PSProvider Registry -Root HKEY_CLASSES_ROOT -Name HKCR Get-ChildItem -Path 'HKCR:\' #HKEY_CURRENT_USER Get-ChildItem -Path 'HKCU:\Software' Get-ChildItem -Path Registry::HKEY_CURRENT_USER #HKEY_LOCAL_MACHINE Get-ChildItem -Path 'HKLM:\SYSTEM' Get-ChildItem -Path Registry::HKEY_LOCAL_MACHINE #HKEY_USERS New-PSDrive -PSProvider Registry -Root HKEY_USERS -Name HKU Get-ChildItem -Path 'HKU:\' #HKEY_CURRENT_CONFIG New-PSDrive -PSProvider Registry -Root HKEY_CURRENT_CONFIG -Name HKCC Get-ChildItem -Path 'HKCC:\' |
چگونه با پاور شل، کلیدهای رجیستری را بطور تکرار شونده لیست کنیم؟
Get-ChildItem -Path 'HKLM:\SYSTEM' -Recurse -ErrorAction SilentlyContinue
چگونه با پاور شل، کلید با یک نام بخصوص را بیابیم؟
Get-ChildItem -Path 'HKLM:\SOFTWARE' -Include *Plugin* -Recurse -ErrorAction SilentlyContinue
چگونه با پاور شل، فقط نام یک کلید رجیستری را برگردانیم؟
(Get-ChildItem -Path 'HKLM:\SYSTEM').Name # Return HKEY_LOCAL_MACHINE\SYSTEM\ControlSet
Get-ChildItem -Path 'HKLM:\SYSTEM' -Name # Return ControlSet
چگونه با پاور شل، مقادیر رجیستری را لیست کنیم؟
Get-ItemProperty -Path 'HKLM:\SOFTWARE\Microsoft\Windows NT\CurrentVersion'
چگونه با پاور شل، مقادیر یک رجیستری خاص را بخوانیم؟
(Get-ItemProperty -Path 'HKLM:\SOFTWARE\Microsoft\Windows NT\CurrentVersion').ProductName
چگونه با پاور شل، مقادیر یک رجیستری خاص را روی یک کامپیوتر از راه دور بخوانیم؟
1 2 3 4 5 |
$hostname = $computer $openRegedit = [Microsoft.Win32.RegistryKey]::OpenRemoteBaseKey('LocalMachine', $hostname) $openKey = $openRegedit.OpenSubKey('SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion') $keyValue = $openKey.GetValue('ProductName') $keyValue |
Write
چگونه با پاور شل، یک کلید رجیستری جدید ایجاد کنیم؟
New-Item -Path 'HKCU:\Software\MyApplication'
چگونه با پاور شل، مقادیر یک رجیستری را ایجاد کنیم؟
New-ItemProperty -Path 'HKCU:\Software\MyApplication' -Name 'Version' -Value '1.0'
چگونه با پاور شل، مقادیر یک رجیستری موجود را تغییر دهیم؟
Set-ItemProperty -Path 'HKCU:\Software\MyApplication' -Name 'Version' -Value '2.0'
Delete
چگونه با پاور شل، مقادیر یک رجیستری را پاک کنیم؟
Remove-ItemProperty -Path 'HKCU:\Software\MyApplication' -Name 'Version'
چگونه با پاور شل، کلید یک رجیستری را پاک کنیم؟
Remove-Item -Path 'HKCU:\Software\MyApplication' -Force
Test
چگونه با پاور شل، چک کنیم که یک کلید رجیستری موجود هست یا خیر؟
Test-Path -Path 'HKCU:\Software\MyApplication'
چگونه با پاور شل، از موجودیت مقدار یک رجیستری اطمینان حاصل کنیم؟
(Get-Item -Path 'HKCU:\Software\MyApplication').GetValueNames() -contains 'Version'
Strings
چگونه با پاور شل، کاراکترهای فواصل سفید را از آغاز یک دنباله حذف کنیم؟
$string = ' PowershellGuru'
$string = $string.TrimStart()
چگونه با پاور شل، کاراکترهای فواصل سفید را از پایان یک دنباله حذف کنیم؟
$string = 'PowershellGuru '
$string = $string.TrimEnd()
چگونه با پاور شل، کاراکترهای فواصل سفید را (از آغاز و پایان) یک دنباله حذف کنیم؟
$string = ' PowershellGuru '
$string = $string.Trim()
چگونه با پاور شل، یک دنباله را به حروف بزرگ تبدیل کنیم؟
$string = 'powershellguru'
$string = $string.ToUpper()
چگونه با پاور شل، یک دنباله را به حروف کوچک تبدیل کنیم؟
$string = 'POWERSHELLGURU'
$string = $string.ToLower()
چگونه با پاور شل، زیر دنباله ی “PowerShell” را از دنباله ی “PowerShellGuru” انتخاب کنیم؟
$string.Substring(0,10)
چگونه با پاور شل، زیر دنباله ی “Guru” را از دنباله ی “PowerShellGuru” انتخاب کنیم؟
$string.Substring(10)
چگونه با پاور شل، زیر دنباله ی “123” را از دنباله ی “PowerShell123Guru” انتخاب کنیم؟
$string = 'Powershell123Guru'
[regex]::match($string,'(\d+)').value
چگونه با پاور شل، ایندکس zero-based را از دنباله ی “PowerShellGuru” بگیریم؟
$string.IndexOf('Guru') # 10
چگونه با پاور شل، چک کنیم که یک دنباله نال است یا خیر؟
$string = $null
$string = ''
[string]::IsNullOrEmpty($string)
چگونه با پاور شل، چک کنیم که یک دنباله نال، خالی است، یا کاراکترهای فاصله دارند؟
$string = $null
$string = ''
$string = ' '
[string]::IsNullOrWhiteSpace($string)
چگونه با پاور شل، چک کنیم که یک دنباله، حرفی به خصوص دارد یا خیر؟
$string = 'PowershellGuru'
$string.Contains('s')
[regex]::match($string,'s').Success
چگونه با پاور شل، طول یک دنباله را برگردانیم؟
$string.Length
چگونه با پاور شل، دو دنباله را به هم بچسبانیم؟
1 2 3 4 5 6 7 |
# Solution 1 $string1 + $string2 # Solution 2 $string1 = 'Powershell' $string2 = 'Guru' [string]::Concat($string1,$string2) |
چگونه با پاور شل، یک یا چند براکت “[ ]” را در یک دنباله تنظیم کنیم؟
$string = '[PowershellGuru]'
$string -match '\[' # Only 1
$string -match '\[(.*)\]' # Several
چگونه با پاور شل، یک یا چند پرانتز “( )” را در یک دنباله تنظیم کنیم؟
$string = '(PowershellGuru)'
$string -match '\(' # Only 1
$string -match '\((.*)\)' # Several
چگونه با پاور شل، یک یا چند آکولاد “{ }” را در یک دنباله تنظیم کنیم؟
$string = '{PowershellGuru}'
$string -match '\{' # Only 1
$string -match '\{(.*)\}' # Several
چگونه با پاور شل، یک یا چند براکت “< >” را در یک دنباله تنظیم کنیم؟
$string = ''
$string -match '\<' # Only 1
$string -match "\<(.*)\>" # Several
چگونه با پاور شل، همه ی حروف کوچک (abc) را در یک دنباله تنظیم کنیم؟
$string = 'POWERSHELLGURU'
$string -cmatch "^[a-z]*$" #False
چگونه با پاور شل، همه ی حروف بزرگ (ABC) را در یک دنباله تنظیم کنیم؟
$string = 'powershellguru'
$string -cmatch "^[A-Z]*$" #False
چگونه با پاور شل، “[p” (حرف کوچک P) را در یک دنباله تنظیم کنیم؟
$string = '[powershellGuru]'
$string -cmatch '\[[a-z]\w+' #True
چگونه با پاور شل، “[P” (حرف بزرگ P) را در یک دنباله تنظیم کنیم؟
$string = '[PowershellGuru]'
$string -cmatch '\[[A-Z]\w+' #True
چگونه با پاور شل، یک خط را با خطی دیگر جایگزین کنیم؟
$a = 'Line A'
$b = 'Line B'
$a = $a -replace $a, $b
چگونه با پاور شل، یک عملگر تقسیم را به یک دنباله (درصد) تبدیل کنیم؟
(1/2).ToString('P')
چگونه با پاور شل، دنباله ی اعداد را ترتیب دهیم؟
1 |
'string-10', 'string-2', 'string-23', 'string-30' | Sort-Object -Property {$_ -replace '[\d]'}, {$_ -replace '[a-zA-Z\p{P}]'-as [int]} |
چگونه با پاور شل، آخرین کلمه ی یک جمله را انتخاب کنیم؟
$sentence = 'My name is Test Powershell'
$sentence.Split(' ')[-1] # Returns Powershell
چگونه با پاور شل، بزرگترین کلمه ی یک جمله را انتخاب کنیم؟
$sentence = 'My name is Test Powershell'
$sentence.Split(' ') | Sort-Object -Property Length | Select-Object -Last 1 # Returns Powershell
چگونه با پاور شل، تعداد دفعاتی که یک دنباله در یک جمله تکرار شده را بشماریم؟
$sentence = 'test test test Powershell'
[regex]::Matches($sentence, 'test').Count # Returns 3
چگونه با پاور شل، هر کاراکتر در یک دنباله را در یک آرایه ی کاراکترها کپی کنیم؟
1 2 3 4 5 6 7 |
$name = 'test' $name.ToCharArray() s t e v e |
چگونه با پاور شل، اولین حرف یک دنباله را به حرف بزرگ تبدیل کنیم؟
1 2 |
$name = 'test' $name.Substring(0,1).ToUpper() + $name.Substring(1) |
چگونه با پاور شل، یک دنباله را پد (چپ به راست) کنیم؟
1 2 3 4 5 6 7 |
# With whitespaces $padRight = 'test'.PadRight(25) $padLeft = 'test'.PadLeft(25) # With characters $padRight = 'test'.PadRight(25,'.') # Return test.................... $padLeft = 'test'.PadLeft(25,'.') # Return ....................test |
چگونه با پاور شل، یک دنباله را به Base64 انکد و دیکد کنیم؟
1 2 3 4 5 6 7 8 9 10 |
# Encode $string = [System.Text.Encoding]::UTF8.GetBytes('test') $encoded = [System.Convert]::ToBase64String($string) # Decode $string = [System.Convert]::FromBase64String($encoded) $decoded = [System.Text.Encoding]::UTF8.GetString($string) # Encoded : c3RldmU= # Decoded : test |
چگونه با پاور شل، یک عدد را (از و به) باینری تبدیل کنیم؟
1 2 3 4 5 |
# Base 10 to Base 2 [System.Convert]::ToString(255,2) # Base 2 to Base 10 [System.Convert]::ToInt32('11111111',2) |
چگونه با پاور شل، تنها آخرین فولدر والد را در یک مسیر برگردانیم؟
1 2 |
$path = 'C:\Folder1\Folder2\Folder3\file.txt' Split-Path -Path (Split-Path -Path $path -Parent) -Leaf # Return Folder3 |
چگونه با پاور شل، تنها آخرین آیتم را در یک مسیر برگردانیم؟
1 2 |
$path = 'C:\Folder1\Folder2\Folder3\file.txt' Split-Path -Path $path -Leaf # Return file.txt |
Math
چگونه با پاور شل، متدهای یک کلاس System.Math را لیست کنیم؟
[System.Math] | Get-Member -Static -MemberType Method
چگونه با پاور شل، قدر مطلق یک مقدار را برگردانیم؟
[Math]::Abs(-12) #Returns 12
[Math]::Abs(-12.5) # Returns 12.5
چگونه با پاور شل، زاویه ای که سینوسش مقدار خاصیست را برگردانیم؟
[Math]::ASin(1) #Returns 1,5707963267949
چگونه با پاور شل، سقف یک مقدار را برگردانیم؟
[Math]::Ceiling(1.4) #Returns 2
[Math]::Ceiling(1.9) #Returns 2
چگونه با پاور شل، کف یک مقدار را برگردانیم؟
[Math]::Floor(1.4) #Returns 1
[Math]::Floor(1.9) #Returns 1
چگونه با پاور شل، لگاریتم طبیعی (base e) را برای یک عدد برگردانیم؟
[Math]::Log(4) #Returns 1,38629436111989
چگونه با پاور شل، لگاریتم پایه ده را برای یک عدد برگردانیم؟
[Math]::Log10(4) #Returns 0,602059991327962
چگونه با پاور شل، ماکزیمم دو مقدار را برگردانیم؟
[Math]::Max(2,4) #Returns 4
[Math]::Max(-2,-4) #Returns -2
چگونه با پاور شل، مینیمم دو مقدار را برگردانیم؟
[Math]::Min(2,4) #Returns 2
[Math]::Max(-2,-4) #Returns -4
چگونه با پاور شل، عددی با توانی به خصوص را برگردانیم؟
[Math]::Pow(2,4) #Returns 16
چگونه با پاور شل، نزدیکترین مقدار یک انتگرال را با مقدار ده دهی برگردانیم؟
[Math]::Round(3.111,2) #Returns 3,11
[Math]::Round(3.999,2) #Returns 4
چگونه با پاور شل، مقدار انتگرال یک عدد ده دهی را برگردانیم؟
[Math]::Truncate(3.111) #Returns 3
[Math]::Truncate(3.999) #Returns 3
چگونه با پاور شل، توان دوی یک عدد را برگردانیم؟
[Math]::Sqrt(16) #Returns 4
چگونه با پاور شل، PI ی دائمی را برگردانیم؟
[Math]::Pi #Returns 3,14159265358979
چگونه با پاور شل، پایه ی طبیعی لگاریتم (constant e) را برگردانیم؟
[Math]::E #Returns 2,71828182845905
چگونه با پاور شل، زوج یا فرد بودن یک عدد را چک کنیم؟
[bool]($number%2)
Hashtables
چگونه با پاور شل، یک جدول هش خالی ایجاد کنیم؟
$hashtable = @{}
$hashtable = New-Object -TypeName System.Collections.Hashtable
چگونه با پاور شل، یک جدول هش و مقادیر ایجاد کنیم؟
1 2 3 4 5 |
$hashtable = @{ 'Key1' = 'Value1' 'Key2' = 'Value2' 'Key3' = 'Value3' } |
چگونه با پاور شل، یک جدول هش سورت شده با نام کلید (ترتیب الفبایی) اشیا را ایجاد کنیم؟
1 2 3 4 5 6 7 |
$hashtable = [ordered]@{ 'Key1' = 'Value1' 'Key2' = 'Value2' 'Key3' = 'Value3' } $hashtable | Get-Member # System.Collections.Specialized.OrderedDictionary |
چگونه با پاور شل، آیتمهایی را به جدول هش اضافه کنیم؟
$hashtable.Add('Key3', 'Value3')
چگونه با پاور شل، مقداری ویژه برای یک جدول هش بدست آوریم؟
$hashtable.Key1
$hashtable.Get_Item('Key1')
چگونه با پاور شل، مقدار مینیمم را برای یک جدول هش بدست آوریم؟
1 2 3 4 5 6 7 8 |
$hashtable = @{ 'Key1' = '1' 'Key2' = '2' 'Key3' = '3' } $hashtable.GetEnumerator() | Sort-Object -Property Value | Select-Object -First 1 $hashtable.GetEnumerator() | Sort-Object -Property Value -Descending | Select-Object -Last 1 |
چگونه با پاور شل، مقدار ماکزیمم را برای یک جدول هس بدست آوریم؟
1 2 3 4 5 6 7 8 |
$hashtable = @{ 'Key1' = '1' 'Key2' = '2' 'Key3' = '3' } $hashtable.GetEnumerator() | Sort-Object -Property Value -Descending | Select-Object -First 1 $hashtable.GetEnumerator() | Sort-Object -Property Value | Select-Object -Last 1 |
چگونه با پاور شل، آیتمهای یک جدول هش را تغییر دهیم؟
$hashtable.Set_Item('Key1', 'Value1Updated')
چگونه با پاور شل، آیتمهای یک جدول هش را حذف کنیم؟
$hashtable.Remove('Key1')
چگونه با پاور شل، یک جدول هش را خالی کنیم؟
$hashtable.Clear()
چگونه با پاور شل، از وجود یک مقدار/کلید در یک جدول هش اطمینان حاصل کنیم؟
$hashtable.ContainsKey('Key3')
$hashtable.ContainsValue('Value3')
چگونه با پاور شل، کلید/مقادیر را در یک جدول هش نظم دهیم؟
$hashtable.GetEnumerator() | Sort-Object -Property Name
$hashtable.GetEnumerator() | Sort-Object -Property Value -Descending
Arrays
چگونه با پاور شل، یک آرایه ی خالی ایجاد کنیم؟
$array = @()
$array = [System.Collections.ArrayList]@()
چگونه با پاور شل، یک آرایه با مقادیر ایجاد کنیم؟
$array = @('A', 'B', 'C')
$array = 'A', 'B', 'C'
$array = 'a,b,c'.Split(',')
$array = .{$args} a b c
$array = echo a b c
چگونه با پاور شل، آیتمهایی را به یک آرایه اضافه کنیم؟
$array += 'D'
[void]$array.Add('D')
چگونه با پاور شل، یک آیتم را در یک آرایه عوض کنیم؟
$array[0] = 'Z' # 1st item[0]
چگونه با پاور شل، اندازه ی یک آرایه را چک کنیم؟
$array = 'A', 'B', 'C'
$array.Length # Returns 3
چگونه با پاور شل، یک/چند/همه ی آیتمهای یک آرایه را استخراج کنیم؟
$array = @('A', 'B', 'C')
$array[0] # One item (A)
$array[0] + $array[2] # Several items (A,C)
$array # All items (A,B,C)
چگونه با پاور شل، آیتمهای خالی را از یک آرایه حذف کنیم؟
$array = @('A', 'B', 'C', '')
$array = $array.Split('',[System.StringSplitOptions]::RemoveEmptyEntries) | Sort-Object # A,B,C
چگونه با پاور شل، چک کنیم که آیتمی در یک آرایه وجود دارد یا خیر؟
$array = @('A', 'B', 'C')
'A' | ForEach-Object -Process {$array.Contains($_)} # Returns True
'D' | ForEach-Object -Process {$array.Contains($_)} # Returns False
چگونه با پاور شل، ایندکس یک آیتم را در یک آرایه بدست آوریم؟
$array = @('A', 'B', 'C')
[array]::IndexOf($array,'A') # Returns 0
چگونه با پاور شل، ترتیب آیتمهای یک آرایه را برعکس کنیم؟
$array = @('A', 'B', 'C')
[array]::Reverse($array) # C,B,A
چگونه با پاور شل، یک آیتم تصادفی در یک آرایه ایجاد کنیم؟
$array | Get-Random
چگونه با پاور شل، یک آرایه را از کوچک به بزرگ یا برعکس ترتیب دهیم؟
$array = @('A', 'B', 'C')
$array | Sort-Object # A,B,C
$array | Sort-Object -Descending # C,B,A
چگونه با پاور شل، تعداد آیتمهای یک آرایه را شمارش کنیم؟
$array.Count
چگونه با پاور شل، یک آرایه را به دیگری اضافه کنیم؟
$array1 = 'A', 'B', 'C'
$array2 = 'D', 'E', 'F'
$array3 = $array1 + $array2 # A,B,C,D,E,F