powershell

اشکان نصیرزاده

اشکان نصیرزاده

کمک گرفتن در powershell ورژن powershell
غربال گری نتایج در powershell مدیریت دیسک ها در powershell کار با user ها و group ها در powershell حلقه ها ، شروط ، متغیر ها کار با فایل ها در powershell کار با process ها و service ها مثال ها: موارد دیگر: administrator کاربر را فعال کردن web و powershell چندین چیز دیگر!

کمک گرفتن در powershell

command های powershell را cmdlets می نامیم ( یا همون command let) و برای کمک گرفتن در پاورشل دستور اصلی Get-Help است اما می توان از دستورات help و man نیز استفاده کرد.

Get-Help dir
man dir
help dir

من جمله سوویچ های مهم در این رابطه عبارتند از :

help dir -showWindow
help dir -Detailed
help dir -examples
help dir -Full
help *user*

اگر مثلا examples ها رو براتون نمیاره باید از فرمان زیر استفاده بکنید:

Update-Help

ورژن powershell

برای اینکه بفهمید آخرین ورژن کدام است باید عبارت windows management framework latest download رو تو گوگل سرچ کنید .

$PSVersionTable

غربال گری نتایج در powershell

اولا می تونید از از سرتیتر ها به شکل سوییچ استفاده کنید مثلا در مثال زیر تمام آیتم هایی که نام آنها d دارد را می گیریم:

dir -Name *d*

دوما باید کار با استرینگ ها در powershell را بلد باشیم :

PS> '12' -match '\d\d'
True
---------------------------------------------
PS> $data = @('12', '13', 'ali', 'hosi')
PS> $data -match '\d\d'
12
13
---------------------------------------------
PS> $a = 'ali is 18 years old' 
PS> $a -match '\w+\s+is (\d+)\s+years old'
PS> $Matches
 Name                               Value 
 ----                               -----
   1                                  18
   0                                  ali is 18 years old 
---------------------------------------------
$message = 'My Name is Kevin and my SSN is 123-45-6789.'
if($message -match 'My Name is (?<Name>.+) and my SSN is (?<SSN>\d\d\d-\d\d-\d\d\d\d)\.')
{
$Matches.Name
$Matches.SSN
}

این مورد سه حالت دیگر هم دارد:
۱- imatch : غیر کیس سنستیو میکنه
۲- cmatch : کیس سنستیو میکنه
۳- notmatch : وقتی که هیچ تطابقی درست نیست true برمی گرداند.

PS> $message = 'hello world how are you?'
PS> $message.contains('hello')
true
PS> $a = 'i am hasan'
PS> $b = $a.Replace('hasan', 'ashkan')
PS> $b
i am ashkan
PS> $b.Length
11
PS> 'a,b,c' -split ','
a
b
c
---------------------------------
PS> $a = 'a,b,c'
PS> $b = $a.Split(',')
PS> $b
a
b
c

این نیز حالت های split- , -csplit دارد.

PS> $a = '12'
PS C:\Users\ashkan nasirzadeh> switch -regex ($a) {
>> '/d' {
>> Write-Warning 'one d'
>> }
>> '\d\d' {
>> Write-Warning 'two d'
>> }
>> }
WARNING: two d

مدیریت دیسک ها در powershell

اولا باید کلا بدونید که داستان چیه ؟ داستان اینه که ما یک سری دیسک داریم که همون دیسک های فیزیکی ای هستند که به سخت افزار وصل می شوند و باید بدونید که مثلا هم یک دیسک محسوب می شود حالا این دیسک ها رو می خواهیم چی کار کنیم؟
۱- اولا شاید بخواهیم این دیسک ها رو اضافه کنیم:
برای این کار باید اول قسمت بندیشون کنیم که به کامپیوتر بفهمونیم چقدر از حجمشون رو می خواهیم که به این کار می گیم پارتیشن بندی دوما باید فایل سیستم مورد نظر رو روی اون پارتیشن نصب کنیم یا به اصطلاح شخمش بزنیم که آماده ی کاشت اطلاعات بشود که این کار رو از طریق فرمت کردن انجام می دیم
۲- کار دیگه ای که ممکنه بخواهیم بکنیم پارک کردن پارتیشن ها و دوباره ساختن آنهاست
۳- و در نهایت کار سومی که می خواهیم بکنیم اضافه کردن فضا به هارد دیسکمون هست
در این آموزش ۲ مورد اول رو یاد می گیریم و مورد سوم فعلا حال ندارم بذارم:

