5.Using PowerShell Scripts and 5.Using WMI

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

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

foreach ($i in $args)
   {$strFile = "c:/mytest/"+ $i +"Processes.txt"
    Write-Host "Testing" $i "please wait ...";
    Get-WmiObject -computername $i -class win32_process |
    Select-Object name, processID, Priority, ThreadCount, PageFaults, PageFileUsage |
    Where-Object {!$_.processID -eq 0} | Sort-Object -property name |
    Format-Table | Out-File $strFile}

$args = "localhost"

foreach ($i in $args)
   {Write-Host "Connecting to" $i "please wait ...";
    Get-WmiObject -computername $i -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 ($i in $args)
      {Write-Host "Testing" $i "..."
         Get-WmiObject -computer $args -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

$^
 Contains the first token of the last line input into the shell
 
$$
 Contains the last token of the last line input into the shell
 
$_
 The current pipeline object; used in script blocks, filters, Where-Object, ForEach-Object, and Switch
 
$?
 Contains the success/fail status of the last statement
 
$Args
 Used in creating functions requiring parameters
 
$Error
 If an error occurred, the error object is saved in the $error variable.
 
$ExecutionContext
 The execution objects available to cmdlets
 
$foreach
 Refers to the enumerator in a foreach loop
 
$HOME
 The user's home directory; set to %HOMEDRIVE%/%HOMEPATH%
 
$Input
 Input is piped to a function or code block.
 
$Match
 A hash table consisting of items found by the -match operator
 
$MyInvocation
 Information about the currently executing script or command-line
 
$PSHome
 The directory where PS is installed
 
$Host
 Information about the currently executing host
 
$LastExitCode
 The exit code of the last native application to run
 
$true
 Boolean TRUE
 
$false
 Boolean FALSE
 
$null
 A null object
 
$this
 In the Types.ps1xml file and some script block instances, this represents the current object
 
$OFS
 Output Field Separator used when converting an array to a string
 
$ShellID
 The identifier for the shell. This value is used by the shell to determine the ExecutionPolicy and what profiles are run at Startup
 
$StackTrace
 Contains detailed stack trace information about the last error
 
$strUserPath
 Path to registry subkey "Software/Microsoft/Windows/CurrentVersion/Explorer"
 
$strUserName
 Registry value "Logon User Name"
 
$strPath
 Path to registry subkey "/Volatile Environment"
 
$strName
 An array of Registry values: "LOGONSERVER", "HOMEPATH", "APPDATA", "HOMEDRIVE"
 
$i
 Holds a single registry value name from the $strName array of registry values; $i gets assigned the value by using the ForEach alias.
 
$strUserPath = "/Software/Microsoft/Windows/CurrentVersion/" `
               + "Explorer"
$strUserName = "Logon User Name"
$strPath = "/Volatile Environment"
$strName = "LOGONSERVER","HOMEPATH", "APPDATA","HOMEDRIVE"

Set-Location HKCU:/
   Get-ItemProperty -path $strUserPath -name $strUserName |
      Format-List $strUserName
foreach ($i in $strName)
   {Get-ItemProperty -path $strPath -name $i |
      Format-List $i}

$a = "this is the beginning"
$b = 22
$c = $a + $b
$c

$c = $a + $b
$c
$b = "this is a number"
$c = $a + $b
$c
[int]$b = 5
$c = $a + $b
$c

$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 ($strComputer in $aryComputers)

   {"Hard drives on: " + $strComputer
   Get-WmiObject -class win32_logicaldisk -computername $strComputer|
      Where {$_.drivetype -eq $intDriveType}}

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

 

Get-Service
ForEach-Object
ForEach-Object `
if ($_.Status -eq "stopped")
{Write-Host $_.name, $_.Status -foregroundcolor red -separator ",`n`t"}
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 = "select * from win32_pingstatus where address = '" + $intNetwork + $i + "'"
   $wmi = get-wmiobject -query $strQuery
   "Pinging $intNetwork$i ... "
   if ($wmi.statuscode -eq 0)
      {"success"}
      else
         {"error: " + $wmi.statuscode + " occurred"}
}

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

do {$dtmCurrent = Get-Date -DisplayHint time
"The current time is " + $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 --; "i is $i"} until ($i -eq 0)

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

$i=0;
do {$i++;
"i is equal to $i"}
until ($i -eq 0)

$i=0;do {$i++; "i is equal to $i"} until ($i -eq 0)
$i=0;do {$i++; "i is equal to $i"} while ($i -eq 0)

WIN32_Processor Processor Values
 
0
 x86
 
1
 MIPS
 
2
 Alpha
 
3
 PowerPC
 
6
 Intel Itanium
 
9
 x64
 
$wmi = get-wmiObject win32_processor
if ($wmi.Architecture -eq 0)
   {"This is an x86 computer"}
   elseif($wmi.architecture -eq 1)
      {"This is an MIPS computer"}
   elseif($wmi.architecture -eq 2)
      {"This is an Alapha computer"}
   elseif($wmi.architecture -eq 3)
      {"This is an PowerPC computer"}
   elseif($wmi.architecture -eq 6)
      {"This is an IPF computer"}
   elseif($wmi.architecture -eq 9)
      {"This is an x64 computer"}
else
      {$wmi.architecture + " is not a cpu type I am familiar with"}
   "Current clockspeed is : " + $wmi.CurrentClockSpeed + " MHZ"
   "Max clockspeed is : " + $wmi.MaxClockSpeed  + " MHZ"
   "Current load percentage is: " + $wmi.LoadPercentage + " Percent"
   "The L2 cache size is: " + $wmi.L2CacheSize + " KB"

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

$wmi = get-wmiobject win32_computersystem
"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 = 10
$intPad
$i = 1
New-Variable -Name strPrefix -Value "testFolder" -Option constant
do {
if ($i -lt 10)
{$intPad=0
new-item -path c:/mytest -name $strPrefix$intPad$i -type directory}
else
{new-item -path c:/mytest -name $strPrefix$i -type directory}
$i++
}until ($i -eq $intFolders+1)

{$intPad=0
      remove-item -path c:/mytest -name $strPrefix$intPad$i -type directory}
   else
      {remove-item -path c:/mytest -name $strPrefix$i -type directory}

{$intPad=0
      remove-item -path c:/mytest/$strPrefix$intPad$i -type directory}
   else
      {remove-item -path c:/mytest/$strPrefix$i -type directory}

{$intPad=0
     Remove-item -path c:/mytest/$strPrefix$intPad$i}
   else
    {Remove-item -path c:/mytest/$strPrefix$i}

$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 ($i -lt $wmi.length)
      {Write-Host -noNewLine "."
      Start-Sleep -m 75}
   else
      {Write-Host "."}
   }
