5.Using PowerShell Scripts and 5.Using WMI

简介: Get-ChildItem c:/fso | Where-Object {_.Length -gt 1000} | Sort-Object -Property nameforeach (_.Length -gt 1000} | Sort-Object -Property nameforeach (i in args) {Get-ChildItemargs) {Get-ChildItemi | Where-Object {$_.

Get-ChildItem c:/fso | Where-Object {_.Length -gt 1000} | Sort-Object -Property name foreach (_.Length -gt 1000} | Sort-Object -Property name foreach (i in args) {Get-ChildItemargs) {Get-ChildItemi | Where-Object {$_.length -gt 1000} | Sort-Object -property name}

$args = "localhost","loopback","127.0.0.1"

foreach (iinargs)
   {strFile="c:/mytest/"+i +"Processes.txt"
    Write-Host "Testing" i"pleasewait...";GetWmiObjectcomputernamei -class win32_process |
    Select-Object name, processID, Priority, ThreadCount, PageFaults, PageFileUsage |
    Where-Object {!_.processID -eq 0} | Sort-Object -property name |     Format-Table | Out-FilestrFile}

$args = "localhost"

foreach (iinargs)
   {Write-Host "Connecting to" i"pleasewait...";GetWmiObjectcomputernamei -class win32_UserAccount |
    Select-Object Name, Disabled, PasswordRequired, SID, SIDType |
    Where-Object {$_.PasswordRequired -eq 0} |
    Sort-Object -property name | Write-Host}

Get-ExecutionPolicy
Set-ExecutionPolicy unrestricted
###RetrieveAndSortServiceState.ps1

$args = "localhost","loopback"

   foreach (iinargs)
      {Write-Host "Testing" i"..."GetWmiObjectcomputerargs -class win32_service |
         Select-Object -property name, state, startmode, startname |
         Sort-Object -property startmode, state, name |
         Format-Table *}
Open the Run dialog box (Start | Run, or the Windows Flag key + R, or Ctrl + Esc then R).
Powershell  -noexit C:/mytest/RetrieveAndSortServiceState.ps1


ContainsthefirsttokenofthelastlineinputintotheshellContainsthelasttokenofthelastlineinputintotheshell_
 The current pipeline object; used in script blocks, filters, Where-Object, ForEach-Object, and Switch
 
?Containsthesuccess/failstatusofthelaststatementArgs
 Used in creating functions requiring parameters
 
ErrorIfanerroroccurred,theerrorobjectissavedintheerror variable.
 
ExecutionContextTheexecutionobjectsavailabletocmdletsforeach
 Refers to the enumerator in a foreach loop
 
HOMETheusershomedirectory;settoInput
 Input is piped to a function or code block.
 
MatchAhashtableconsistingofitemsfoundbythematchoperatorMyInvocation
 Information about the currently executing script or command-line
 
PSHomeThedirectorywherePSisinstalledHost
 Information about the currently executing host
 
LastExitCodeTheexitcodeofthelastnativeapplicationtoruntrue
 Boolean TRUE
 
falseBooleanFALSEnull
 A null object
 
thisIntheTypes.ps1xmlfileandsomescriptblockinstances,thisrepresentsthecurrentobjectOFS
 Output Field Separator used when converting an array to a string
 
ShellIDTheidentifierfortheshell.ThisvalueisusedbytheshelltodeterminetheExecutionPolicyandwhatprofilesarerunatStartupStackTrace
 Contains detailed stack trace information about the last error
 
strUserPathPathtoregistrysubkey"Software/Microsoft/Windows/CurrentVersion/Explorer"strUserName
 Registry value "Logon User Name"
 
strPathPathtoregistrysubkey"/VolatileEnvironment"strName
 An array of Registry values: "LOGONSERVER", "HOMEPATH", "APPDATA", "HOMEDRIVE"
 
iHoldsasingleregistryvaluenamefromthestrName array of registry values; igetsassignedthevaluebyusingtheForEachalias.strUserPath = "/Software/Microsoft/Windows/CurrentVersion/" `
               + "Explorer"
strUserName="LogonUserName"strPath = "/Volatile Environment"
$strName = "LOGONSERVER","HOMEPATH", "APPDATA","HOMEDRIVE"

Set-Location HKCU:/
   Get-ItemProperty -path strUserPathnamestrUserName |
      Format-List strUserNameforeach(i in strName)    {Get-ItemProperty -pathstrPath -name i|FormatListi}


a="thisisthebeginning"b = 22
c=a + bc

c=a + bc
b="thisisanumber"c = a+b
c[int]b = 5
c=a + bc

b = "this is a string" #Cannot convert value "this is a number" to type "System.Int32". #Error: "Input string was not in a correct format." #At line:1 char:3 #+b  <<<< = "this is a string"

Data Type Aliases
 Open table as spreadsheet  Alias
 Type
 
[int]
 32-bit signed integer
 
[long]
 64-bit signed integer
 
[string]
 Fixed-length string of Unicode characters
 
[char]
 A Unicode 16-bit character
 
[bool]
 True/false value
 
[byte]
 An 8-bit unsigned integer
 
[double]
 Double-precision 64-bit floating point number
 
[decimal]
 An 128-bit decimal value
 
[single]
 Single-precision 32-bit floating point number
 
[array]
 An array of values
 
[xml]
 Xml objects
 
[hashtable]
 A hashtable object (similar to a dictionary object)
 
$aryComputers = "loopback", "localhost"
Set-Variable -name intDriveType -value 3 -option constant

foreach (strComputerinaryComputers)

   {"Hard drives on: " + strComputerGetWmiObjectclasswin32logicaldiskcomputernamestrComputer|
      Where {.drivetypeeqintDriveType}}

Get-Process |
   ForEach-Object `
      {if (.cpult100)WriteHost$.name,$.cpuforegroundcolorblueelseif(_.cpu -gt 100)
            {Write-Host .name,_.cpu -foregroundcolor red}}

 

Get-Service
ForEach-Object
ForEach-Object `
if (.Statuseq"stopped")WriteHost$.name,$.Statusforegroundcolorredseparator",nt"elseif(_.Status -eq "running")
{Write-Host .name,_.Status -foregroundcolor green -separator ",`n`t"}}


for (a=1;a -le 3 ; $a++) {"hello"}

[int]intPing=10[string]intNetwork = "127.0.0."

for (i=1;i -le intPing;i++)
{
strQuery="selectfromwin32pingstatuswhereaddress="+intNetwork + i+""wmi = get-wmiobject -query strQuery"PingingintNetworki..."if(wmi.statuscode -eq 0)
      {"success"}
      else
         {"error: " + $wmi.statuscode + " occurred"}
}


$dtmTime = get-date -h 04 -mi 23 -s 00

do {dtmCurrent=GetDateDisplayHinttime"Thecurrenttimeis"+dtmCurrent
"counting to " + dtmtime start-sleep -s 2 } while (dtmCurrent -lt $dtmTime)
"time reached à"


Comparison Operators
 Open table as spreadsheet  Operator
 Description
 
-eq
 equals
 
-ne
 not equal
 
-gt
 greater than
 
-ge
 greater than or equal to
 
-lt
 less than
 
-le
 less than or equal to
 
-like
 wild card comparison
 
-notlike
 wild card comparison
 
-match
 regular expression comparison
 
-notmatch
 regular expression comparison
 
i=10;do$i;"iis$i"until(i -eq 0)


strTxtFile="c:/mytest/loopbackprocesses.txt"i = 0
mytext=GetContentstrTxtFile
do {
   mytext[i]
   i ++ } until (i -eq $mytext.length)


i=0;do$i++;"iisequalto$i"until(i -eq 0)

i=0;do$i++;"iisequalto$i"until(i -eq 0)
i=0;do$i++;"iisequalto$i"while(i -eq 0)

WIN32_Processor Processor Values
 
0
 x86
 
1
 MIPS
 
2
 Alpha
 
3
 PowerPC
 
6
 Intel Itanium
 
9
 x64
 
wmi=getwmiObjectwin32processorif(wmi.Architecture -eq 0)
   {"This is an x86 computer"}
   elseif(wmi.architectureeq1)"ThisisanMIPScomputer"elseif(wmi.architecture -eq 2)
      {"This is an Alapha computer"}
   elseif(wmi.architectureeq3)"ThisisanPowerPCcomputer"elseif(wmi.architecture -eq 6)
      {"This is an IPF computer"}
   elseif(wmi.architectureeq9)"Thisisanx64computer"else$wmi.architecture+"isnotacputypeIamfamiliarwith""Currentclockspeedis:"+wmi.CurrentClockSpeed + " MHZ"
   "Max clockspeed is : " + wmi.MaxClockSpeed+"MHZ""Currentloadpercentageis:"+wmi.LoadPercentage + " Percent"
   "The L2 cache size is: " + $wmi.L2CacheSize + " KB"


a=5;switch(a) { 4{"four detected"} 5{"five detected"} }

wmi=getwmiobjectwin32computersystem"computer"+wmi.name + " is: "
switch ($wmi.domainrole)
   {
   0 {"`t Stand alone workstation"}
   1 {"`t Member workstation"}
   2 {"`t Stand alone server"}
   3 {"`t Member server"}
   4 {"`t Back up domain controller"}
   5 {"`t Primary domain controller"}
   default {"`t The role can not be determined"}
   }

intFolders=10intPad
i=1NewVariableNamestrPrefixValue"testFolder"Optionconstantdoif($ilt10)$intPad=0newitempathc:/mytestname$strPrefix$intPad$itypedirectoryelsenewitempathc:/mytestname$strPrefix$itypedirectory$i++until(i -eq $intFolders+1)

{intPad=0removeitempathc:/mytestnamestrPrefixintPadi -type directory}
   else
      {remove-item -path c:/mytest -name strPrefixi -type directory}

{intPad=0removeitempathc:/mytest/strPrefixintPadi -type directory}
   else
      {remove-item -path c:/mytest/strPrefixi -type directory}

{intPad=0Removeitempathc:/mytest/strPrefixintPadi}
   else
    {Remove-item -path c:/mytest/strPrefixi}

wmi = Get-WmiObject -class __Namespace -namespace root    "Listing namespaces on " +wmi[0].__server +
   " please wait a second "
for (i=0;i -le wmi.length;i++)
   {if (iltwmi.length)
      {Write-Host -noNewLine "."
      Start-Sleep -m 75}
   else
      {Write-Host "."}
   }
wmi|FormatListnameWriteHostforegroundColorgreen"Thereare"wmi.length `
   "namespaces on this machine `n"


wmiNS = "root/cimV2" Get-WmiObject -class __Provider -namespacewmiNS |
   Sort-Object -property Name |
   Format-List name

Variable Name
 Variable Use
 
strComputerNameofcomputertorunthescriptonwmiNS
 WMI namespace containing WMI class used in the script
 
strUsrUsernameforconnectiontoremotecomputerstrPWD
 Password of user connecting to remote machine
 
strLoclLanguagetobeusedwithWMIconnectionstrAuth
 Credential authority, for example, Kerberos, NTLM
 
iFlagSecurityflag;usedtospecifytimeoutvaluestrComputer = "."
wmiNS="/root/cimv2"strUsr ="" #Blank for current security. Domain/Username
strPWD = "" #Blank for current security.strLocl = "MS_409" #US English. Can leave blank for current language
strAuth = "" #if specify domain in strUsr this must be blankiFlag = "0" #only two values allowed: 0 and 128.
objLocator=NewObjectcomobject"WbemScripting.SWbemLocator"objWMIService = objLocator.ConnectServer(strComputer,
    wmiNS,strUsr, strPWD,strLocl, strAuth,iFLag)

colItems=objWMIService.subClassesOf()
   Write-Host "There are: " colItems.count"classesinwmiNS"
   foreach (objItemIncolItems)
           {
             $objItem.path_.class
           }

strComputer="."wmiNS = "/root/cimv2"
strUsr ="" #Blank for current security. Domain/UsernamestrPWD = "" #Blank for current security.
strLocl = "MS_409" #US English. Can leave blank for current languagestrAuth = "" #if specify domain in strUsr this must be blank
$iFlag = "0" #only two values allowed: 0 and 128.

objLocator = New-Object -comobject "WbemScripting.SWbemLocator" #objWMIService = objLocator.ConnectServer(strComputer, `
wmiNS,strUsr, strPWD,strLocl, strAuth,iFLag)
#
# colItems=objWMIService.subClassesOf()
# Write-Host "There are: " colItems.count"classesinwmiNS"
#    foreach (objItemIncolItems)
#            {
#              $objItem.path_.class
#            }