# to build a new partition:
-----------------------------------------------
# get the number of the disk that you want to add:
PS> Get-Disk
# initialize it:
PS> Initialize-Disk -Number 1
# partition it with max size of that
PS> New-Partition -DiskNumber 1 -DriveLetter D -UseMaximumSize
# get the drive letter that you want to format
PS> Get-Volume
# format that volume with default filesystem
PS> Format-Volume -DriveLetter E
# to delete a partition:
-----------------------------------------------
diskpart
list disk
select disk n
list partition
select partition n
delete partition #or delete partition OVERRIDE

کار با user ها و group ها در powershell

دقت کنید که کاربر در ویندوز بدون گروه هیچ معنایی ندارد زیرا که اصلا بدون تعلق به یک گروه سطح دسترسی ای متصور نیست و همچنین دقت کنید برای هر user باید یک password داشته باشید.

# get all users:
PS> Get-LocalUser
# get all groups:
PS> Get-LocalGroup
# add a user and bind it with a group:
PS> New-LocalUser -Name newTestUser
PS> Add-LocalGroupMember -Group "administrators"
# add a group and add a user to it:
PS>  New-LocalGroup -Name newTestgroup
PS>  Add-LocalGroupMember -Group "administrators"
# get members of a group:
PS> Get-LocalGroupMember -Group 'administrators'

حلقه ها ، شروط ، متغیر ها

# build 10 folder:
PS> for ($i = 1; $i -le 10; $i++) { mkdir $i }
# delete same folders:
PS> for ($i = 1; $i -le 10; $i++) { rmdir $i }
# delete all directories that have one digit name:
PS> dir | ForEach-Object { if ($_ -match '^\d$') { rmdir $_ } }
# delete all mp3 files (1):
PS> dir | ForEach-Object { $Matches = @() ; echo ------$_ ; $_ -match '(\w+)\.(\w+)' ; if  ($Matches[2] -eq 'mp3') { Remove-Item $Matches[0] }}
# delete all mp3 files (2):
PS> dir | Where-Object { $_ -match '^(.+)\.mp3$' } | Remove-Item
# get all directories that have 'ali' string in their names:
PS> dir | Where-Object { $_.Name -like '*ali*' }
--------------------------------------------------------------------
# get variable type:
PS> $x | Get-Member
# type casting:
PS> [string]$a = 123
--------------------------------------------------------------------
# arrays:
PS> $a = 1,2,3,4
PS> $a[0]
1
PS> $a[1,2]
2
3
PS> $a[0..2]
1
2
3
--------------------------------------------------------------------
# About Comparison Operators:
# -eq : equals
# -ne : not equals
# -gt : greater than
# -lt : less than
# -ge : greater than or equal
# -le : less than or equal
# About logical operators:
# -or
# -and
# About Arithmetic Operators
# % : Modulus
# About Assignment Operators
# += : C += A => C = C + A
# -= : ...

کار با فایل ها در powershell

# make a file
PS> New-Item song.mp3
# delete a file
PS> Remove-Item song.mp3
# make a directory
PS> mkdir folder
# delete a directory
PS> rmdir folder
# delete a directory with everything in it
PS> rmdir folder -Recurse
# get a list of all files and folders
PS> dir
# copy
PS> copy file1 .\folder\file1
# move
PS> move file1 .\folder\file1
# get content:
PS> Get-Content .\file.txt
# read
PS> cat sample.txt
# read line by line
PS> more sample.txt

#example:
PS> dir | Where-Object { ($_.Name -match '^file1$') -or ($_.Name -match '^file2$') }

کار با process ها و service ها

# get all services:
PS> Get-Service
# get all processes:
PS> Get-Process

# restart a service:
PS> Get-Service -Name XblGameSave | Restart-Service
# restart a process:
PS> Get-Process -Name notepad | Stop-Process ; notepad 
# kill a process
PS> Stop-Process -Id 4134 -Force