$wmi | Format-List name
   Write-Host -foregroundColor green "There are" $wmi.length `
   "namespaces on this machine `n"

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

Variable Name
 Variable Use
 
$strComputer
 Name of computer to run the script on
 
$wmiNS
 WMI namespace containing WMI class used in the script
 
$strUsr
 User name for connection to remote computer
 
$strPWD
 Password of user connecting to remote machine
 
$strLocl
 Language to be used with WMI connection
 
$strAuth
 Credential authority, for example, Kerberos, NTLM
 
$iFlag
 Security flag; used to specify timeout value
 
$strComputer = "."
$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 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 " classes in $wmiNS"
   foreach ($objItem In $colItems)
           {
             $objItem.path_.class
           }

$strComputer = "."
$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 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 " classes in $wmiNS"
#    foreach ($objItem In $colItems)
#            {
#              $objItem.path_.class
#            }

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

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

$wmiQuery = "Select * from Win32_Desktop"
$wmiNS = "root/cimv2"
$strComputer = "."
$objWMIService = Get-WmiObject -computer $strComputer -namespace
$wmiNS -query $wmiQuery
$objWMIService | Format-List *

$objWMIService | Format-List -property name
$objWMIService | Format-List -property name, screensaverexecutable
$objWMIService | Format-List -property name, screensaverexecutable,screensaverSecure
$objWMIService | 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.status
Stop-Service -InputObject $a
Start-Service -InputObject $a
$a.status

$wmiQuery = "Select * from win32_Printer"
$objWMIServices | Format-List name
$objWMIServices | Format-List name, portname
$objWMIServices | Format-List name, portname, capabilitydescriptions
$objWMIServices | GM

时间: 2024-08-04 10:50:37

5.Using PowerShell Scripts and 5.Using WMI的相关文章

【探索PowerShell 】【十三】WMI对象