objLocator|GetMemberobjWMIService = objLocator.ConnectServer(strComputer, `
     wmiNS,strUsr, strPWD,strLocl, strAuth,iFLag)
objWMIService|GetMembercolItems = objWMIService.subClassesOf()colItems | Get-Member

wmiClass="WIN32Service"objLocator = New-Object -comobject "WbemScripting.SWbemLocator"
#objLocator|GetMemberobjWMIService = objLocator.ConnectServer(strComputer,
     wmiNS,strUsr, strPWD,strLocl, strAuth,iFLag)
#objWMIService|GetMemberobjItem = objWMIService.Get(wmiClass)
$objItem | Get-Member

wmiQuery="SelectfromWin32Desktop"wmiNS = "root/cimv2"
strComputer="."objWMIService = Get-WmiObject -computer strComputernamespacewmiNS -query wmiQueryobjWMIService | Format-List *

objWMIService|FormatListpropertynameobjWMIService | Format-List -property name, screensaverexecutable
objWMIService|FormatListpropertyname,screensaverexecutable,screensaverSecureobjWMIService | Format-List -property name, screen*

Get-Service
Get-Service |sort -property status
Get-Service |sort -property name
Get-Service |sort status, name
Get-Service | where {_.DisplayName -match "server"} Get-Service | where {$_.name -eq "alerter"}a=Get-Service | where {_.name -eq "alerter"}a | gm
a.statusStopServiceInputObjecta
Start-Service -InputObject aa.status

wmiQuery="Selectfromwin32Printer"objWMIServices | Format-List name
objWMIServices|FormatListname,portnameobjWMIServices | Format-List name, portname, capabilitydescriptions
$objWMIServices | GM

目录
打赏
0
0
0
0
20
分享
相关文章
|
5月前
|
Powershell 重新排列去重 Windows环境变量
【9月更文挑战第13天】本文介绍如何使用PowerShell对Windows环境变量进行重新排列和去重。首先通过`$env:`访问环境变量,接着使用`-split`命令分割路径,再利用`Select-Object -Unique`去除重复项。之后可根据需要对路径进行排序,最后将处理后的路径组合并更新环境变量。注意修改环境变量前应备份重要数据并了解潜在影响。
194 10
PowerShell 脚本编写 :自动化Windows 开发工作流程
PowerShell 脚本编写 :自动化Windows 开发工作流程
197 0
|
9月前
|
windows可以安装Ubuntu,ubuntu上也可以安装Powershell
powerhsell除了可以在windows上使用外,还可以在Ubuntu上部署开发环境。下面介绍Ubuntu上安装powershell的方法。
263 0
windows中cmd和PowerShell批处理命令
之前在 Git 批量删除本地分支,有用到 Linux 或 MacOS 下的批处理命令,这个命令中的 grep、xargs 本身是 Shell script,在 windows 中的 cmd 和 PowerShell 中是不能用的
147 0
使用PowerShell获取Windows当前锁屏壁纸
使用PowerShell获取Windows当前锁屏壁纸 如果原始图片丢了,用这段代码就可以提取当前锁屏壁纸了!
217 0
利用powershell进行windows日志分析
0x00 前言   Windows 中提供了 2 个分析事件日志的 PowerShell cmdlet:一个是Get-WinEvent,超级强大,但使用起来比较麻烦;另一个是Get-EventLog,使得起来相当简单,可以实时筛选,接下来,我们利用PowerShell 来自动筛选 Windows 事件日志。
2555 0
AI助理

你好,我是AI助理

可以解答问题、推荐解决方案等