Windows PowerShell language examples.
# =============================================================================
# Test files or directories for existence
#
# -Path The path to the file or directory to test for existence.
# =============================================================================
if (Test-Path -Path "C:\path\to\file\or\directory") {
Write-Host "File exists."
} else {
Write-Host "File does not exist."
}
# =============================================================================
# Copy one or more files or folders
#
# -Path The source path of the file or directory to copy.
# -Destination The destination path for the copied file or directory.
# -Recurse Include the entire contents of the copied directory to the destination.
# =============================================================================
# To copy source a directory recursively to another directory:
Copy-Item -Path "C:\path\to\source" -Destination "C:\path\to\destination" -Recurse
# To copy only "*.txt" files from source to destination:
Copy-Item C:\path\to\source\*.txt C:\path\to\destination
# =============================================================================
# PowerShell Comparison Operators
#
# Description Operator Example
# ------------ -------- --------------------------
# Greater than -gt 1 -gt 2 (Returns $false)
# Less than -lt 1 -lt 2 (Returns $true)
# Equals -eq 2 -eq 1+1 (Returns $true)
# Not equals -ne 3 -ne 1+1 (Returns $true)
# Greater than or equal to -ge 3 -ge 1+1 (Returns $true)
# Less than or equal to -le 2 -le 1+1 (Returns $true)
#
# http://www.tomsitpro.com/articles/powershell-comparison-operators-conditional-logic,2-850.html
# =============================================================================
# To select processes related to various web browsers:
Get-Process | Where-Object {($_.Name -eq "iexplore") -or ($_.Name -eq "chrome") -or ($_.Name -eq "firefox")}
# =============================================================================
# PowerShell Where-Object
#
# NOTE: The "$_" default variable is used to indicate the current record being
# passed from the pipeline.
#
# http://www.tomsitpro.com/articles/powershell-comparison-operators-conditional-logic,2-850.html
# =============================================================================
# To list files in the current user profile which have the archive bit set:
Get-ChildItem $env:USERPROFILE -Recurse -Force | Where-Object {$_.Mode -like "*a*"}
# =============================================================================
# If, ElseIf, and Else Statements
#
# http://www.tomsitpro.com/articles/powershell-comparison-operators-conditional-logic,2-850.html
# =============================================================================
# To test if a connection can be reached with "www.google.com":
if (Test-Connection www.google.com -Quiet) {
Write-Host "Internet connection is live."
}
# Test if a connection can be reached with "www.google.com", if not... try
# connecting to "192.168.0.1"; finally echo "Network connectivity is
# unavailable.", if no Network connectivity.
if (Test-Connection www.google.com -Quiet) {
Write-Host "Internet connection is live."
} elseif (Test-Connection 192.168.0.1 -Quiet) {
Write-Host "Only local network connectivity is available."
} else {
Write-Host "Network connectivity is unavailable."
}
# =============================================================================
# Switch Statements
#
# http://www.tomsitpro.com/articles/powershell-comparison-operators-conditional-logic,2-850.html
# =============================================================================
# To read the day of the week and return whether it is a Weekday or the Weekend:
switch ((Get-Date).DayOfWeek)
{
"Saturday" {"Weekend"}
"Sunday" {"Weekend"}
Default {"Weekday"}
}
# To use the wildcard option with a switch statement to perform matching on days
# that start with the letter "s" for indicating "Weekend".
switch -Wildcard ((Get-Date).DayOfWeek)
{
"S*" {"Weekend"}
Default {"Weekday"}
}
#
# Switch to the appropriate server env. based on script arg:
$ENV = $args[0]
if ($ENV -eq $null)
{
$ENV = "PROD"
}
switch ($ENV)
{
"PROD"
{
$DBServer = "status.db.prod.dexma.com";
$DB = "status";
$SQLQuery = "SELECT s.server_name
FROM dbo.t_server AS s INNER JOIN
dbo.t_monitoring AS m ON s.server_id = m.server_id
WHERE (s.active = 1) AND (m.Perfmon = 1) AND (s.environment_id = 0)"
}
"DEMO"
{
$DBServer = "status.db.stage.dexma.com";
$DB = "statusstage";
$SQLQuery = "SELECT s.server_name
FROM dbo.t_server AS s INNER JOIN
dbo.t_monitoring AS m ON s.server_id = m.server_id
WHERE (s.active = 1) AND (m.Perfmon = 1) AND (s.environment_id = 1)"
}
"IMP"
{
$DBServer = "status.db.imp.dexma.com";
$DB = "statusimp";
$SQLQuery = "SELECT s.server_name
FROM dbo.t_server AS s INNER JOIN
dbo.t_monitoring AS m ON s.server_id = m.server_id
WHERE (s.active = 1) AND (m.Perfmon = 1) AND (s.environment_id IN ('2', '9'))"
}
}
Write-Host $DBServer, $DB, $SQLQuery
# =============================================================================
# Try, Catch and Finally
#
# http://www.vexasoft.com/blogs/powershell/7255220-powershell-tutorial-try-catch-finally-and-error-handling-in-powershell
# =============================================================================
# The last part of Try Catch Finally is the Finally block. This must be defined
# immediately after the Catch block and runs every time, regardless of whether
# there was an error or not. In this way you can perform actions that need to be
# made regardless of whether an operation succeeds or fails. In our example we are
# going to log that a file read was attempted. Our Get-Content line now looks
# like:
Try
{
$AuthorizedUsers = Get-Content \\FileServer\HRShare\UserList.txt -ErrorAction Stop
}
Catch [System.OutOfMemoryException]
{
Restart-Computer localhost
}
Catch
{
$ErrorMessage = $_.Exception.Message
$FailedItem = $_.Exception.ItemName
Send-MailMessage -From ExpensesBot@MyCompany.Com -To WinAdmin@MyCompany.Com -Subject "HR File Read Failed!" -SmtpServer EXCH01.AD.MyCompany.Com -Body "We failed to read file $FailedItem. The error message was $ErrorMessage"
Break
}
Finally
{
$Time=Get-Date
"This script made a read attempt at $Time" | out-file c:\logs\ExpensesScript.log -append
}