我记得在xp时代,经常使用的工具有一个叫做WMI Administrative Tools,是微软官方提供的用来查看.编辑WMI对象的,只是现在好似不支持新的系统了.但是,在Win7.Server 2008下,这些功能都可以方便的通过PowerShell来完成. 首先,先来认识一下什么是WMI对象: WMI是作为一个基本的数据库存在于Windows系统中的.我们可以连接到WMI服务请求查询其中所包含的信息.WMI包括了系统方方面面的信息,包括: • 机器信息:制造商.型号.序列号等 • BIOS

Powershell小技巧之使用WMI测试服务响应_PowerShell

测试一个服务是否有响应,有一个好办法.首先,使用WMI查询你指定的服务,WMI中可以返回构成它进程的ID. function Test-ServiceResponding($ServiceName) { $service = Get-WmiObject -Class Win32_Service -Filter "Name='$ServiceName'" $processID = $service.processID $process = Get-Process -Id $process

Powershell小技巧之使用WMI查询插上的U盘_PowerShell

如果你想知道当前插在你电脑上的USB设备,WMI能帮助你: Get-WmiObject -Class Win32_PnPEntity | Where-Object { $_.DeviceID -like 'USBSTOR*' } 这将返回所有插上在使用的USBSTOR设备类 如果你使用WMI查询语言(WQL),你甚至可以使用筛选命令: Get-WmiObject -Query 'Select * From Win32_PnPEntity where DeviceID Like "USBSTOR%

Powershell小技巧之使用WMI工具_PowerShell

WMI是一个强大的技术:只需要简单的指定一个WMI类名就能返回它类的所有实例: 复制代码 代码如下: PS> Get-WmiObject -Class Win32_BIOS SMBIOSBIOSVersion : 76CN27WW Manufacturer      : LENOVO Name              : 76CN27WW SerialNumber      : 1006250300406 Version           : LENOVO - 1 你如何知道它有哪些类呢?这

Thoughtworks Techniques

If you are wondering "What comes after agile?," you should look towards continuous delivery. While your development processes may be fully optimized, it still might take your organization weeks or months to get a single change into production. C

java如何获取计算机软件信息?

问题描述 java如何获取计算机软件信息? 比如安装的office2013版本 ,有安装的360安全卫士 等等. 解决方案 读取注册表https://docs.oracle.com/javase/7/docs/api/java/util/prefs/Preferences.html http://xiaohuafyle.iteye.com/blog/1543559 解决方案二: 应该能够调用PowerShell脚本吧,powershell能够方便地操作wmi,获取计算机信息很容易的. 解决方案三

ASP.NET MVC 3 Beta新特性以及.Net开源的趋势----最新译文

NuPack – .NET的开源软件包管理器 NuPack是一个开源的软件包管理器,它使你在项目中能够更加容易的查找.安装和使用.NET 库.它能够和所有的.NET 项目类型很好的一起工作(包括,没有任何限制的,ASP.NET Web Forms和ASP.NET MVC). NuPack 使维护开源项目的开发者(例如, Moq, NHibernate, Ninject, StructureMap, NUnit, Windsor, RhinoMocks, Elmah, 等等) 能够去打包他们的库,

花了一上午,合成的一个粗糙的IT用来了解EXCHANGE运行情况的自动邮件脚本

看着简单,格式不好. 但也让IT能了解EXCHANGE 2010的MAIL DATABASE的空间占用,WHITE SPACE闲置空间情况,每个用户占用的大小. 代码也使用了输出为HTML,发送多个邮件,同时发送多个HTML作EMAIL BODY.因为附近毕竟要打开多次.  原始参考贴及后续操作: http://www.mikepfeiffer.net/2010/03/exchange-2010-database-statistics-with-powershell/ Then you coul

调查显示,越来越多的攻击活动不再依赖恶意软件了

根据CarbonBlack的最新研究报告,各位安全研究专家可要注意了,因为现在越来越多的攻击者在进行恶意活动时并不需要依赖恶意软件了. 根据该公司发表的这篇标题为<2016年非恶意软件攻击和勒索软件正在兴起>的报告,在今年的1月份,大约有3%的网络攻击利用的是目标系统中的应用程序漏洞以及合法进程.但是到11月份时,这种攻击方法的占比数量上升到了13%.报告中指出:"不依赖于恶意软件的黑客攻击活动目前已经到达了一种前所未有的高水平阶段,所以在2017年,安全研究专家们应该更加注意这种类