# check a service running or not:
PS> $a = Get-Service -Name XblGameSave; $a.Status
# check a process running or not (true: running, false: stopped):
PS> $a = Get-Process -Name notepad; $a -ne $null

مثال ها:

$files = dir
$counter = 0;
foreach ($item in $files)
{
    $counter++
}
Write-Host $counter
--------------------------------------------------
for ($i=1;$i -le 5;$i++)
{
    $userName = 'user' + $i.ToString();
    New-LocalUser -Name $userName -NoPassword
}
--------------------------------------------------
$con = 0;
while ($con -le 10) {
    Write-Host $con;
    $con++;
}
0
1
2
3
4
5
6
7
8
9
10
--------------------------------------------------
$con = 0;
do {
    $con++;
    Write-Host $con;
} while ($con -le 10)
0
1
2
3
4
5
6
7
8
9
10
11
--------------------------------------------------
switch (1,3) { 
    1 {"One"} 
    2 {"Two"} 
    3 {"Three"; break} 
    4 {"Four"} 
    3 {"Three Again"} 
}
One
Three
--------------------------------------------------
$color = Read-Host 'ENTER COLOR'
$price = Read-Host 'ENTER PRICE'
$comName = $env:COMPUTERNAME
if (($color -eq 'blue') -and ($price -le 100))
{
    clear;
    Write-Host 'from' $comName ': buy'
}
else
{
    clear;
    Write-Host 'from' $comName ': DO NOT BUY'
}

موارد دیگر:

# create a folder & file:
New-Item -Path 'D:\temp\Test Folder' -ItemType Directory
New-Item -Path 'D:\temp\Test Folder\Test File.txt' -ItemType File
# -----------------------------------------------------
# copy folder & file:
Copy-Item 'D:\temp\Test Folder' 'D:\temp\Test Folder1'
# recursively:
Copy-Item 'D:\temp\Test Folder' -Destination 'D:\temp\Test Folder1'
Copy-Item 'D:\temp\Test Folder\Test File.txt' 'D:\temp\Test Folder1\Test File1.txt'
Copy-Item -Filter *.txt -Path 'D:\temp\Test Folder' -Recurse -Destination 'D:\temp\Test Folder1'
# -----------------------------------------------------
# delete folder & file:
Remove-Item 'D:\temp\Test Folder1'
Remove-Item 'D:\temp\Test Folder' -Recurse
Remove-Item 'D:\temp\Test Folder\test.txt'
Remove-Item 'D:\temp\Test Folder' -Recurse
# -----------------------------------------------------
# move folder & file:
Move-Item D:\temp\Test D:\temp\Test1
Move-Item D:\temp\Test\Test.txt D:\temp\Test1
# -----------------------------------------------------
# rename folder & file:
Rename-Item D:\temp\Test D:\temp\Test1
Rename-Item D:\temp\Test\test.txt test1.txt
# -----------------------------------------------------
# Retrieving Item
(Get-Content D:\temp\test\test.txt).length
# -----------------------------------------------------
# check folder and file existence:
Test-Path D:\temp\test
Test-Path D:\temp\test\test.txt
# get date and time:
Get-Date
Get-Date -DisplayHint Time
# create , set and get content from a txt file:
New-Item D:\temp\test\test.txt
Set-Content D:\temp\test\test.txt 'Welcome to TutorialsPoint'
get-Content D:\temp\test\test.txt
# -----------------------------------------------------
# Erase content of File
Clear-Content D:\temp\test\test.txt
# -----------------------------------------------------
# Append content to File
Add-Content D:\temp\test\test.txt 'World!'
# Get-Unique
$list = "one","two","two","three","four","five"
$list | sort | get-unique
#output:
five
four
one
three
two
# Measure-Object
get-content D:\temp\test\test.txt | measure-object -character -line -word
Get-ChildItem | Measure-Object
# Compare-Object
# In this example, first we've a file test.txt in D:\temp\test with content "Welcome to TutorialsPoint.Com" and
# test1.txt with content "Hello World!" and "Welcome to TutorialsPoint.Com" in two lines.
Compare-Object -ReferenceObject $(Get-Content D:\temp\test\test.txt) -DifferenceObject $(Get-Content D:\temp\test\test1.txt) -IncludeEqual
# output:
InputObject                                      SideIndicator
-----------                                      -------------
Welcome to TutorialsPoint.Com                    ==
Hello World!                                     =>
# Format-List
dir | Format-List
# Format-Wide
Format-Wide -InputObject $A -Property Length
# returns $A objects sizes (length)
# sleep for 15 second
Start-Sleep -s 15
# sleep for 500 milliseconds
Start-Sleep -m 500
dir | Select-Object -Property Mode
"a","b","c","a","a","a" | Select-Object -Unique
Get-Process | Sort-Object -Property WS
# perform a default action on specified item (in this example we open notepad ...)
Invoke-Item test.txt
> $Command = 'Get-Process'
> $Command
Get-Process
> Invoke-Expression $Command
# Get-Process cmdlet output
# meaure the time taken by script or command
Measure-Command { dir }
# run the last command from the current session
Invoke-History
Get-history -count 5 | Add-history
get-culture

