Powershell example 1
简介:
Restart-Computers.ps1
# Define input parameters
param (
[string] filename=(throw "Filename is required!")
)
...
Restart-Computers.ps1
# Define input parameters
param (
[string] $filename = $(throw "Filename is required!")
)
Write-Host "Reading computer names from $filename"
# Read file
$computers = get-content $filename
foreach ($computer in $computers) {
# Connect to WMI
$wmi = get-wmiobject -class "Win32_OperatingSystem" `
-namespace "root/cimv2" -computer $computer
# Restart computer
foreach ($item in $wmi) {
$wmi.reboot()
write-host "Restarted " + $computer
}
}
ScopeTest.ps1
write-host "1 (var): $var"
$var = "SCRIPT"
$global:var = "GLOBAL"
write-host "2a (var): $var"
write-host "2b (global): $global:var"
function foo {
write-host "3a (var): $var"
write-host "3b (global): $global:var"
$var = "LOCAL"
$script:var = "SCRIPT!"
write-host "4a (var): $var"
write-host "4b (global): $global:var"
write-host "4c (script): $script:var"
}
foo
write-host "5a (var): $var"
write-host "5b (global): $global:var"
write-host "5c (script): $script:var"
NegativeMatchingTest.ps1
$var="The-quick-brown-fox-jumped-over-the-lazy-dog."
$var2="The quick brown fox jumped over the lazy dog."
$regex=[regex]"/s{1}"
$var
if (($regex.IsMatch($var)) -eq "False")
{
write-host "Expression has spaces"
}
else
{
write-host "Expression has no spaces" }
$var2
if (($regex.IsMatch($var2)) -eq "False")
{
write-host "Expression has spaces"
}
else
{
write-host "Expression has no spaces" }
 |
ForEachFruit.ps1
#ForEachFruit.ps1
$var=("apple","banana","pineapple","orange")
foreach ($fruit in $var) {
$i++ #this is a counter that is incremented by one each time through
write-host "Adding" $fruit
}
write-host "Added" $i "pieces of fruit"
ForEachFile.ps1
#ForEachFile.ps1
set-location "C:/"
$sum=0
foreach ($file in get-childitem) {
#$file.GetType()
if (($file.GetType()).Name -eq "FileInfo") {
write-host $file.fullname `t $file.length "bytes"
$sum=$sum+$file.length
$i++
}
}
write-host "Counted" $i "file for a total of" $sum "bytes."
ForEachSvc.ps1
#ForEachSvc.ps1
get-service | foreach {
if ($_.status -eq "Running") {
write-host $_.displayname "("$_.status")" -foregroundcolor "Green"
write-host `t "Service Type="$_.servicetype -foregroundcolor "Green"
}
else
{
write-host $_.displayname "("$_.status")" -foregroundcolor "Red"
}
}
IfTest.ps1
#IfTest.ps1
$i=11
if ($i-le 10) {
"Less than 10"
}
else
{
"Greater than 10"
}
IfElseIfTest.ps1
#IfElseIfTest.ps1
$i=45
if ($i -le 10) {
write-host "Less than 25"
}
elseif ($i -le 50)
{
write-host "Less than 50"
}
else
{
write-host "Greater than 50"
}
IfElseIfTest.ps1
#IfElseIfTest.ps1
$i=45
if ($i -le 10) {
write-host "Less than 25"
}
elseif ($i -le 50)
{
write-host "Less than 50"
}
else
{
write-host "Greater than 50"
}
|