PowerShell 语法结构

Get-Service -name P*

[int]$a = 2
write-output $a

[string]$b = "string"
write-output $b

#$computername = Read-host "Enter computer name"
#write-output $computername

[datetime]$d="12/25/2014"
write-output $d.DayofWeek

$service = get-service -name bits
$service.name
$service.status
"Service name is $($service.displayname)"

#collection
$services = get-service
$services.count
#loop
$services[1..5]
$services[5..1]


$status =2
switch($status)
{
0 {$status_text = 'OK'}
1 {$status_text = 'good'}
2 {$status_text = 'complete'}
default {$status_text = 'unknown'}
}

write-output $status_text

$service = get-service -name bits
if($service.status -eq "running")
{
"bits is running"
}
else{
"bits is not running"
}

#loop
$i=1
do{
write-output "powershell is awsome"
$i = $i+1
} while ($i -le 0)

$i = 5
while ($i -gt 0)
{
write-output "power shell new"
$i--
}


$services = Get-Service -name b*
ForEach ($service in $services)
{
$service.name  
$service.displayname
}

1..3|ForEach-Object -process {
calc
}

 test2.ps1

Function Verb-Noun{
param(
[parameter(valuefrompipeline = $true)]
[int]$x
)

Begin {$total =0}
Process {$total +=$x}
End { write-Verbose "total = $total"}
}

Function Get-ComputerInfo{
param(
[parameter(
Mandatory=$true,
Valuefrompipeline=$true
)]
[Alias("Host")]
[ValidateSet('ws-ace','lexbuild1')]
[string[]]$ComputerName,
[Switch]$ErrorLog,
[string]$LogFile = 'd:workdirectoryscriptserrorlog.txt'
)

Begin{
if($ErrorLog)
{
"Error Log is turned on"
}
else{
"Error log is turned off"
}
}

Process{
Foreach($c in $ComputerName)
{
$os = Get-Wmiobject -ComputerName $c -Class Win32_OperatingSystem
$Disk = Get-Wmiobject -ComputerName $c -Class Win32_LogicalDisk -filter "DeviceID ='c:'"

$prop =@{
'ComputerName'=$c;
'OS Name'= $os.caption;
'OS build' = $os.buildnumber;
'Free Space' = $Disk.freespace /1gb -as [int]
}

$obj = New-object -typename PSObject -Property $prop
write-output $obj
}
}
End{}
}

run get-computerInfo

原文地址:https://www.cnblogs.com/qixue/p/3685024.html