در powershell متغیر ها همون object ها هستند (بهشون object هم می گیم) ، یکسری متغیر ها هم هستند که در powershell هستند و اسمشون هست special variables :

$^
اولین token که در اخرین خط توسط seasion دریافت شده را برمی گرداند
$$ اخرین token که در اخرین خط توسط session دریافت شده را برمی گرداند
$?
می گه آخرین کاری که کردی موفقیت آمیز بوده یا نه
$_/$PSItem
-
$Error
آرایه ای از ارور ها رو برمی گردونه
$ExecutionContext
یک EngineIntrinsics object را نشان می دهد که زمینه ی اجرای powershell host را نشان می دهد.
$FALSE
-
$TRUE
-
$NULL
-
$HOME
 Represents the full path of the user's home directory.
$HOST
 Represents an object that represents the current host application for PowerShell
$MATCHES
-
$MYINVOCATION
مثلا تو یه تابع می گه که کی منو صدا زده؟ بعد اسم همون تابع رو می ده مثلا
$PID
 Represents the process identifier (PID) of the process that is hosting the current PowerShell session
$PROFILE
 Represents the full path of the PowerShell profile for the current user and the current host application
$PSCOMMANDPATH
 Represents the full path and file name of the script that is being run
$PSCULTURE
Represents the name of the culture currently in use in the operating system.

$PSHOME
Represents the full path of the installation directory for PowerShell

$PSSCRIPTROOT
Represents the directory from which a script is being run.

$SHELLID
Represents the identifier of the current shell.

$THIS
In a script block that defines a script property or script method the $This variable refers to the object that is being extended.
$A = 1,2,3,4
$A = 1..4
$A.getType()
$A.Length
$subA = $A[1..3]
$B = @(1..4)
# Hashtables 
# -----------------------------------------------------------------------------
$hash = @{ ID = 1; Shape = 'Square'; Color = 'Blue'} 
# -----------------------------------------------------------------------------                         
$hash2 = [ordered]@{ id = 1; name= 'ashkan'; familiy= 'nasirzadeh'} 
Name                           Value
----                           -----
id                             1
name                           ashkan
familiy                        nasirzadeh
> $hash.keys 
ID 
Color 
Shape 
> $hash.values 
Blue 
Square
> $hash.Add("Created","Now") 
>$hash.Remove("Updated")
# following -matchs are true:
'copy' -match 'c..y'
'big' -match 'b[iou]g'
'baggy' -match 'g+'

به وسیله ی ` می توانیم یک دستور طولانی را در چند خط بنویسیم

New-Alias -Name d -Value dir
Get-Alias | Where-Object { $_ -like '*d*'}

administrator کاربر را فعال کردن

powershell حتما با اختیارات administrator باز شده باشد و سپس کد زیر را بزنید:

net user administrator /active:yes

web و powershell

netstat -ano
Get-NetTCPConnection

چندین چیز دیگر!

# get the computer name:
hostname
# close all tcp connections which have 127.0.0.1 localAddress
netstat -ano |
ForEach-Object {
    if ($_ -match '\s+TCP\s+127.0.0.1:(.*)\s+(.*)\s+(.*)\s+(.*)') {
        Stop-Process -Id $Matches[4] -Force
    }
}