powershell1

PowerShell
ICACLS.EXE C:\TEST /GRANT USERS:`(F`)
Get-Service LANMANSERVER | FL
Get-Service LAN* | % { $_.Name; SC.EXE SDSHOW $_.Name }
Вывод настроек рабочего стола
Get-WmiObject -Class Win32_Desktop -ComputerName . | Select-Object -Property [a-z]*
использование функции автозавершения при помощи клавиши TAB;
предоставляют способ автоматического завершения длинных имен файлов или команд, ускоряя ввод команд и
предоставляя советы.
оператор конвейерной обработки (|).
```````````````````````````` Гравис (`)
`0 Значение Null
`a Звуковой сигнал
for($i = 0; $i -le 1; $i++){Write-Host `a} ======== два сигнала гудка на динамик
`b
Возврат на одну позицию
Write-Host " возвррт`b`bат"
`n
Новая строка
Write-Host "Два разрыва строки `n`nздесь."
`r
Возврат каретки
Write-Host "Этот текст будет удален`rНе двигайтесь."
Горизонтальная табуляция
Write-Host "Раз`t`tДва`t`tТри"
`' Одинарная кавычка
`" Двойные кавычки
`t
%%%%%%%%%%%%%% ->ForEach-Object
???????????? -> Where-Object , знак вопроса (?) соответствует ровно одному знаку
Get-ChildItem -Path C:\Windows\?????.log
?n возвращает An, an, In, in, On, on.
!!!!!!!!!!!!!!!!
!(1 -eq 2)
~~~~~~~~~~~~
convert-path ~
&&&&&&&&&&&&& - вызов дочернего процесса
$a=3
---
&{ clear-variable a } ----
$a
$$$$$$$$$$
$$
$? ========== true или false
$^
$_ ======= текущий
get-date | convertto-html -title "Date Table" | foreach { $_ -replace "><",">`n<" }
30000,56798,12432 | foreach-object -process {$_/1024} ---- делит каждое на 1024 и отображает результаты.
get-ACL c:/windows/k*.log -Audit | foreach-object { $_.Audit.Count }
get-childitem C:\ | foreach-object -process { $_.length / 1024 }
get-itemproperty -path hkcu:\Network\* | foreach-object {set-itemproperty -path $_.pspath -name RemotePath
-value $_.RemotePath.ToUpper();}
Get-ChildItem c: | where {$_.PsIsContainer -eq $false} | Format-List
/////////////////////
30000,56798,12432 | foreach-object -process {$_/1024} ---- делит каждое на 1024 и отображает результаты.
**************
get-alias -name g*, s*
get-traceSource *provider*
Get-ChildItem -Path C:\Windows\x*
.............................. точка (.) представляет папку C:\Windows, а две точки (..) представляют папку C:.
Set-Location -Path .. -PassThru
Get-ChildItem .\system
Get-ChildItem ..\"program files"
$B = 5..8
$a[0,2+4..6]
$a[2..($a.length-1)]
^^^^^^^^^^^^^^^^^
get-process | where-object { $_.ProcessName -match "^p.*" }
@@@@@@@@@@@@@@@@
gci *.txt | Sort-Object @{Expression={$_.LastWriteTime-$_.CreationTime}
$processes = get-process | select-object ProcessName,@{Name="Start Day"; Expression = {$_.StartTime.DayOfWeek}}
'''''''''''''''''''''''''''''''''''' """"""""""""""""""""""
Write-Host "`$home = $home"
Write-Host 'Как говорится, "учись, пока жив".'
++++++++++++++
$env:path += ";C:\Program Files\Windows NT\Accessories"
>>>>>>>>>>>>>>>
Get-ChildItem c:\windows\system > c:\techdocs\results.txt
Get-ChildItem c:\windows\system >> c:\techdocs\results.txt
[][][][][][][][][]
Get-ChildItem -Path C:\Windows\[xz]* ==== все файлы, чьи имена начинаются с x или z
Get-ChildItem -Path C:\WINDOWS\System32\w*32*.dll -Exclude *[9516]*
Get-ChildItem -Path C:\Windows\*.dll -Recurse -Exclude [a-y]*.dll
Get-WmiObject -Class Win32_Desktop -ComputerName . | Select-Object -Property [a-z]*
[System.Environment]
[System.Environment] | Get-Member
[System.Environment] | Get-Member -Static
[System.Environment]::Commandline
[System.Environment]::OSVersion
[System.Environment]::HasShutdownStarted
[System.Math] | Get-Member -Static -MemberType Methods
[System.Math]::Sqrt(9)
[System.Math]::Pow(2,3)
[System.Math]::Floor(3.3)
[System.Math]::Floor(-3.3)
[System.Math]::Ceiling(3.3)
[System.Math]::Ceiling(-3.3)
[System.Math]::Max(2,7)
[System.Math]::Min(2,7)
[System.Math]::Truncate(9.3)
[System.Math]::Truncate(-9.3)
`'
`"
`0
`a
`b
`f
`n
`r
`t
`v
Одинарная кавычка
Двойные кавычки
Значение Null
Звуковой сигнал
Возврат на одну позицию
Перевод страницы
Новая строка
Возврат каретки
Горизонтальная табуляция
Вертикальная табуляция
a
ab
about_Updatable_Help
ac
ad
add
add-content -path *.txt -exclude help* -value "END"
add-content -Path file1.log, file2.log -Value (get-date) -passthru
add-content -path monthly.txt -value (get-content c:\rec1\weekly.txt)
import-csv history.csv | add-history
import-clixml c:\temp\history.xml | add-history -passthru | invoke-history
get-history id 5 -count 5 | add-history
$a = import-csv c:\testing\history.csv ---- add-history -inputobject $a -passthru
add-history -inputobject (import-clixml c:\temp\history01.xml)
$a = "a string" ----- $a = $a | add-member noteproperty StringUse Display -passthru --- $a.StringUse
$a = "this is a string" --- $a = add-member -inputobject $a -membertype scriptmethod -name words `
-value {$this.split()} -passthru ---- $a.words()
$event = get-eventlog -logname system -newest 1 --- $event.TimeWritten | get-member ---
add-member -inputobject $event -membertype aliasproperty -name When -value TimeWritten -secondvalue ---System.String ----- $event.When | get-member
add-PSSnapIn Microsoft.Exchange,Microsoft.Windows.AD ---- Эта команда добавляет в текущую консоль
оснастки Microsoft Exchange и Microsoft Active Directory Directory Services.
get-pssnapin -registered | add-pssnapin -passthru --- Эта команда добавляет в консоль все
зарегистрированные оснастки Windows PowerShell.
add-pssnapin sql
al
ali
clear-item Alias:dog* -include *1* -exclude *3* -whatif
$event = get-eventlog -logname system -newest 1 --- $event.TimeWritten | get-member --add-member -inputobject $event -membertype aliasproperty -name When -value TimeWritten -secondvalue ---System.String ----- $event.When | get-member
an
and
-and
========
логическое "И"
Get-ChildItem c:\ | where { $_.length -lt 100 -and !$_.PSIsContainer}
Get-ChildItem -Path $env:ProgramFiles -Recurse -Include *.exe | Where-Object
-FilterScript {($_.LastWriteTime -gt "2005-10-01") -and ($_.Length -ge 1m) -and ($_.Length -le 10m)}
Get-ChildItem -Path HKCU:\Software -Recurse | Where-Object -FilterScript {($_.SubKeyCount -le 1)
–and ($_.ValueCount -eq 4) }
ap
app
export-alias -path alias.txt -append -description "Appended Alias Info"
ar
arg
$Args ======= переменная
New-Object -TypeName System.Diagnostics.EventLog -ArgumentList
$AppLog = New-Object -TypeName System.Diagnostics.EventLog -ArgumentList Application
as
export-alias -path alias.txt -as script ---- notepad alias.txt
asc
get-childitem *.txt | sort-object @{Expression={$_.LastWriteTime-$_.CreationTime}; Ascending=$false} |
select-object LastWriteTime, CreationTime
ASCII
$a = get-process ------ out-file -filepath C:\Test1\process.txt -inputobject $a -encoding ASCII -width 50
ass
$securestring = read-host -assecurestring
--- запись с клавиатуры ,а на экране * в System.Security.SecureString
get-process | sort-object | select processname | get-unique -asstring
au
aut
auto
Get-Command -Noun Variable | Format-Table -Property Name,Definition -AutoSize -Wrap
av
get-childitem | measure-object -property length -minimum -maximum -average
b
ban
band
-band
========= побитовое "И"
be
beg
$events = get-eventlog -logname system -newest 1000 ---- $events | foreach-object
-begin {get-date} -process
{out-file -filepath events.txt -append -inputobject $_.message} -end {get-date}
bo
bor
-bor
========= побитовое "ИЛИ"
br
break
$i=0 --- $varB = 10,20,30,40 foreach ($val in $varB) { $i++ if ($val -eq 30)
Write-Host "30 пилигримов сели на мель в $i часа ночи"
c
cal
calc
--- вызов салькулятора
{
break } }
cat
get-help -category provider
(get-uiculture).calendar
cd
cd hklm: | cd system\currentcontrolset\control
cd cert: ----- cd currentuser -------- cd authroot ---- dir
ce
get-childitem cert:\. -recurse -codesigningcert
ch
get-content C:\test.txt | measure-object -character -line -word
cl
cle
clear-content ..\SmpUsers\*\init.txt
clear-content -path * -filter *.log -force
clear-content c:\Temp\* -Include Smp* -Exclude *2* -whatif
Clear-Host
============= команда очистки окна консоли
clear-item Alias:dog* -include *1* -exclude *3* -whatif
clear-item registry::HKLM\Software\MyCompany\MyKey -confirm
clear-itemproperty -path HKLM:\Software\MyCompany\MyApp -name Options
clear-variable my* -global
clear-variable -name processes
co
cod
get-childitem cert:\. -recurse -codesigningcert
col
get-childitem | format-wide -column 3
com
(New-Object -ComObject Scripting.FileSystemObject).CopyFile("c:\boot.ini", "c:\boot.bak")
New-Object -ComObject WScript.Shell
New-Object -ComObject WScript.Network
(New-Object -ComObject WScript.Network).EnumPrinterConnections()
(New-Object -ComObject WScript.Network).RemovePrinterConnection("\\Printserver01\Xerox5")
(New-Object -ComObject WScript.Network).MapNetworkDrive("B:", "\\FPS01\users")
New-Object -ComObject Scripting.Dictionary
New-Object -ComObject Scripting.FileSystemObject
$ie = New-Object -ComObject InternetExplorer.Application
$xl = New-Object -ComObject Excel.Application -Strict
comp
-comp ============ дополняющий оператор (~)
compare-object -referenceobject $(get-content C:\test\testfile1.txt) -differenceobject $(get-content C:\test\testfile2.txt)
compare-object -referenceobject $(get-content C:\Test\testfile1.txt) -differenceobject $(get-content
C:\Test\testfile2.txt) -includeequal
compare-object -referenceobject $processes_before -differenceobject $processes_after
computername
get-service -computername cloud-films
get-service -computername valery_pc
get-wmiobject win32_service -computername 127.0.0.1
$c=Get-Credential ---- Get-WmiObject Win32_DiskDrive -ComputerName Server01 -Credential $c
Get-WmiObject Win32_BIOS -ComputerName Server01 ' -Credential (get-credential Domain01\User01)
get-wmiobject win32_bios -computername valery_pc
Get-WmiObject -List -ComputerName .
Get-WmiObject -List -ComputerName Admin01
Get-WmiObject -List -ComputerName 192.168.1.88
Get-WmiObject -List -ComputerName cloud-films
Get-WmiObject -List -ComputerName 127.0.0.1
Get-WmiObject -List -ComputerName localhost
$RemoteAppLog = New-Object -TypeName System.Diagnostics.EventLog Application,192.168.1.88 --- $RemoteAppLog
con
clear-item registry::HKLM\Software\MyCompany\MyKey -confirm
Stop-Process -Name t*,e* -Confirm
cont
contains
1,2,3 -contains 1
conv
convert
$standardstring = convertfrom-securestring $securestring
$key = (3,4,2,3,56,34,254,222,1,1,2,23,42,54,33,233,1,34,2,7,6,5,35,43) --$standardstring = convertfrom-securestring $securestring -key $key
convert-path ~
convert-path HKLM:\software\microsoft
get-date | convertto-html -title "Date Table" | foreach { $_ -replace "><",">`n<" }
get-process | convertto-html -properties Name,Path,Company ' -title "Process Information" > proc.htm --invoke-item proc.htm
cop
copy
copy-item C:\Wabash\Logfiles\mar1604.log.txt -destination C:\Presentation
Copy-Item -Path c:\boot.ini -Destination c:\boot.bak
Copy-Item -Path c:\boot.ini -Destination c:\boot.bak -Force == если уже файл существует
Copy-Item -Path 'HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion' -Destination hkcu:
Copy-Item -Path 'HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion' -Destination hkcu: -Recurse
copy-item C:\Logfiles -destination C:\Drawings -recurse ===== копирование папок
Copy-Item C:\temp\test1 -Recurse c:\temp\DeleteMe ===== копирование папок
Copy-Item -Filter *.txt -Path c:\data -Recurse -Destination c:\temp\text ===== копирование папок
copy-itemproperty -path MyApplication -destination HKLM:\Software\MyApplicationRev2 -name MyProperty
(New-Object -ComObject Scripting.FileSystemObject).CopyFile("c:\boot.ini", "c:\boot.bak")
copyto
(Get-ChildItem c:\final.txt).CopyTo("c:\bin\final.txt")
cou
get-ACL c:/windows/k*.log -Audit | foreach-object { $_.Audit.Count }
(get-alias | where-object {$_.Options -match "ReadOnly"}).count
cr
cre
get-wmiobject win32_service -credential FABRIKAM\administrator -computer fabrikam
$c=Get-Credential ---- Get-WmiObject Win32_DiskDrive -ComputerName Server01 -Credential $c
Get-WmiObject Win32_BIOS -ComputerName Server01 ' -Credential (get-credential Domain01\User01)
cu
cur
set-executionpolicy -scope CurrentUser remotesigned
d
de
deb
Debug-Process
$DebugPreference ======= переменная
def
get-alias | where-object {$_.definition -eq "set-location"}
get-alias | where-object {$_.Definition -match "Get-Childitem"}
des
get-history | sort-object -descending
Get-WmiObject -Class Win32_SystemDriver | Sort-Object -Property State,Name -Descending
| Format-Table -Property Name,State,Started,DisplayName -AutoSize -Wrap
export-alias -path alias.txt -append -description "Appended Alias Info"
copy-item C:\Wabash\Logfiles\mar1604.log.txt -destination C:\Presentation
det
get-help ls -detailed
get-help get-command -detailed
di
dif
compare-object -referenceobject $(get-content C:\test\testfile1.txt) -differenceobject $(get-content C:\test\testfile2.txt)
dir
dir
dis
$a = "a string" -----
$a = $a | add-member noteproperty StringUse Display -passthru ---
$a.StringUse
e
en
enc
$a = get-process ------ out-file -filepath C:\Test1\process.txt -inputobject $a -encoding ASCII -width 50
env
get-childitem env:computername
get-childitem env: | sort name
$env:windir
$env:path
$env:path += ";C:\Program Files\Windows NT\Accessories"
Get-ChildItem -Path $env:ProgramFiles -Recurse -Include *.exe | Where-Object
-FilterScript {($_.LastWriteTime -gt "2005-10-01") -and ($_.Length -ge 1m) -and ($_.Length -le 10m)}
subst p: $env:programfiles ====== создает локальный диск P:,
eq
-eq
========= равно (без учета регистра)
get-service | where-object {$_.Status -eq "Stopped"}
Get-ChildItem c: | where {$_.PsIsContainer -eq $false} | Format-List
get-alias | where-object {$_.definition -eq "set-location"}
Get-ChildItem -Path HKCU:\Software -Recurse | Where-Object -FilterScript {($_.SubKeyCount -le 1)
–and ($_.ValueCount -eq 4) }
er
err
$Error ======= переменная
$ErrorActionPreference
======= переменная
ev
eve
$event = get-eventlog -logname system -newest 1 --- $event.TimeWritten | get-member --add-member -inputobject $event -membertype aliasproperty -name When -value TimeWritten -secondvalue ---System.String ----- $event.When | get-member
$events = get-eventlog -logname system -newest 1000 ---- $events | group-object -property eventID
ex
exa
get-help start-service -examples
get-help get-command -examples
exc
get-childitem c:\windows\logs\* -include *.txt -exclude A*
clear-content c:\Temp\* -Include Smp* -Exclude *2* -whatif
Get-ChildItem -Path C:\WINDOWS\System32\w*32*.dll -Exclude *[9516]*
Get-ChildItem -Path C:\Windows\*.dll -Recurse -Exclude [a-y]*.dll
exe
get-childitem * -Include *.exe
exp
get-process | select-object processname -expandproperty modules | format-list
export-alias -path alias.txt -noclobber
export-alias -path alias.txt -append -description "Appended Alias Info"
export-alias -path alias.txt -as script ---- notepad alias.txt
get-acl C:\test.txt | export-clixml -Path testacl.xml
---- $testacl = import-clixml testacl.xml
export-console -path $pshome\Consoles\ConsoleS1.psc1
export-console NewConsole
get-history | export-csv c:\testing\history.csv
get-process wmiprvse | select-object basePriority,ID,SessionID,WorkingSet | export-csv -path data.csv
$processes = get-process | select-object ProcessName,@{Name="Start Day"; Expression = {$_.StartTime.DayOfWeek}}
gci *.txt | Sort-Object @{Expression={$_.LastWriteTime-$_.CreationTime}
get-childitem *.txt | sort-object @{Expression={$_.LastWriteTime-$_.CreationTime}; Ascending=$false} |
select-object LastWriteTime, CreationTime
ext
get-childitem | group-object extension -noelement
----(групировка по расширению файлов)
f
fal
get-childitem *.txt | sort-object @{Expression={$_.LastWriteTime-$_.CreationTime}; Ascending=$false} |
select-object LastWriteTime, CreationTime
Get-ChildItem c: | where {$_.PsIsContainer -eq $false} | Format-List
fi
fil
file
foreach ($file in Get-ChildItem c:\techdocs\*.txt) {Write-Host $file.fullname $file.length}
foreach ($file in Get-ChildItem c:\techdocs\*.txt) { if ($file.length -ge 100) { Write-Host $file.name - $file.length байт }
else { Write-Host $file.name - "Этот файл меньше 100 байт."
} }
filt
filter
filter process_c { $_.processname -like "c*"
}
clear-content -path * -filter *.log -force
Copy-Item -Filter *.txt -Path c:\data -Recurse -Destination c:\temp\text ===== копирование папок
1,2,3,4 | Where-Object -FilterScript {$_ -lt 3}
Get-ChildItem -Path $env:ProgramFiles -Recurse -Include *.exe | Where-Object
-FilterScript {($_.LastWriteTime -gt "2005-10-01") -and ($_.Length -ge 1m) -and ($_.Length -le 10m)}
Get-ChildItem -Path HKCU:\Software -Recurse | Where-Object -FilterScript {($_.SubKeyCount -le 1)
–and ($_.ValueCount -eq 4) }
Get-WmiObject -Class Win32_SystemDriver | Where-Object -FilterScript {$_.State -eq "Running"}
fo
for
for($i=1; $i -le 10; $i++) { Write-Host $i }
$i=1 --for (;;$i++){Write-Host $i}
for($i=1; $i -le 10; $i++){Write-Host $i}
for ($i = 0; $i -ile 20; $i += 2) {Write-Host $i}
foreach
$foreach ======= переменная
$i=0 --- $varB = 10,20,30,40 foreach ($val in $varB) { $i++ if ($val -eq 30)
Write-Host "30 пилигримов сели на мель в $i часа ночи"
{
break } }
$ips = 1..254 | ForEach-Object -Process {"192.168.1." + $_}
get-date | convertto-html -title "Date Table" | foreach { $_ -replace "><",">`n<" }
foreach ($file in Get-ChildItem c:\techdocs\*.txt) {Write-Host $file.fullname $file.length}
foreach ($file in Get-ChildItem c:\techdocs\*.txt) { if ($file.length -ge 100) { Write-Host $file.name - $file.length байт }
else { Write-Host $file.name - "Этот файл меньше 100 байт."
} }
Get-WmiObject -Class Win32_LogicalDisk | Select-Object -Property Name,FreeSpace
| ForEach-Object -Process {$_.FreeSpace = ($_.FreeSpace)/1024.0/1024.0; $_}
"127.0.0.1","localhost","research.microsoft.com" | ForEach-Object -Process {Get-WmiObject -Class Win32_PingStatus
-Filter ("Address='" + $_ + "'") -ComputerName .} | Select-Object -Property Address,ResponseTime,StatusCode
1..254| ForEach-Object -Process {Get-WmiObject -Class Win32_PingStatus
-Filter ("Address='192.168.1." + $_ + "'") -ComputerName .}
| Select-Object -Property Address,ResponseTime,StatusCode
Get-WmiObject -Class Win32_NetworkAdapterConfiguration -Filter IPEnabled=true -ComputerName .
| ForEach-Object -Process { $_.InvokeMethod("SetDNSDomain", "fabrikam.com")}
Get-Process | foreach { if ($_.WS -gt 20m) {Write-Host $_.name ": " ($_.WS/1m).ToString("F0") MB -Separator "" } }
force
=== показывает скрытые элементы
clear-content -path * -filter *.log -force
Get-ChildItem -Path C:\Windows -Force === показывает скрытые элементы
Remove-Variable -Name * -Force -ErrorAction SilentlyContinue ==== очистить все переменные
get-ACL c:/windows/k*.log -Audit | foreach-object { $_.Audit.Count }
30000,56798,12432 | foreach-object -process {$_/1024} ---- делит каждое на 1024 и отображает результаты.
get-childitem C:\ | foreach-object -process { $_.length / 1024 }
$events = get-eventlog -logname system -newest 1000 ---- $events | foreach-object
-begin {get-date} -process
{out-file -filepath events.txt -append -inputobject $_.message} -end {get-date}
get-itemproperty -path hkcu:\Network\* | foreach-object {set-itemproperty -path $_.pspath -name RemotePath
-value $_.RemotePath.ToUpper();}
form
format
get-process Winlogon | format-custom
get-service schedule | format-list -property *
Get-Process winword, explorer | format-list * --- (*-все доступные свойства)
get-wmiobject win32_bios | format-list *
get-process | select-object processname -expandproperty modules | format-list
get-service alerter | format-list -property name, CanPauseAndContinue
Get-Process -Name powershell | Format-List -Property ProcessName,FileVersion,StartTime,Id
Get-Process | Format-List | Out-Host -Paging
$a = get-process ---- get-process -inputobject $a | format-table -view priority
get-command | sort-object noun | format-table -group noun --- сортировка по алфавиту
get-service | format-table -property name, CanPauseAndContinue
get-service | format-table name, Servicetype, Canshutdown
Get-Process -Name powershell | Format-Table -Wrap -AutoSize -Property Name,Id,Path -GroupBy Company
get-childitem | format-wide -column 3
get-childitem HKCU:\software\microsoft | format-wide -property pschildname -autosize
Get-Command Format-Wide -Property Name -Column 1
Get-WmiObject -Class Win32_Product -ComputerName . | Format-Wide -Column 1 ==== выдает только имена пекетов
fu
ful
get-help get-command -full
fun
function CD32 {set-location c:\windows\system32}
function add2 {$args[0] + $args[1] } ========== выполнение add2 126 27
function small_files {Get-ChildItem c:\ | where { $_.length -lt 100 -and $_.PSIsContainer}
}
g
gc
gci *.txt | Sort-Object @{Expression={$_.LastWriteTime-$_.CreationTime}
ge
-ge
========= больше или равно (без учета регистра)
foreach ($file in Get-ChildItem c:\techdocs\*.txt) { if ($file.length -ge 100) { Write-Host $file.name - $file.length байт }
else { Write-Host $file.name - "Этот файл меньше 100 байт."
} }
Get-ChildItem -Path $env:ProgramFiles -Recurse -Include *.exe | Where-Object
-FilterScript {($_.LastWriteTime -gt "2005-10-01") -and ($_.Length -ge 1m) -and ($_.Length -le 10m)}
get
get-acl C:\windows
----- Эта команда получает дескриптор безопасности каталога "C:Windows".
get-acl C:\Windows\k*.log | select-object PSPath, Sddl | format-list
get-ACL c:/windows/k*.log -Audit | foreach-object { $_.Audit.Count }
get-acl -path hklm:\system\currentcontrolset\control | format-list
get-acl C:\test.txt | export-clixml -Path testacl.xml
---- $testacl = import-clixml testacl.xml
get-alias
get-alias -?
$alias = get-alias --- $alias | get-member --- get-member -inputobject $alias
get-alias -name g*, s*
get-alias | where-object {$_.definition -eq "set-location"}
get-alias | where-object {$_.Definition -match "Get-Childitem"}
get-alias | where-object {$_.Options -match "ReadOnly"}
(get-alias | where-object {$_.Options -match "ReadOnly"}).count
get-alias | out-string -stream | select-string "Get-Command"
get-help get-alias -detailed.
get-AuthenticodeSignature -filepath C:\Test\NewScript.ps1 ---- Эта команда получает сведения о подписи Authenticode
get-authenticodesignature test.ps1, test1.ps1, sign-file.ps1, makexml.ps1
get-childitem
get-childitem alias:
Get-ChildItem variable: ========== все переменные Windows PowerShell
Get-ChildItem -path c:\
Get-ChildItem c:\techdocs\[a-l]*.txt
Get-ChildItem -Path C:\Windows -Force === показывает скрытые элементы
Get-ChildItem -Path $env:ProgramFiles -Recurse -Include *.exe | Where-Object
-FilterScript {($_.LastWriteTime -gt "2005-10-01") -and ($_.Length -ge 1m) -and ($_.Length -le 10m)}
get-childitem env:computername
get-childitem env: | sort name
Get-ChildItem -Path hkcu:\
Get-ChildItem -Path hkcu:\ -Recurse
Get-ChildItem -Path Registry::HKEY_CURRENT_USER
Get-ChildItem -Path Microsoft.PowerShell.Core\Registry::HKEY_CURRENT_USER
Get-ChildItem -Path Registry::HKCU
Get-ChildItem -Path Microsoft.PowerShell.Core\Registry::HKCU
get-childitem -path $pshome
Get-ChildItem -Path Uninstall: | ForEach-Object -Process { $_.GetValue("UninstallString") }
Get-ChildItem -Force C:\
Get-ChildItem -Force C:\ -Recurse === показ вложенных элементов
get-childitem -name --- Эта команда извлекает только имена элементов из текущей папки.
get-childitem C:\ | foreach-object -process { $_.length / 1024 }
get-childitem . -Include *.txt -Recurse
get-childitem * -include *.csv -recurse | remove-item
Get-ChildItem c:\techdocs\[a-l]*.txt
get-help get-childitem -parameter f*
get-childitem c:\windows\logs\* -include *.txt -exclude A*
get-childitem registry::hklm\software
get-childitem cert:\. -recurse -codesigningcert
get-childitem * -Include *.exe
get-childitem | measure-object
get-childitem | sort-object {$_.GetType()} | unique -OnType
Get-ChildItem c:\ | where { $_.length -lt 100 and !$_.PSIsContainer}
(Get-ChildItem c:\techdocs\final.txt).length
$a = (Get-ChildItem c:\techdocs\final.txt) ---- Write-Host $a.fullname $a.length $a.lastwritetime
(Get-ChildItem c:\final.txt).name.ToUpper()
(Get-ChildItem c:\final.txt).MoveTo("c:\techdocs\final.txt")
(Get-ChildItem c:\final.txt).CopyTo("c:\bin\final.txt")
foreach ($file in Get-ChildItem c:\techdocs\*.txt) {Write-Host $file.fullname $file.length}
foreach ($file in Get-ChildItem c:\techdocs\*.txt) { if ($file.length -ge 100) { Write-Host $file.name - $file.length байт }
else { Write-Host $file.name - "Этот файл меньше 100 байт."
} }
Get-ChildItem c: | where {$_.PsIsContainer -eq $false} | Format-List
get-childitem HKCU:\software\microsoft | format-wide -property pschildname -autosize
$a = Get-ChildItem ----foreach ($file in $a){Write-Host $file.name $file.CreationTime $file.LastAccessTime
$file.LastWriteTime
}
foreach ($file in Get-ChildItem) { Write-Host $file }
get-command
---- Эта команда возвращает сведения обо всех командлетах Windows PowerShell
get-command -list
Get-Command | more
get-command *
get-command b*
get-command -moun *net* |out_help1._net1.txt
Get-Command -CommandType Alias
Get-Command -CommandType Function
Get-Command -CommandType ExternalScript
Get-Command -Name Get-PSDrive -Syntax
Get-Command -Name New-PSDrive -Syntax
get-command -pssnapin Microsoft.PowerShell.Security --- извлекает сведения о командлетах в оснастке Microsoft.
get-command | sort-object noun | format-table -group noun --- сортировка по алфавиту
Get-Command -Syntax
Get-Command -type cmdlet
get-command -verb set | format-list ---- только содержащих глагол "set"
get-command get-childitem -ArgumentList cert: | format-list --- Эта команда извлекает сведения о
командлете Get-Childitem при его использовании с поставщиком Windows PowerShell Certificate
Get-Command -Noun Item
Get-Command -Noun Variable | Format-Table -Property Name,Definition -AutoSize -Wrap
get-content C:\test.txt | measure-object -character -line -word
compare-object -referenceobject $(get-content C:\test\testfile1.txt) -differenceobject $(get-content C:\test\testfile2.txt)
get-content -Path C:\Chapters\chapter1.txt
get-content c:\Logs\Log060912.txt -totalcount 50 | set-content sample.txt
get-content $pshome\about_signing.help.txt | Out-Printer
(Get-Content -Path C:\boot.ini).Length
$Computers = Get-Content -Path C:\temp\DomainMembers.txt
$c = Get-Credential ---- Get-WmiObject Win32_DiskDrive -ComputerName Server01 -Credential $c
Get-WmiObject Win32_BIOS -ComputerName Server01 ' -Credential (get-credential Domain01\User01)
get-culture ----
Эта команда отображает сведения о региональных параметрах компьютера.
get-date
get-date -format g
get-date -uformat "%Y / %m / %d / %A / %Z"
(get-date -year 2000 -month 12 -day 31).dayofyear
$a = get-date ---- $a.IsDaylightSavingTime() --- Эта команда сообщает, корректируются ли
текущие дата и время с учетом перехода на летнее и зимнее время в используемом региональном стандарте.
get-date | get-member ---- все свойства и методы объекта DateTime
add-content -Path file1.log, file2.log -Value (get-date) -passthru
get-date | convertto-html -title "Date Table" | foreach { $_ -replace "><",">`n<" }
$events = get-eventlog -logname system -newest 1000 ---- $events | foreach-object
-begin {get-date} -process
{out-file -filepath events.txt -append -inputobject $_.message} -end {get-date}
$events = get-eventlog -logname system -newest 1000 ---- $events | group-object -property eventID
$events = get-eventlog -logname application -newest 500
$event = get-eventlog -logname system -newest 1 --- $event.TimeWritten | get-member --add-member -inputobject $event -membertype aliasproperty -name When -value TimeWritten -secondvalue ---System.String ----- $event.When | get-member
get-executionpolicy
get-help
get-help <имя-поставщика>
get-help -category provider
get-help about_*
get-help about_commonparameters
get-help about_signing - отображает справку о подписании скриптов.
get-help about_provider
get-help about_wildcard
Get-Help Environment-PSProvider
get-help format-string -full
get-help format-list
get-help format-table
get-help format-wide
get-help format-custom
get-help get-*
get-help get-alias
get-help get-alias -detailed.
get-help get-childitem -parameter f*
get-help get-command -detailed
get-help get-command -full
get-help get-command -examples
get-help get-command -parameter totalcount
get-help get-command -parameter *
get-help get-Process - отображает справку о командлете
get-help get-Process -Online
(в Internet)
get-help ls -detailed
get-help location
get-help registry
Get-Help Set-AuthenticodeSignature
get-help start-service -examples
get-help Where-Object -examples
get-help Where-Object -detailed
get-help Where-Object -full
Get-Process.
(get-help write-object).syntax
get-history | sort-object -descending
get-history | export-csv c:\testing\history.csv
get-history id 5 -count 5 | add-history
Get-History -id 12
get-host
$h = get-host ---- $win = $h.ui.rawui.windowsize --- $win.height = 10 --- $win.width = 10
$h.ui.rawui.set_windowsize($win)
get-item .
---- Эта команда извлекает текущий каталог. Точка (.) обозначает элемент в
текущем местоположении (но не его содержимое).
get-item *
----- Эта команда извлекает все элементы в текущем каталоге.
Подстановочный знак (*) обозначает все содержимое текущего элемента.
get-item C:\
--------- Эта команда извлекает текущий каталог диска C: .
Извлекаемый объект представляет только каталог, но не его содержимое.
(get-item C:\Windows).LastAccessTime
get-item hklm:\software\microsoft\powershell\1\shellids\microsoft.powershell\*
get-item c:\Windows\* -include *.* -exclude w* ---- Эта команда извлекает элементы каталога Windows,
имена которых включают точку (.) и не начинаются с буквы "w".
Get-Item -Path ---????????
get-item -path env:* | get-member
get-InitiatorID
get-itemproperty C:\Windows
get-itemproperty C:\Test\Weather.xls | format-list
get-itemproperty -path HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion
get-itemproperty -path HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion -name "ProgramFilesDir"
| format-list ProgramFilesDir
get-itemproperty -path hkcu:\Network\* | foreach-object {set-itemproperty -path $_.pspath -name RemotePath
-value $_.RemotePath.ToUpper();}
get-itemproperty -path . -name executionpolicy
get-location
-------------- Эта команда отображает текущее рабочее местоположение.
get-location -stack
get-member ------------- Список свойств
Get-Member -inputobject $a -membertype method
Get-Member -inputobject $a -membertype property
Get-ChildItem c:\final.txt | Get-Member -membertype method
Get-ChildItem c:\final.txt | Get-Member -membertype property
Get-ChildItem c:\final.txt | Get-Member -membertype NoteProperty
get-process | get-member -MemberType property
get-process | get-member | get-member
get-date | get-member ---- все свойства и методы объекта DateTime
$event = get-eventlog -logname system -newest 1 --- $event.TimeWritten | get-member --add-member -inputobject $event -membertype aliasproperty -name When -value TimeWritten -secondvalue ---System.String ----- $event.When | get-member
$alias = get-alias --- $alias | get-member --- get-member -inputobject $alias
$RemoteAppLog | Get-Member -MemberType Method
get-pfxcertificate -filepath C:\windows\system32\Test.pfx --- Эта команда получает данные о сертификате
get-Process -?
get-process Winlogon | format-custom
get-process | get-member -MemberType property
Get-Process | Get-Member | Out-Host -Paging
get-process | get-member | get-member
Get-Process winword, explorer | format-list *
$a = get-process ---- get-process -inputobject $a | format-table -view priority
Get-Process -Name powershell
Get-Process -Name exp*,power*,NotAProcess
Get-Process -Id 0
get-process -name svchost | where-object {$True}
get-process | sort-object -property WS | select-object -Last 5
get-process | sort-object | select processname | get-unique -asstring
get-process | select-object processname -expandproperty modules | format-list
$processes = get-process | select-object ProcessName,@{Name="Start Day"; Expression = {$_.StartTime.DayOfWeek}}
get-process wmiprvse | select-object basePriority,ID,SessionID,WorkingSet | export-csv -path data.csv
get-process | where-object {$_.HasExited}
get-process | where-object {$_.WorkingSet -gt 20000000}
get-process | where-object { $_.ProcessName -match "^p.*" }
Get-Process | where {$_.processname -like "[a-m]*"} ====== where= where-object (псевдоним)
Get-Process | Where-Object -FilterScript {$_.Responding -eq $false} | Stop-Process
Get-Process | foreach { if ($_.WS -gt 20m) {Write-Host $_.name ": " ($_.WS/1m).ToString("F0") MB -Separator "" } }
get-pssnapin ========= список имеющихся в системе оснасток Windows PowerShell
get-pssnapin -registered
get-psprovider
get-psprovider | format-list name, pssnapin
get-psdrive --- список дисков Windows PowerShell
get-psdrive HK*
Get-Command -Name Get-PSDrive -Syntax
Get-PSDrive -PSProvider FileSystem
Get-PSDrive -PSProvider Registry
get-psprovider --- Эта команда отображает список всех доступных поставщиков Windows PowerShell.
get-psprovider f*, r* | format-list
Get-PSDrive -PSProvider FileSystem
Get-PSDrive -PSProvider Registry
get-PSSnapIn
get-pssnapin -registered | add-pssnapin -passthru --- Эта команда добавляет в консоль все
зарегистрированные оснастки Windows PowerShell.
get-PSSnapIn smp*
get-service
get-service wmi*
get-service | get-member
get-service -displayname *network*
Get-Service -Name se*
get-service schedule | format-list -property *
get-service | where-object {$_.Status -eq "Running"}
get-service | where-object {$_.Status -eq "Stopped"}
get-service -computername cloud-films
get-service -computername valery_pc
get-service alerter | format-list -property name, CanPauseAndContinue
get-service | format-table -property name, CanPauseAndContinue
get-service | format-table name, Servicetype, Canshutdown
$services = get-service ---- get-service -inputobject $Services -include RPC*
(get-service alerter).canpauseandcontinue
(get-service schedule).stop()
get-traceSource *provider*
get-uiculture | format-list *
(get-uiculture).calendar
(get-uiculture).datetimeformat.shortdatepattern
1,1,1,1,12,23,4,5,4643,5,3,3,3,3,3,3,3 | sort-object | Get-Unique
get-childitem | sort-object {$_.GetType()} | unique -OnType
get-process | sort-object | select processname | get-unique -asstring
get-variable m*
get-variable m* -valueonly
get-variable -include M*,P* | sort-object name
Get-WmiObject -List
get-wmiobject -namespace "root/default" -list
get-help -full get-wmiobject ---- out-printer -inputobject $h
Get-WmiObject -List -ComputerName 192.168.1.88
Get-WmiObject -List -ComputerName 127.0.0.1
Get-WmiObject -List -ComputerName localhost
Get-WmiObject -List -ComputerName 192.168.1.88 -Namespace root
(Get-WMIObject -ComputerName PC01 -List | Where-Object
-FilterScript {$_.Name -eq "Win32_Product"}).InvokeMethod("Install","\\AppSrv\dsp\NewPackage.msi")
(Get-WmiObject -Class Win32_Product -Filter "Name='ILMerge'" -ComputerName . ).InvokeMethod("Uninstall",$null)
Get-WmiObject -Class Win32_BIOS -ComputerName .
Get-WmiObject Win32_BIOS -ComputerName Server01 ' -Credential (get-credential Domain01\User01)
get-wmiobject win32_bios -computername valery_pc
get-wmiobject win32_bios | format-list *
Get-WmiObject -Class Win32_ComputerSystem
Get-WmiObject -Class Win32_ComputerSystem -ComputerName . | Select-Object -Property SystemType
Get-WmiObject -Class Win32_ComputerSystem -Property UserName -ComputerName .
Get-WmiObject -Class Win32_Desktop -ComputerName .
Get-WmiObject -Class Win32_Desktop -ComputerName . | Select-Object -Property [a-z]*
$c=Get-Credential
---- Get-WmiObject Win32_DiskDrive -ComputerName Server01 -Credential $c
Get-WmiObject -Class Win32_LocalTime -ComputerName . | Select-Object -Property [a-z]*
Get-WmiObject -Class Win32_LogicalDisk | Select-Object -Property Name,FreeSpace
Get-WmiObject -Class Win32_LogicalDisk | Select-Object -Property Name,FreeSpace| Get-Member
Get-WmiObject -Class Win32_LogicalDisk | Select-Object -Property Name,FreeSpace
| ForEach-Object -Process {$_.FreeSpace = ($_.FreeSpace)/1024.0/1024.0; $_}
Get-WmiObject -Class Win32_LogonSession -ComputerName .
Get-WmiObject -Class Win32_NetworkAdapter -ComputerName .
Get-WmiObject -Class Win32_NetworkAdapterConfiguration -Filter IPEnabled=TRUE -ComputerName .
| Select-Object -Property IPAddress
Get-WmiObject -Class Win32_NetworkAdapterConfiguration -Filter IPEnabled=TRUE -ComputerName .
| Select-Object -Property [a-z]* -ExcludeProperty IPX*,WINS*
Get-WmiObject -Class Win32_NetworkAdapterConfiguration -Filter IPEnabled=true -ComputerName .
| ForEach-Object -Process { $_.InvokeMethod("SetDNSDomain", "fabrikam.com")}
Get-WmiObject -Class Win32_OperatingSystem -Namespace root/cimv2 -ComputerName .
Get-WmiObject -Class Win32_OperatingSystem -Namespace root/cimv2 -ComputerName .
| Get-Member -MemberType Property
Get-WmiObject -Class Win32_OperatingSystem -Namespace root/cimv2 -ComputerName .
| Format-List TotalVirtualMemorySize,TotalVisibleMemorySize,FreePhysicalMemory,
FreeVirtualMemory,FreeSpaceInPagingFiles
Get-WmiObject -Class Win32_PingStatus -Filter "Address='127.0.0.1'" -ComputerName .
Get-WmiObject -Class Win32_Printer -ComputerName .
get-wmiobject win32_process -- все процесcы, выполняющихся на компьютере.
Get-WmiObject -Class Win32_Processor -ComputerName . | Select-Object -Property [a-z]*
Get-WmiObject -Class Win32_Product -ComputerName .
Get-WmiObject -Class Win32_Product -ComputerName . | Where-Object
-FilterScript {$_.Name -eq "Microsoft .NET Framework 2.0"} | Select-Object -Property [a-z]*
Get-WmiObject -Class Win32_QuickFixEngineering -ComputerName .
get-wmiobject win32_service -computername 127.0.0.1
get-wmiobject win32_service -computername 192.168.1.88
get-wmiobject win32_service -computername cloud-films
get-wmiobject -query "select * from win32_service where name='alerter'"
(get-wmiobject win32_service -filter "name='alerter'").StopService()
get-wmiobject win32_service -credential FABRIKAM\administrator -computer fabrikam
Get-WmiObject -Class Win32_Service -ComputerName . | Select-Object -Property Status,Name,DisplayName
Get-WmiObject -Class Win32_Service -ComputerName . | Format-Table -Property Status,Name,DisplayName -AutoSize -Wrap
(Get-WmiObject -List -ComputerName . | Where-Object -FilterScript {$_.Name –eq "Win32_Share"})
.InvokeMethod("Create",("C:\temp","TempShare",0,25,"test share of the temp folder"))
(Get-WmiObject -Class Win32_Share -ComputerName . -Filter "Name='TempShare'").InvokeMethod("Delete",$null)
Get-WmiObject -Class Win32_SystemDriver | Sort-Object -Property State,Name |
Format-Table -Property Name,State,Started,DisplayName -AutoSize -Wrap
Get-WmiObject -Class Win32_SystemDriver | Sort-Object -Property State,Name -Descending
| Format-Table -Property Name,State,Started,DisplayName -AutoSize -Wrap
Get-WmiObject -Class Win32_SystemDriver | Where-Object -FilterScript {$_.State -eq "Running"}
| Where-Object -FilterScript {$_.StartMode -eq "Auto"}
$a.GetType()
gl
glo
clear-variable my* -global
go
set-alias go cd32
gr
gro
1..35 | group-object -property {$_ % 2},{$_ % 3}
$events = get-eventlog -logname system -newest 1000 ---- $events | group-object -property eventID
get-process | group-object -property company -noelement
get-childitem | group-object extension -noelement
Get-Process -Name powershell | Format-Table -Wrap -AutoSize -Property Name,Id,Path -GroupBy Company
gt
-gt
========= больше (без учета регистра)
get-process | where-object {$_.WorkingSet -gt 20000000} ---- (>20000000 байт)
get-process | where-object {$_.workingset -gt 25000*1024}
---- (>25000K)
Get-ChildItem *.txt | where {$_.length -gt 100} | Format-Table name, length
Get-ChildItem -Path $env:ProgramFiles -Recurse -Include *.exe | Where-Object
-FilterScript {($_.LastWriteTime -gt "2005-10-01") -and ($_.Length -ge 1m) -and ($_.Length -le 10m)}
h
get-process | where-object {$_.HasExited}
he
$h = get-host ---- $win = $h.ui.rawui.windowsize --- $win.height = 10 --- $win.width = 10
$h.ui.rawui.set_windowsize($win)
hel
help
help about_alias
help about_automatic_variables
help about_command_syntax
help about_comparison_operators
help about_environment_variable
help about_filter
help about_flow_control
help about_for
help about_foreach - отображает справку о циклах foreach в PowerShell.
help about_function
help about_history
help about_if
help about_line_editing
help about_logical_operator
help about_location
help about_method
help about_namespace
help about_object
help about_parameter
help about_parsing
help about_path_syntax
help about_pipeline
help about_property
help about_quoting_rules
help about_scope
help about_script_block
help about_shell_variable
help about_switch
help about_system_state
help about_while
help about_wildcard
help Where-Object - отображает справку о командлете Where-Object.
help Get-ChildItem
help get-command
help Foreach-Object
help Get-Member
Help Get-Process
ho
hom
home
$Home
======== первоначально имеет значение $env:HOMEDRIVE + $env:HOMEPATH
new-psdrive -name MyDocs -psprovider FileSystem -root "$home\My Documents"
Write-Host "`$home = $home"
Host
$Host
======= переменная
i
if
foreach ($file in Get-ChildItem c:\techdocs\*.txt) { if ($file.length -ge 100) { Write-Host $file.name - $file.length байт }
else { Write-Host $file.name - "Этот файл меньше 100 байт."
} }
im
imp
get-acl C:\test.txt | export-clixml -Path testacl.xml
import-csv history.csv | add-history
$a = import-csv c:\testing\history.csv ----
---- $testacl = import-clixml testacl.xml
add-history -inputobject $a -passthru
import-clixml c:\temp\history.xml | add-history -passthru | invoke-history
add-history -inputobject (import-clixml c:\temp\history01.xml)
in
inc
get-childitem . -Include *.txt -Recurse
clear-content c:\Temp\* -Include Smp* -Exclude *2* -whatif
$services = get-service ---- get-service -inputobject $Services -include RPC*
get-variable -include M*,P* | sort-object name
compare-object -referenceobject $(get-content C:\Test\testfile1.txt) -differenceobject $(get-content
C:\Test\testfile2.txt) -includeequal
inp
Input
$Input ======= переменная
Get-Member -inputobject $a -membertype property
$a = get-process ---- get-process -inputobject $a | format-table -view priority
$a = import-csv c:\testing\history.csv ---- add-history -inputobject $a -passthru
add-history -inputobject (import-clixml c:\temp\history01.xml)
$a = "this is a string" --- $a = add-member -inputobject $a -membertype scriptmethod -name words `
-value {$this.split()} -passthru ---- $a.words()
$event = get-eventlog -logname system -newest 1 --- $event.TimeWritten | get-member --add-member -inputobject $event -membertype aliasproperty -name When -value TimeWritten -secondvalue ---System.String ----- $event.When | get-member
$services = get-service ---- get-service -inputobject $Services -include RPC*
$a = get-history ------- out-host -InputObject $a
$a = get-process ------ out-file -filepath C:\Test1\process.txt -inputobject $a -encoding ASCII -width 50
ins
Install
(Get-WMIObject -ComputerName PC01 -List | Where-Object
-FilterScript {$_.Name -eq "Win32_Product"}).InvokeMethod("Install","\\AppSrv\dsp\NewPackage.msi")
inv
invoke
import-clixml c:\temp\history.xml | add-history -passthru | invoke-history
Invoke-History -id 12 --- выполнение 12 команды из журнала команд
get-process | convertto-html -properties Name,Path,Company ' -title "Process Information" > proc.htm --invoke-item proc.htm
Invoke-Item C:\WINDOWS
Invoke-Item C:\boot.ini
(Get-WMIObject -ComputerName PC01 -List | Where-Object
-FilterScript {$_.Name -eq "Win32_Product"}).InvokeMethod("Install","\\AppSrv\dsp\NewPackage.msi")
(Get-WmiObject -Class Win32_Product -Filter "Name='ILMerge'" -ComputerName . ).InvokeMethod("Uninstall",$null)
(Get-WmiObject -Class Win32_Product -ComputerName . -Filter
"Name='OldAppName'").InvokeMethod("Upgrade","\\AppSrv\dsp\OldAppUpgrade.msi")
(Get-WmiObject -Class Win32_OperatingSystem -ComputerName .).InvokeMethod("Win32Shutdown",0)
(Get-WmiObject -ComputerName . -Class Win32_Printer
-Filter "Name='HP LaserJet 5Si'").InvokeMethod("SetDefaultPrinter",$null)
(Get-WmiObject -List -ComputerName . | Where-Object -FilterScript {$_.Name –eq "Win32_Share"})
.InvokeMethod("Create",("C:\temp","TempShare",0,25,"test share of the temp folder"))
(Get-WmiObject -Class Win32_Share -ComputerName . -Filter "Name='TempShare'").InvokeMethod("Delete",$null)
ip
ipconfig
ipconfig | select-string -pattern 255
ipconfig | findstr "Address"
it
ite
item
New-Item -Path 'C:\temp\New Folder' -ItemType "directory"
New-Item -Path 'C:\temp\New Folder\file.txt' –ItemType "file"
j
k
ke
key
$key = (3,4,2,3,56,34,254,222,1,1,2,23,42,54,33,233,1,34,2,7,6,5,35,43) ----$standardstring = convertfrom-securestring $securestring -key $key
l
last
get-process | sort-object -property WS | select-object -Last 5
$LASTEXITCODE ======= переменная
le
-le
========= меньше или равно (без учета регистра)
Get-ChildItem -Path $env:ProgramFiles -Recurse -Include *.exe | Where-Object
-FilterScript {($_.LastWriteTime -gt "2005-10-01") -and ($_.Length -ge 1m) -and ($_.Length -le 10m)}
Get-ChildItem -Path HKCU:\Software -Recurse | Where-Object -FilterScript {($_.SubKeyCount -le 1)
–and ($_.ValueCount -eq 4) }
len
get-childitem | sort-object -property length
get-childitem | measure-object -property length -minimum -maximum -average
foreach ($file in Get-ChildItem c:\techdocs\*.txt) { if ($file.length -ge 100) { Write-Host $file.name - $file.length байт }
else { Write-Host $file.name - "Этот файл меньше 100 байт."
} }
Get-ChildItem c:\ | where { $_.length -lt 100 and !$_.PSIsContainer}
(Get-ChildItem c:\techdocs\final.txt).length
li
lik
like
-like ======= сравнение строк с использованием правил подстановочных знаков
"file.doc" -like "f*.do?"
$_.processname -like "c*"
Get-Process | where {$_.processname -like "[a-m]*"} ====== where= where-object (псевдоним)
lin
get-content C:\test.txt | measure-object -character -line -word
lis
list
Get-WmiObject -List
Get-WmiObject -List -ComputerName 192.168.1.88
lo
log
logoff /?
lt
-lt
========= меньше (без учета регистра)
Get-ChildItem c:\ | where { $_.length -lt 100 and !$_.PSIsContainer}
m
man
man get-command
mat
match
-match ========= сравнение строк по правилам регулярных выражений
-match "ни".
-match "к...я" === ( , == любой знак)
-match "ж[аоу]к"
-match "[к-н]ос"
-match "[^грт]ык"
-match "^кн"
-match "га$"
-match "н*"
-match "xy+" ===== "xyxyxy"
-match "\$1000"
-match "\p{Ll}+"
-match "\P{Ll}+"
-match "\w+"
-match "\w*" ==== "abc"
-match "\w?"
-match "\w{2}"
-match "\w{2,}"
-match "\w{2,3}"
-match "\W+"
-match "\s+"
-match "\S+"
-match "\d+"
-match "\D+"
get-process | where-object { $_.ProcessName -match "^p.*" }
get-alias | where-object {$_.Definition -match "Get-Childitem"}
get-alias | where-object {$_.Options -match "ReadOnly"}
(get-alias | where-object {$_.Options -match "ReadOnly"}).count
max
maximum
get-childitem | measure-object -property length -minimum -maximum -average
$MaximumAliasCount ======= переменная
$MaximumDriveCount ======= переменная
$MaximumFunctionCount ======= переменная
$MaximumHistoryCount ======= переменная
$MaximumVariableCount ======= переменная
me
get-childitem | measure-object
get-childitem | measure-object -property length -minimum -maximum -average
get-content C:\test.txt | measure-object -character -line -word
Get-WmiObject -Class Win32_LogicalDisk -Filter "DriveType=3" -ComputerName .
| Measure-Object -Property FreeSpace,Size -Sum
Get-WmiObject -Class Win32_LogicalDisk -Filter "DriveType=3" -ComputerName .
| Measure-Object -Property FreeSpace,Size -Sum | Select-Object -Property Property,Sum
mem
Get-Member -inputobject $a -membertype method
Get-Member -inputobject $a -membertype property
Get-ChildItem c:\final.txt | Get-Member -membertype property
Get-ChildItem c:\final.txt | Get-Member -membertype NoteProperty
$a = "this is a string" --- $a = add-member -inputobject $a -membertype scriptmethod -name words `
-value {$this.split()} -passthru ---- $a.words()
$event = get-eventlog -logname system -newest 1 --- $event.TimeWritten | get-member --add-member -inputobject $event -membertype aliasproperty -name When -value TimeWritten -secondvalue ---System.String ----- $event.When | get-member
get-process | get-member -MemberType property
met
Get-Member -inputobject $a -membertype method
mi
mic
add-PSSnapIn Microsoft.Exchange,Microsoft.Windows.AD ---- Эта команда добавляет в текущую консоль
оснастки Microsoft Exchange и Microsoft Active Directory Directory Services.
min
get-childitem | measure-object -property length -minimum -maximum -average
mo
mor
more
Get-Command | more
more c:\boot.ini ========== прочитает указанные файлы и разобьет на страницы
mov
move
Move-Item -Path C:\temp\New.Directory -Destination C:\ -PassThru
(Get-ChildItem c:\final.txt).MoveTo("c:\techdocs\final.txt")
ms
msi
(Get-WMIObject -ComputerName PC01 -List | Where-Object
-FilterScript {$_.Name -eq "Win32_Product"}).InvokeMethod("Install","\\AppSrv\dsp\NewPackage.msi")
n
nam
name
$processes = get-process | select-object ProcessName,@{Name="Start Day"; Expression = {$_.StartTime.DayOfWeek}}
$a = "this is a string" --- $a = add-member -inputobject $a -membertype scriptmethod -name words `
-value {$this.split()} -passthru ---- $a.words()
$event = get-eventlog -logname system -newest 1 --- $event.TimeWritten | get-member --add-member -inputobject $event -membertype aliasproperty -name When -value TimeWritten -secondvalue ---System.String ----- $event.When | get-member
clear-itemproperty -path HKLM:\Software\MyCompany\MyApp -name Options
clear-variable -name processes
get-alias -name g*, s*
foreach ($file in Get-ChildItem c:\techdocs\*.txt) { if ($file.length -ge 100) { Write-Host $file.name - $file.length байт }
else { Write-Host $file.name - "Этот файл меньше 100 байт."
} }
(Get-ChildItem c:\final.txt).name.ToUpper()
ne
-ne
========= не равно (без учета регистра)
1 -ne 2
neq
Get-Process -Name BadApp | Where-Object -FilterScript {$_.SessionId -neq 0} | Stop-Process
net
net share tempshare=c:\temp /users:25 /remark:"test share of the temp folder"
net share tempshare /delete
net use B: \\FPS01\users
netsh
new
(New-Object -ComObject Scripting.FileSystemObject).CopyFile("c:\boot.ini", "c:\boot.bak")
New-Object -ComObject WScript.Shell
New-Object -ComObject WScript.Network
(New-Object -ComObject WScript.Network).EnumPrinterConnections()
(New-Object -ComObject WScript.Network).RemovePrinterConnection("\\Printserver01\Xerox5")
(New-Object -ComObject WScript.Network).MapNetworkDrive("B:", "\\FPS01\users")
New-Object -ComObject Scripting.Dictionary
New-Object -ComObject Scripting.FileSystemObject
$ie = New-Object -ComObject InternetExplorer.Application
$xl = New-Object -ComObject Excel.Application -Strict
New-Object System.Environment
New-Object -TypeName System.Diagnostics.EventLog
New-Object -TypeName System.Diagnostics.EventLog -ArgumentList
$AppLog = New-Object -TypeName System.Diagnostics.EventLog -ArgumentList Application
$RemoteAppLog = New-Object -TypeName System.Diagnostics.EventLog Application,192.168.1.88 --- $RemoteAppLog
New-Item -Path 'C:\temp\New Folder' -ItemType "directory"
New-Item -Path 'C:\temp\New Folder\file.txt' –ItemType "file"
get-command -name New-Item -syntax
New-Item -Path hkcu:\software\_DeleteMe
New-Item -Path Registry::HKCU\_DeleteMe
Get-Command -Name New-PSDrive -Syntax
new-psdrive -name MyDocs -psprovider FileSystem -root "$home\My Documents"
New-PSDrive -Name Office -PSProvider FileSystem -Root "C:\Program Files\Microsoft Office\OFFICE11"
New-PSDrive -Name cvkey -PSProvider Registry -Root HKLM\Software\Microsoft\W
$event = get-eventlog -logname system -newest 1 --- $event.TimeWritten | get-member --add-member -inputobject $event -membertype aliasproperty -name When -value TimeWritten -secondvalue ---System.String ----- $event.When | get-member
no
export-alias -path alias.txt -noclobber
get-process | out-file C:\Test1\process.txt -noclobber == NoClobber предотвращает перезапись существующего файла
get-process | group-object -property company -noelement
nolike
-notlike ======= сравнение строк с использованием правил подстановочных знаков
"file.doc" -notlike "p*.doc"
notmatch
-notmatch ========= сравнение строк по правилам регулярных выражений
not
-not
========= логическое "НЕ" (с псевдонимом !)
-not (1 -eq 2)
notc
notcontains
1,2,3 -notcontains 4
notepad
$a = "a string" ----- $a = $a | add-member noteproperty StringUse Display -passthru --- $a.StringUse
Get-ChildItem c:\final.txt | Get-Member -membertype NoteProperty
o
of
ofs
$OFS ========
Output Field Separator (по умолчанию пробел)
op
opt
clear-itemproperty -path HKLM:\Software\MyCompany\MyApp -name Options
or
-or
========
логическое "ИЛИ"
(1 -eq 1) -or (1 -eq 2)
ou
out
get-process | out-file -filepath C:\Test1\process.txt
get-process | out-file C:\Test1\process.txt -noclobber == NoClobber предотвращает перезапись существующего файла
$a = get-process ------ out-file -filepath C:\Test1\process.txt -inputobject $a -encoding ASCII -width 50
Get-ChildItem -Path C:\WINDOWS\System32 | Out-Host -Paging
$a = get-history ------- out-host -InputObject $a
Get-Process | Format-List | Out-Host -Paging
get-childitem | out-null
"Hello, World" | out-printer -name "\\Server01\Prt-6B Color"
get-content $pshome\about_signing.help.txt | Out-Printer ===== на принтер по умолчанию
get-alias | out-string -stream | select-string "Get-Command"
p
pag
Get-ChildItem -Path C:\WINDOWS\System32 | Out-Host -Paging
par
get-help get-childitem -parameter f*
get-help get-command -parameter totalcount
pas
passthru ==== для возвращения сведений о результатах в случаях, когда по умолчанию вывод отсутствует.
import-clixml c:\temp\history.xml | add-history -passthru | invoke-history
$a = import-csv c:\testing\history.csv ---- add-history -inputobject $a -passthru
$a = "a string" ----- $a = $a | add-member noteproperty StringUse Display -passthru --- $a.StringUse
get-pssnapin -registered | add-pssnapin -passthru --- Эта команда добавляет в консоль все
зарегистрированные оснастки Windows PowerShell.
pat
path
clear-content -path * -filter *.log -force
get-acl -path hklm:\system\currentcontrolset\control | format-list
Get-ChildItem -Path Microsoft.PowerShell.Core\Registry::HKEY_CURRENT_USER
get-itemproperty -path HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion
add-content -path monthly.txt -value (get-content c:\rec1\weekly.txt)
get-process wmiprvse | select-object basePriority,ID,SessionID,WorkingSet | export-csv -path data.csv
get-itemproperty -path hkcu:\Network\* | foreach-object {set-itemproperty -path $_.pspath -name RemotePath
-value $_.RemotePath.ToUpper();}
Get-ChildItem -Path HKCU:\Software -Recurse | Where-Object -FilterScript {($_.SubKeyCount -le 1)
–and ($_.ValueCount -eq 4) }
Copy-Item -Path 'HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion' -Destination hkcu:
Copy-Item -Path 'HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion' -Destination hkcu: -Recurse
Get-ChildItem -Path Uninstall: | ForEach-Object -Process { $_.GetValue("UninstallString") }
po
pop
Pop-Location
Pop-Location -PassThru
pow
powershell
powershell -?
powershell.exe -PsConsoleFile NewPsSnapinConsole.psc1 === запускает сохраненную консоль
pr
pri
$a = get-process ----
get-process -inputobject $a | format-table -view priority
pro
$_.processname -like "c*"
$events = get-eventlog -logname system -newest 1000 ---- $events | foreach-object
-begin {get-date} -process
{out-file -filepath events.txt -append -inputobject $_.message} -end {get-date}
30000,56798,12432 | foreach-object -process {$_/1024} ---- делит каждое на 1024 и отображает результаты.
get-childitem C:\ | foreach-object -process { $_.length / 1024 }
get-process | where-object { $_.ProcessName -match "^p.*" }
get-process | get-member -MemberType property
Get-Member -inputobject $a -membertype property
get-process | sort-object -property WS | select-object -Last 5
get-childitem | sort-object -property length
1..35 | group-object -property {$_ % 2},{$_ % 3}
---- остатки от деления на 2 и3
$events = get-eventlog -logname system -newest 1000 ---- $events | group-object -property eventID
get-process | group-object -property company -noelement
get-eventlog -logname system -newest 1000 | group-object -property {$_.TimeWritten - $_.TimeGenerated}
get-service schedule | format-list -property *
get-service alerter | format-list -property name, CanPauseAndContinue
get-service | format-table -property name, CanPauseAndContinue
Get-WmiObject -Class Win32_Desktop -ComputerName . | Select-Object -Property [a-z]*
get-help -category provider
ps
c:\test\testscript.ps1 ---- запуск сценария (можно без расширения)
выполнение сценариев отключено !!!!!!!!!!!!
.\testscript.ps1
--- из текущего каталога
$pshome
======= переменная
Get-ChildItem c: | where {$_.PsIsContainer -eq $false} | Format-List
pu
pus
push
Push-Location -Path "Local Settings"
Push-Location -Path Temp
q
que
get-wmiobject -query "select * from win32_service where name='alerter'"
r
re
$securestring = read-host -assecurestring
--- запись с клавиатуры ,а на экране * в System.Security.SecureString
get-childitem registry::hklm\software
rec
recurse ======= Для показа вложенных элементов необходимо также указать параметр -Recurse
copy-item C:\Logfiles -destination C:\Drawings -recurse
Copy-Item -Path 'HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion' -Destination hkcu: -Recurse
Get-ChildItem -Path C:\Windows\*.dll -Recurse -Exclude [a-y]*.dll
get-childitem . -Include *.txt -Recurse
ref
compare-object -referenceobject $(get-content C:\test\testfile1.txt) -differenceobject $(get-content C:\test\testfile2.txt)
reg
clear-item registry::HKLM\Software\MyCompany\MyKey -confirm
get-pssnapin -registered | add-pssnapin -passthru --- Эта команда добавляет в консоль все
зарегистрированные оснастки Windows PowerShell.
rem
Remove
remove-item C:\Test\*.*
Remove-Item C:\New.Directory
Remove-Item C:\temp\New.Directory -Recurse
remove-item * -include *.doc -exclude *1*
remove-item -path C:\Test\hidden-RO-file.txt -force
get-childitem * -include *.csv -recurse | remove-item
remove-item hklm:\software\mycompany\OldApp -recurse
Remove-Item -Path hkcu:\Software\_DeleteMe
Remove-Item -Path 'hkcu:\key with spaces in the name'
Remove-Item -Path hkcu:\CurrentVersion
Remove-Item -Path HKCU:\CurrentVersion -Recurse
Remove-Item -Path HKCU:\CurrentVersion\* -Recurse
Remove-Variable -Name * -Force -ErrorAction SilentlyContinue ==== очистить все переменные
set-executionpolicy -scope CurrentUser remotesigned
Remove-PSDrive -Name Office
remove-pssnapin sql ========== удаление оснастки из консоли
ren
rename
Rename-Item -Path C:\temp\New.Directory\file1.txt fileOne.txt
rep
get-date | convertto-html -title "Date Table" | foreach { $_ -replace "><",">`n<" }
Report
$ReportErrorShowExceptionClass
======= переменная
$ReportErrorShowInnerException======= переменная
$ReportErrorShowSource ======= переменная
$ReportErrorShowStackTrace ======= переменная
res
Restart-Service -Name spooler
Get-Service | Where-Object -FilterScript {$_.CanStop} | Restart-Service
ro
roo
new-psdrive -name MyDocs -psprovider FileSystem -root "$home\My Documents"
ru
run
rundll
rundll32.exe user32.dll,LockWorkStation
====== блокирует рабочую станцию
s
save-Help
sc
sch
get-service schedule | format-list -property *
sco
set-executionpolicy -scope CurrentUser remotesigned
scr
export-alias -path alias.txt -as script ---- notepad alias.txt
$a = "this is a string" --- $a = add-member -inputobject $a -membertype scriptmethod -name words `
-value {$this.split()} -passthru ---- $a.words()
se
$event = get-eventlog -logname system -newest 1 --- $event.TimeWritten | get-member --add-member -inputobject $event -membertype aliasproperty -name When -value TimeWritten -secondvalue ---System.String ----- $event.When | get-member
sel
get-process | sort-object | select processname | get-unique -asstring
get-childitem | sort-object
get-childitem | sort-object -property length
get-acl C:\Windows\k*.log | select-object PSPath, Sddl | format-list
get-process | select-object processname -expandproperty modules | format-list
get-process | sort-object -property WS | select-object -Last 5
$processes = get-process | select-object ProcessName,@{Name="Start Day"; Expression = {$_.StartTime.DayOfWeek}}
"a","b","c","a","a","a" | select-object -unique ---- Эта команда выводит уникальные знаки из массива знаков. ( a b c)
get-process wmiprvse | select-object basePriority,ID,SessionID,WorkingSet | export-csv -path data.csv
Get-WmiObject -Class Win32_Desktop -ComputerName . | Select-Object -Property [a-z]*
get-alias | out-string -stream | select-string "Get-Command"
set
Set-Alias np c:\windows\notepad.exe
set-alias -name list -value get-childitem
set-alias list get-location
set-alias scrub remove-item -option readonly -passthru | format-list
function CD32 {set-location c:\windows\system32} ---- set-alias go cd32
Get-Help Set-AuthenticodeSignature
get-content c:\Logs\Log060912.txt -totalcount 50 | set-content sample.txt
set-executionpolicy -scope CurrentUser remotesigned
Set-ExecutionPolicy Restricted
get-itemproperty -path hkcu:\Network\* | foreach-object {set-itemproperty -path $_.pspath -name RemotePath
-value $_.RemotePath.ToUpper();}
set-location alias:
set-location C:
Set-Location -Path C:\Windows
Set-Location -Path .. -PassThru
set-location HKLM:
Set-Location -Path HKLM:\SOFTWARE -PassThru
Set-Location -Path Registry::HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion
set-location env: -passthru
set-location \\cloud-films\public
function CD32 {set-location c:\windows\system32}
set-service -?
:отображает справку о командлете
Set-Service.
$h = get-host ---- $win = $h.ui.rawui.windowsize --- $win.height = 10 --- $win.width = 10
$h.ui.rawui.set_windowsize($win)
sh
sho
Should
$ShouldProcessPreference ======= переменная
$ShouldProcessReturnPreference ======= переменная
show
Show-Command
======== вывод в выпадающее окно всех команд
shu
shut
shutdown -r -r (перезагрузка) команды Shutdown
shutdown.exe -l
so
sor
sort
1,1,1,1,12,23,4,5,4643,5,3,3,3,3,3,3,3 | sort-object | Get-Unique
get-variable -include M*,P* | sort-object name
get-childitem | sort-object {$_.GetType()} | unique -OnType
get-childitem *.txt | sort-object @{Expression={$_.LastWriteTime-$_.CreationTime}; Ascending=$false} |
select-object LastWriteTime, CreationTime
get-process | sort-object -property WS | select-object -Last 5
Get-WmiObject -Class Win32_SystemDriver | Sort-Object -Property State,Name |
Format-Table -Property Name,State,Started,DisplayName -AutoSize -Wrap
get-history | sort-object -descending
gci *.txt | Sort-Object @{Expression={$_.LastWriteTime-$_.CreationTime}
get-command | sort-object noun | format-table -group noun --- сортировка по алфавиту
get-process | sort-object | select processname | get-unique -asstring
sp
spl
$a = "this is a string" --- $a = add-member -inputobject $a -membertype scriptmethod -name words `
-value {$this.split()} -passthru ---- $a.words()
sq
sqr
sqrt
[System.Math]::Sqrt(9)
st
Stack
$StackTrace ======= переменная
star
start
Start-Process
get-help start-service -examples
Start-Service -Name spooler
Start-Transcript ========== Создает запись сеанса Windows PowerShell
stat
status
get-service | where-object {$_.Status -eq "Stopped"}
sto
stop
(get-service schedule).stop()
Stop-Process -Name Idle
Stop-Process -Name t*,e* -Confirm
Get-Process | Where-Object -FilterScript {$_.Responding -eq $false} | Stop-Process
Get-Process -Name BadApp | Where-Object -FilterScript {$_.SessionId -neq 0} | Stop-Process
Get-Process -Name powershell | Where-Object -FilterScript {$_.Id -ne $PID} | Stop-Process -PassThru
$p = get-process calc ---- stop-process -inputobject $p
get-service | where-object {$_.Status -eq "Stopped"}
(get-wmiobject win32_service -filter "name='alerter'").StopService()
Stop-Service -Name spooler
Stop-Transcript ========== останавливает запись сеанса Windows PowerShell
str
get-alias | out-string -stream | select-string "Get-Command"
$a = "a string" -----
$a = $a | add-member noteproperty StringUse Display -passthru --- $a.StringUse
$event = get-eventlog -logname system -newest 1 --- $event.TimeWritten | get-member --add-member -inputobject $event -membertype aliasproperty -name When -value TimeWritten -secondvalue ---System.String ----- $event.When | get-member
$a = "a string" -----
$a = $a | add-member noteproperty StringUse Display -passthru --- $a.StringUse
su
sub
subst
subst p: $env:programfiles
====== создает локальный диск P:,
sus
Suspend-Service -Name spooler === Чтобы приостановить очередь печати
sy
syn
Get-Command -Syntax
(get-help write-object).syntax
sys
System
[System.Math]::Abs(-30)
[System.Math]::Acos(-0.5)
[System.Math]::Asin(?)
[System.Math]::Atan(?)
[System.Math]::Atan2(?)
[System.Math]::Ceiling(-3.3)
[System.Math]::Cos(?)
[System.Math]::Cosh(?)
[System.Math]::Exp(?)
[System.Math]::Floor(-3.3)
[System.Math]::Log(?)
[System.Math]::Log10(?)
[System.Math]::Max(2,7)
[System.Math]::Min(2,7)
[System.Math]::Pow(2,3)
[System.Math]::Round(?)
[System.Math]::Sign(?)
[System.Math]::Sin(?)
[System.Math]::Sinh(?)
[System.Math]::Sqrt(9)
[System.Math]::Tan(?)
[System.Math]::Tanh(?)
[System.Math]::Truncate(9.3)
$event = get-eventlog -logname system -newest 1 --- $event.TimeWritten | get-member --add-member -inputobject $event -membertype aliasproperty -name When -value TimeWritten -secondvalue ---System.String ----- $event.When | get-member
New-Object -TypeName System.Diagnostics.EventLog
System.Management.Automation.PSObject
System.ServiceProcess.ServiceController
System.Object
t
th
thi
$a = "this is a string" --- $a = add-member -inputobject $a -membertype scriptmethod -name words `
-value {$this.split()} -passthru ---- $a.words()
ti
tim
$event = get-eventlog -logname system -newest 1 --- $event.TimeWritten | get-member --add-member -inputobject $event -membertype aliasproperty -name When -value TimeWritten -secondvalue ---System.String ----- $event.When | get-member
tit
get-date | convertto-html -title "Date Table" | foreach { $_ -replace "><",">`n<" }
to
tou
toup
(Get-ChildItem c:\final.txt).name.ToUpper()
tr
tru
true
get-process -name svchost | where-object {$True}
tx
txt
function text_files
{
Get-ChildItem c:\techdocs\*.txt }
get-content C:\test.txt | measure-object -character -line -word
get-childitem . -Include *.txt -Recurse
get-childitem c:\windows\logs\* -include *.txt -exclude A*
ty
typ
type
Get-Command -type cmdlet
New-Object -TypeName System.Diagnostics.EventLog
u
uf
get-date -uformat "%Y / %m / %d / %A / %Z"
un
uni
get-childitem | sort-object {$_.GetType()} | unique -OnType
uninstall
Get-ChildItem -Path Uninstall: | ForEach-Object -Process { $_.GetValue("UninstallString") }
(Get-WmiObject -Class Win32_Product -Filter "Name='ILMerge'" -ComputerName . ).InvokeMethod("Uninstall",$null)
Get-ChildItem -Path Uninstall: | Where-Object -FilterScript { $_.GetValue("DisplayName") -like "Win*"}
| ForEach-Object -Process { $_.GetValue("UninstallString") }
up
Update-Help
v
val
add-content -path *.txt -exclude help* -value "END"
add-content -Path file1.log, file2.log -Value (get-date) -passthru
add-content -path monthly.txt -value (get-content c:\rec1\weekly.txt)
$event = get-eventlog -logname system -newest 1 --- $event.TimeWritten | get-member --add-member -inputobject $event -membertype aliasproperty -name When -value TimeWritten -secondvalue ---System.String ----- $event.When | get-member
get-itemproperty -path hkcu:\Network\* | foreach-object {set-itemproperty -path $_.pspath -name RemotePath
-value $_.RemotePath.ToUpper();}
get-variable m* -valueonly
var
Get-ChildItem variable: ========== все переменные Windows PowerShell
ve
ver
get-command -verb set | format-list
$VerbosePreference
---- только содержащих глагол "set"
======= переменная
vi
$a = get-process ----
get-process -inputobject $a | format-table -view priority
w
war
$WarningPreference ======= переменная
wh
Wait-Process
clear-content c:\Temp\* -Include Smp* -Exclude *2* -whatif
--- что произойдет при выполнении этой команды
whe
when
$event = get-eventlog -logname system -newest 1 --- $event.TimeWritten | get-member --add-member -inputobject $event -membertype aliasproperty -name When -value TimeWritten -secondvalue ---System.String ----- $event.When | get-member
where
Get-ChildItem c:\ | where { $_.length -lt 100 and !$_.PSIsContainer}
Get-ChildItem *.txt | where {$_.length -gt 100} | Format-Table name, length
1,2,3,4 | Where-Object -FilterScript {$_ -lt 3}
get-process | where-object {$_.WorkingSet -gt 20000000}
get-process | where-object {$_.HasExited}
Get-Help Where-Object -full
get-service | where-object {$_.Status -eq "Stopped"}
get-process | where-object {$_.workingset -gt 25000*1024}
get-process | where-object { $_.ProcessName -match "^p.*" }
get-process -name svchost | where-object {$True}
get-alias | where-object {$_.Definition -match "Get-Childitem"}
Get-ChildItem -Path $env:ProgramFiles -Recurse -Include *.exe | Where-Object
-FilterScript {($_.LastWriteTime -gt "2005-10-01") -and ($_.Length -ge 1m) -and ($_.Length -le 10m)}
Get-ChildItem -Path HKCU:\Software -Recurse | Where-Object -FilterScript {($_.SubKeyCount -le 1)
–and ($_.ValueCount -eq 4) }
whi
while
while($val -ne 3){$val++; Write-Host $val}
$i = 3 --- while ($true) { trap [DivideByZeroException] { Write-Host "исключение перехвачено"
--- break} 1 / $i-- }
wi
wid
$h = get-host ---- $win = $h.ui.rawui.windowsize --- $win.height = 10 --- $win.width = 10
$h.ui.rawui.set_windowsize($win)
$a = get-process ------ out-file -filepath C:\Test1\process.txt -inputobject $a -encoding ASCII -width 50
win
get-wmiobject win32_bios | format-list *
Get-WmiObject Win32_BIOS -ComputerName Server01 ' -Credential (get-credential Domain01\User01)
Get-WmiObject -Class Win32_ComputerSystem -ComputerName . | Select-Object -Property SystemType
Get-WmiObject -Class Win32_ComputerSystem -Property UserName -ComputerName .
Get-WmiObject -Class Win32_Desktop -ComputerName .
Get-WmiObject -Class Win32_Desktop -ComputerName . | Select-Object -Property [a-z]*
$c=Get-Credential
---- Get-WmiObject Win32_DiskDrive -ComputerName Server01 -Credential $c
Get-WmiObject -Class Win32_LocalTime -ComputerName . | Select-Object -Property [a-z]*
Get-WmiObject -Class Win32_LogicalDisk | Select-Object -Property Name,FreeSpace
Get-WmiObject -Class Win32_LogicalDisk | Select-Object -Property Name,FreeSpace| Get-Member
Get-WmiObject -Class Win32_LogicalDisk | Select-Object -Property Name,FreeSpace
| ForEach-Object -Process {$_.FreeSpace = ($_.FreeSpace)/1024.0/1024.0; $_}
Get-WmiObject -Class Win32_LogicalDisk -Filter "DriveType=3" -ComputerName .
Get-WmiObject -Class Win32_LogicalDisk -Filter "DriveType=3" -ComputerName .
| Measure-Object -Property FreeSpace,Size -Sum
Get-WmiObject -Class Win32_LogicalDisk -Filter "DriveType=3" -ComputerName .
| Measure-Object -Property FreeSpace,Size -Sum | Select-Object -Property Property,Sum
Get-WmiObject -Class Win32_LogonSession -ComputerName .
Get-WmiObject -Class Win32_NetworkAdapter -ComputerName .
Get-WmiObject -Class Win32_NetworkAdapterConfiguration -Filter IPEnabled=TRUE -ComputerName .
| Select-Object -Property IPAddress
Get-WmiObject -Class Win32_NetworkAdapterConfiguration -Filter IPEnabled=TRUE -ComputerName .
| Select-Object -Property [a-z]* -ExcludeProperty IPX*,WINS*
Get-WmiObject -Class Win32_NetworkAdapterConfiguration -Filter IPEnabled=true -ComputerName .
| ForEach-Object -Process { $_.InvokeMethod("SetDNSDomain", "fabrikam.com")}
Get-WmiObject -Class Win32_NetworkAdapterConfiguration -ComputerName . | Where-Object
-FilterScript {$_.IPEnabled} | ForEach-Object -Process {$_.InvokeMethod("SetDNSDomain", "fabrikam.com")}
Get-WmiObject -Class Win32_OperatingSystem -Namespace root/cimv2 -ComputerName .
Get-WmiObject -Class Win32_OperatingSystem -Namespace root/cimv2 -ComputerName .
| Get-Member -MemberType Property
Get-WmiObject -Class Win32_OperatingSystem -Namespace root/cimv2 -ComputerName .
| Format-List TotalVirtualMemorySize,TotalVisibleMemorySize,FreePhysicalMemory,
FreeVirtualMemory,FreeSpaceInPagingFiles
Get-WmiObject -Class Win32_OperatingSystem ======= SerialNumber : 00178-10518-87676-AB307
Get-WmiObject -Class Win32_OperatingSystem -ComputerName . | Select-Object -Property
Get-WmiObject -Class Win32_OperatingSystem -ComputerName . | Select-Object -Property *user*
(Get-WmiObject -Class Win32_OperatingSystem -ComputerName .).InvokeMethod("Win32Shutdown",0)
Get-WmiObject -Class Win32_PingStatus -Filter "Address='127.0.0.1'" -ComputerName .
Get-WmiObject -Class Win32_PingStatus -Filter "Address='127.0.0.1'" -ComputerName .
| Select-Object -Property Address,ResponseTime,StatusCode
Get-WmiObject -Class Win32_Printer -ComputerName .
(Get-WmiObject -ComputerName . -Class Win32_Printer
-Filter "Name='HP LaserJet 5Si'").InvokeMethod("SetDefaultPrinter",$null)
get-wmiobject win32_process -- все процесcы, выполняющихся на компьютере.
Get-WmiObject -Class Win32_Processor -ComputerName . | Select-Object -Property [a-z]*
Get-WmiObject -Class Win32_Product -ComputerName .
Get-WmiObject -Class Win32_Product -ComputerName . | Where-Object
-FilterScript {$_.Name -eq "Microsoft .NET Framework 2.0"} | Select-Object -Property [a-z]*
Get-WmiObject -Class Win32_Product -ComputerName . -Filter "Name='Microsoft .NET Framework 2.0'"
| Select-Object -Property [a-z]*
(Get-WmiObject -Class Win32_Product -Filter "Name='ILMerge'" -ComputerName . ).InvokeMethod("Uninstall",$null)
Get-WmiObject -Class Win32_QuickFixEngineering -ComputerName . ===== список установленных обновлений (KB......)
Get-WmiObject -Class Win32_QuickFixEngineering -ComputerName . -Property HotFixId | Select-Object -Property HotFixId
get-wmiobject win32_service -computername 127.0.0.1
get-wmiobject win32_service -credential FABRIKAM\administrator -computer fabrikam
Get-WmiObject -Class Win32_Service -ComputerName . | Select-Object -Property Status,Name,DisplayName
Get-WmiObject -Class Win32_Service -ComputerName . | Format-Table -Property Status,Name,DisplayName -AutoSize -Wrap
get-wmiobject -query "select * from win32_service where name='alerter'"
(Get-WmiObject -List -ComputerName . | Where-Object -FilterScript {$_.Name –eq "Win32_Share"})
.InvokeMethod("Create",("C:\temp","TempShare",0,25,"test share of the temp folder"))
(Get-WmiObject -Class Win32_Share -ComputerName . -Filter "Name='TempShare'").InvokeMethod("Delete",$null)
Get-WmiObject -Class Win32_SystemDriver | Sort-Object -Property State,Name |
Format-Table -Property Name,State,Started,DisplayName -AutoSize -Wrap
Get-WmiObject -Class Win32_SystemDriver | Sort-Object -Property State,Name -Descending
| Format-Table -Property Name,State,Started,DisplayName -AutoSize -Wrap
Get-WmiObject -Class Win32_SystemDriver | Where-Object -FilterScript {$_.State -eq "Running"}
| Where-Object -FilterScript {$_.StartMode -eq "Auto"}
wo
wor
get-content C:\test.txt | measure-object -character -line -word
$a = "this is a string" --- $a = add-member -inputobject $a -membertype scriptmethod -name words `
-value {$this.split()} -passthru ---- $a.words()
$a = "this is a string" --- $a = add-member -inputobject $a -membertype scriptmethod -name words `
-value {$this.split()} -passthru ---- $a.words()
get-process | where-object {$_.WorkingSet -gt 20000000}
ws
WScript
New-Object -ComObject WScript.Shell
New-Object -ComObject WScript.Network
(New-Object -ComObject WScript.Network).EnumPrinterConnections()
(New-Object -ComObject WScript.Network).AddWindowsPrinterConnection("\\Printserver01\Xerox5")
(New-Object -ComObject WScript.Network).SetDefaultPrinter('HP LaserJet5Si')
(New-Object -ComObject WScript.Network).RemovePrinterConnection("\\Printserver01\Xerox5")
(New-Object -ComObject WScript.Network).MapNetworkDrive("B:", "\\FPS01\users")
wr
wrap
Get-Command -Noun Variable | Format-Table -Property Name,Definition -AutoSize -Wrap
wri
write
Write-Host book
Write-Host "`$home = $home"
Write-Host 'Как говорится, "учись, пока жив".' ======== Как говорится, "учись, пока жив".
Write-Host 'Знак `' несложно вставить в строку PowerShell.'== Знак ' несложно вставить в строку PowerShell.
Write-Host "Перейти на новую строку `nздесь "
Write-Host "Привет, `"Антон`"" ======== Привет, "Антон"
Write-Host "12345678123456781`nСт1`tСтолбец2`tСт3"
$a = (Get-ChildItem c:\techdocs\final.txt) ---- Write-Host $a.fullname $a.length $a.lastwritetime
foreach ($file in Get-ChildItem c:\techdocs\*.txt) { if ($file.length -ge 100) { Write-Host $file.name - $file.length байт }
else { Write-Host $file.name - "Этот файл меньше 100 байт."
} }
$a = {Write-Host $file.fullname $file.length}
(get-help write-object).syntax
x
xo
xor
-xor
=========== оператор "Исключающее ИЛИ"
y
z
DBGrid.SelectedField.AsString