信创国产化如何推动技术自主创新与安全保障的未来发展
955
2022-09-11
PowerShell - 基础参考
认识PowerShell
运行PowerShell窗口
Windows PowerShell 命令行窗口Windows PowerShell 命令行窗口(x86)Windows PowerShell 集成脚本环境Windows PowerShell 继承脚本环境(x86)
打开窗口时,右键选择以管理员身份运行
查看PowerShell版本
PS C:\Users\Administrator> $PSVersionTableName Value ---- ----- PSVersion 5.1.17763.2090 PSEdition Desktop PSCompatibleVersions {1.0, 2.0, 3.0, 4.0...} BuildVersion 10.0.17763.2090 CLRVersion 4.0.30319.42000 WSManStackVersion 3.0 PSRemotingProtocolVersion 2.3 SerializationVersion 1.1.0.1 PS C:\Users\Administrator> $PSVersionTable.PSVersionMajor Minor Build Revision----- ----- ----- --------5 1 17763 2090
获得PowerShell命令
PS C:\Users\Administrator> Get-Command
筛选PowerShell命令
获取动词是Get的命令
PS C:\Users\Administrator> Get-Command -Verb Get
获取名词是Service的命令
PS C:\Users\Administrator> Get-Command -Noun Service
获取动词是Get,名词是Service的命令
PS C:\Users\Administrator> Get-Command -Verb Get -Noun ServiceCommandType Name Version Source ----------- ---- ------- ------ Cmdlet Get-Service 3.1.0.0 Microsoft.PowerShell.Management
获取包含Process的命令(*为通配符,代表任意字符,包括 0 个字符)
PS C:\Users\Administrator> Get-Command *Process*CommandType Name Version Source ----------- ---- ------- ------ Function Get-AppvVirtualProcess 1.0.0.0 AppvClient Function Start-AppvVirtualProcess 1.0.0.0 AppvClient Cmdlet ConvertTo-ProcessMitigationPolicy 1.0.11 ProcessMitigations Cmdlet Debug-Process 3.1.0.0 Microsoft.PowerShell.Management Cmdlet Enter-PSHostProcess 3.0.0.0 Microsoft.PowerShell.Core Cmdlet Exit-PSHostProcess 3.0.0.0 Microsoft.PowerShell.Core Cmdlet Get-Process 3.1.0.0 Microsoft.PowerShell.Management Cmdlet Get-ProcessMitigation 1.0.11 ProcessMitigations Cmdlet Get-PSHostProcessInfo 3.0.0.0 Microsoft.PowerShell.Core Cmdlet Set-ProcessMitigation 1.0.11 ProcessMitigations Cmdlet Start-Process 3.1.0.0 Microsoft.PowerShell.Management Cmdlet Stop-Process 3.1.0.0 Microsoft.PowerShell.Management Cmdlet Wait-Process 3.1.0.0 Microsoft.PowerShell.Management Application qprocess.exe 10.0.17... C:\Windows\system32\qprocess.exe
使用PowerShell帮助
更新帮助
Update-Help
查询Get-Service命令的使用帮助
PS C:\Users\Administrator> Get-Help -Name Get-Service
查询Get-Service命令的使用帮助(包括使用案例)
PS C:\Users\Administrator> Get-Help -Name Get-Service -Examples
查询Get-Service命令的使用帮助(详细说明)
PS C:\Users\Administrator> Get-Help -Name Get-Service -Details
查询Get-Service命令的使用帮助(在线)
PS C:\Users\Administrator> Get-Help -Name Get-Service -Online
如何使用关于帮助
Get-Help -Name about*Get-Help -Name about_PipelinesGet-Help -Name about_VariablesGet-Help -Name about_ArraysGet-Help -Name about_Hash_TablesGet-Help -Name about_ParametersGet-Help -Name about_FunctionsGet-Help -Name about_ModulesGet-Help -Name about_ScriptsGet-Help -Name about_Execution_PoliciesGet-Help -Name about_ForeachGet-Help -Name about_If
案例:
PS C:\Users\Administrator> Get-Help -Name Get-Service -Online
使用方式一
Get-Service [[-Name]
最外层和-Name的[]表示可选项
[-ComputerName
[-DependentServices]
[-RequiredServices]
[-Include
[-Exclude
[
使用PowerShell注意
Powershell很强大,同时也需要安全的使用
Get-Service会获取本机上的所有服务的信息
那么Get-Service | Stop-service会怎么样呢?
当我们不确定命令的功能时,可以使用参数-WhatIf
PS C:\Users\Administrator> Get-Service | Stop-Service -WhatIf
使用-WhatIf参数时,系统会告诉我们将要做什么,但是并未执行
PowerShell常用命令
管道命令 |
PS C:\Users\Administrator> Get-Service -Name SpoolerStatus Name DisplayName ------ ---- ----------- Running Spooler Print Spooler PS C:\Users\Administrator> Get-Service -Name Spooler | Stop-ServicePS C:\Users\Administrator> Get-Service -Name SpoolerStatus Name DisplayName ------ ---- ----------- Stopped Spooler Print Spooler
Get-Help -Name Stop-Service -Online
-Name
Specifies the service names of the services to stop. Wildcard characters are permitted.
Type: | String[] |
Aliases: | ServiceName |
Position: | 0 |
Default value: | None |
Accept pipeline input: | True |
Accept wildcard characters: | True |
Get-Member
PS C:\Users\Administrator> Get-Service -Name Spooler | Get-Member TypeName:System.ServiceProcess.ServiceControllerName MemberType Definition ---- ---------- ---------- Name AliasProperty Name = ServiceName RequiredServices AliasProperty RequiredServices = ServicesDependedOn Disposed Event System.EventHandler Disposed(System.Object, System.EventArgs) Close Method void Close() Continue Method void Continue() CreateObjRef Method System.Runtime.Remoting.ObjRef CreateObjRef(type requestedType) Dispose Method void Dispose(), void IDisposable.Dispose() Equals Method bool Equals(System.Object obj) ExecuteCommand Method void ExecuteCommand(int command) GetHashCode Method int GetHashCode() GetLifetimeService Method System.Object GetLifetimeService() GetType Method type GetType() InitializeLifetimeService Method System.Object InitializeLifetimeService() Pause Method void Pause() Refresh Method void Refresh() Start Method void Start(), void Start(string[] args) Stop Method void Stop() WaitForStatus Method void WaitForStatus(System.ServiceProcess.ServiceControllerStatus desiredStatus), void WaitForStatus(System.ServiceProc...CanPauseAndContinue Property bool CanPauseAndContinue {get;} CanShutdown Property bool CanShutdown {get;} CanStop Property bool CanStop {get;} Container Property System.ComponentModel.IContainer Container {get;} DependentServices Property System.ServiceProcess.ServiceController[] DependentServices {get;} DisplayName Property string DisplayName {get;set;} MachineName Property string MachineName {get;set;} ServiceHandle Property System.Runtime.InteropServices.SafeHandle ServiceHandle {get;} ServiceName Property string ServiceName {get;set;} ServicesDependedOn Property System.ServiceProcess.ServiceController[] ServicesDependedOn {get;} ServiceType Property System.ServiceProcess.ServiceType ServiceType {get;} Site Property System.ComponentModel.ISite Site {get;set;} StartType Property System.ServiceProcess.ServiceStartMode StartType {get;} Status Property System.ServiceProcess.ServiceControllerStatus Status {get;} ToString ScriptMethod System.Object ToString();
根据上面的结果,我们可以:
PS C:\Users\Administrator> (Get-Service -Name Spooler).StartTypeAutomaticPS C:\Users\Administrator> (Get-Service -Name Spooler).StatusRunningPS C:\Users\Administrator> (Get-Service -Name Spooler).CanStopTruePS C:\Users\Administrator> (Get-Service -Name Spooler).Stop()PS C:\Users\Administrator> (Get-Service -Name Spooler).StatusStopped
Get-Date
Get-Date
PS C:\Users\Administrator> Get-Date2022年6月6日 23:26:17PS C:\Users\Administrator> Get-Date -Format yyyyMMdd20220606PS C:\Users\Administrator> (Get-Date).Year2022PS C:\Users\Administrator> (Get-Date).Month6PS C:\Users\Administrator> (Get-Date).Day6PS C:\Users\Administrator> (Get-Date).AddDays(6)2022年6月12日 23:27:19
Get-Date | Ge-Member
PS C:\Users\Administrator> Get-Date | Get-Member TypeName:System.DateTimeName MemberType Definition ---- ---------- ---------- Add Method datetime Add(timespan value) AddDays Method datetime AddDays(double value) AddHours Method datetime AddHours(double value) AddMilliseconds Method datetime AddMilliseconds(double value) AddMinutes Method datetime AddMinutes(double value) AddMonths Method datetime AddMonths(int months) AddSeconds Method datetime AddSeconds(double value) AddTicks Method datetime AddTicks(long value) AddYears Method datetime AddYears(int value) CompareTo Method int CompareTo(System.Object value), int CompareTo(datetime value), int IComparable.CompareTo(System.Object obj), int IComp...Equals Method bool Equals(System.Object value), bool Equals(datetime value), bool IEquatable[datetime].Equals(datetime other) GetDateTimeFormats Method string[] GetDateTimeFormats(), string[] GetDateTimeFormats(System.IFormatProvider provider), string[] GetDateTimeFormats(c...GetHashCode Method int GetHashCode() GetObjectData Method void ISerializable.GetObjectData(System.Runtime.Serialization.SerializationInfo info, System.Runtime.Serialization.Streami...GetType Method type GetType() GetTypeCode Method System.TypeCode GetTypeCode(), System.TypeCode IConvertible.GetTypeCode() IsDaylightSavingTime Method bool IsDaylightSavingTime() Subtract Method timespan Subtract(datetime value), datetime Subtract(timespan value) ToBinary Method long ToBinary() ToBoolean Method bool IConvertible.ToBoolean(System.IFormatProvider provider) ToByte Method byte IConvertible.ToByte(System.IFormatProvider provider) ToChar Method char IConvertible.ToChar(System.IFormatProvider provider) ToDateTime Method datetime IConvertible.ToDateTime(System.IFormatProvider provider) ToDecimal Method decimal IConvertible.ToDecimal(System.IFormatProvider provider) ToDouble Method double IConvertible.ToDouble(System.IFormatProvider provider) ToFileTime Method long ToFileTime() ToFileTimeUtc Method long ToFileTimeUtc() ToInt16 Method int16 IConvertible.ToInt16(System.IFormatProvider provider) ToInt32 Method int IConvertible.ToInt32(System.IFormatProvider provider) ToInt64 Method long IConvertible.ToInt64(System.IFormatProvider provider) ToLocalTime Method datetime ToLocalTime() ToLongDateString Method string ToLongDateString() ToLongTimeString Method string ToLongTimeString() ToOADate Method double ToOADate() ToSByte Method sbyte IConvertible.ToSByte(System.IFormatProvider provider) ToShortDateString Method string ToShortDateString() ToShortTimeString Method string ToShortTimeString() ToSingle Method float IConvertible.ToSingle(System.IFormatProvider provider) ToString Method string ToString(), string ToString(string format), string ToString(System.IFormatProvider provider), string ToString(strin...ToType Method System.Object IConvertible.ToType(type conversionType, System.IFormatProvider provider) ToUInt16 Method uint16 IConvertible.ToUInt16(System.IFormatProvider provider) ToUInt32 Method uint32 IConvertible.ToUInt32(System.IFormatProvider provider) ToUInt64 Method uint64 IConvertible.ToUInt64(System.IFormatProvider provider) ToUniversalTime Method datetime ToUniversalTime() DisplayHint NoteProperty DisplayHintType DisplayHint=DateTime Date Property datetime Date {get;} Day Property int Day {get;} DayOfWeek Property System.DayOfWeek DayOfWeek {get;} DayOfYear Property int DayOfYear {get;} Hour Property int Hour {get;} Kind Property System.DateTimeKind Kind {get;} Millisecond Property int Millisecond {get;} Minute Property int Minute {get;} Month Property int Month {get;} Second Property int Second {get;} Ticks Property long Ticks {get;} TimeOfDay Property timespan TimeOfDay {get;} Year Property int Year {get;} DateTime ScriptProperty System.Object DateTime {get=if ((& { Set-StrictMode -Version 1; $this.DisplayHint }) -ieq "Date")...
Get-WimObject
Get-WmiObject
# BIOS信息PS C:\Users\Administrator> Get-WmiObject -Class Win32_BIOSSMBIOSBIOSVersion : F5Manufacturer : American Megatrends Inc.Name : F5SerialNumber : To be filled by O.E.M.Version : ALASKA - 1072009# 逻辑磁盘信息PS C:\Users\Administrator> Get-WmiObject -Class Win32_LogicaldiskDeviceID : C:DriveType : 3ProviderName : FreeSpace : 29718904832Size : 239410868224VolumeName : DeviceID : D:DriveType : 3ProviderName : FreeSpace : 269805010944Size : 1000202039296VolumeName : Local Disk
Get-CimInstance -ClassName Win32_BIOS(支持Tab命令补全)Get-CimInstance -ClassName Win32_Logicaldisk(支持Tab命令补全
变量,数组,哈希表
变量
PS C:\Users\Administrator> $a = 1PS C:\Users\Administrator> $b = 2PS C:\Users\Administrator> $c = $a + $bPS C:\Users\Administrator> $c3PS C:\Users\Administrator> $c -is [int]TruePS C:\Users\Administrator> $c -is [string]FalsePS C:\Users\Administrator> $d = "Hello World"PS C:\Users\Administrator> Write-Host "$d is $d"Hello World is Hello WorldPS C:\Users\Administrator> Write-Host "`$d is $d"$d is Hello World
Get-Help -Name about_Variables
数组
PS C:\Users\Administrator> $City = @("Beijing", "Shanghai")PS C:\Users\Administrator> $City += "Shenzhen"PS C:\Users\Administrator> $CityBeijingShanghaiShenzhenPS C:\Users\Administrator> $City -is [array]TruePS C:\Users\Administrator> $City[0]BeijingPS C:\Users\Administrator> $City[1]ShanghaiPS C:\Users\Administrator> $City[2]ShenzhenPS C:\Users\Administrator> $City[-1]Shenzhen
哈希表
PS C:\Users\Administrator> $User = @{Name = "Zhao Yun"; Department = "IT"; City="Beijing"}PS C:\Users\Administrator> $UserName Value ---- ----- Department IT Name Zhao Yun City Beijing PS C:\Users\Administrator> $User.CityBeijingPS C:\Users\Administrator> $User.City = "Shanghai"PS C:\Users\Administrator> $User.CityShanghaiPS C:\Users\Administrator> $User.Add("Title", "Senior IT Engineer")PS C:\Users\Administrator> $UserName Value ---- ----- Title Senior IT Engineer Department IT Name Zhao Yun City Shanghai
Get-Help -Name about_Hash_Tables
PowerShell操作符
PowerShell比较操作符
PS C:\Users\Administrator> 8 -eq 8TruePS C:\Users\Administrator> 8 -gt 7TruePS C:\Users\Administrator> "Hello" -like "He*"TruePS C:\Users\Administrator> "Hello" -match "hello"TruePS C:\Users\Administrator> "Hello" -cmatch "hello"FalsePS C:\Users\Administrator> 1,2,3 -contains 1TruePS C:\Users\Administrator> 1,2,3 -contains 6False
Get-Help -Name about_Comparison_Operators
PowerShell逻辑操作符
PS C:\Users\Administrator> $true -and $trueTruePS C:\Users\Administrator> $true -and $falseFalsePS C:\Users\Administrator> $true -or $trueTruePS C:\Users\Administrator> $true -or $falseTruePS C:\Users\Administrator> $true -xor $trueFalsePS C:\Users\Administrator> $true -xor $falseTruePS C:\Users\Administrator> -not $trueFalsePS C:\Users\Administrator> -not $falseTrue
Get-Help -Name about_Logical_Operators
循环和判断
For
# 计算1+2+3+...+100的和$Sum = 0For ($i = 1; $i -le 100; $i++) {$Sum += $i;}Write-Host "`$Sum is $Sum"
Get-Help -Name about_For
Foreach
# 计算1+2+3+...+100的和$Sum = 01..100 | foreach {$Sum += $_}Write-Host "`$Sum is $Sum"# 获取Servers.txt里的服务器Spooler服务状态$Servers = Get-Content -Path "C:\Servers.txt"Foreach ($Server in $Servers) {Get-Service -Name Spooler -ComputerName $Server}
Get-Help -Name about_Foreach
If
For ($i = 1; $i -le 10; $i++) {if ($i % 2) {Write-Host "$i is odd"}else {Write-Host "$i is even"}}
Get-Help -Name about_If
导入,导出数据
TXT文本数据
"BJSRV01" | Out-File -FilePath "C:\Servers.txt"Get-Content -Path "C:\Servers.txt"Write-Host "Appending a new line""BJSRV02" | Out-File -FilePath "C:\Servers.txt" -AppendGet-Content -Path "C:\Servers.txt"
CSV数据
Import-Csv
PS C:\Users\Administrator> Import-Csv -Path "C:\ITusers.csv"SamAccountName Name Department-------------- ---- ----------Demo.User01 User01 Demo IT Demo.User02 User02 Demo IT Demo.User03 User03 Demo IT PS C:\Users\Administrator> $Users = Import-Csv -Path "C:\ITusers.csv"PS C:\Users\Administrator> $Users -is [array]TruePS C:\Users\Administrator> $Users[0]SamAccountName Name Department-------------- ---- ----------Demo.User01 User01 Demo IT PS C:\Users\Administrator> $Users.SamAccountNameDemo.User01Demo.User02Demo.User03
Export-Csv
PS C:\Users\Administrator> Get-ADUser -Filter {Department -eq "IT"} -Properties * | Select-Object -Property SamAccountName, Name, DepartmentSamAccountName Name Department-------------- ---- ----------Demo.User01 User01 Demo IT Demo.User02 User02 Demo IT Demo.User03 User03 Demo IT PS C:\Users\Administrator> Get-ADUser -Filter {Department -eq "IT"} -Properties * | Select-Object -Property SamAccountName, Name, Department | Export-Csv -Path "C:\ITusers.csv" -Encoding UTF8
-Encoding UTF8可以解决中文乱码问题
脚本
执行策略
PS C:\Users\Administrator> Get-ExecutionPolicyRestrictedPS C:\Users\Administrator> Set-ExecutionPolicy -ExecutionPolicy RemoteSignedPS C:\Users\Administrator> Get-ExecutionPolicyRemoteSigned
Get-Help -Name about_Execution_Policies
Get-Mylog.ps1
<#.SYNOPSIS获取系统日志.DESCRIPTION获取最近的100条系统,应用日志,并以html形式呈现#>$Date = Get-Date -Format yyyyMMdd$LogFile = $env:TEMP + "\Log" + $Date + ".html"$Css = @""@$SysLog = Get-EventLog -LogName System -Newest 100 | Select-Object MachineName,TimeGenerated,EntryType,EventID,Message,Source$AppLog = Get-EventLog -LogName Application -Newest 100 | Select-Object MachineName,TimeGenerated,EntryType,EventID,Message,Source$SysLog | ConvertTo-Html -PreContent "
版权声明:本文内容由网络用户投稿,版权归原作者所有,本站不拥有其著作权,亦不承担相应法律责任。如果您发现本站中有涉嫌抄袭或描述失实的内容,请联系我们jiasou666@gmail.com 处理,核实后本网站将在24小时内删除侵权内容。
发表评论
暂时没有评论,来抢沙发吧~