More Related Content Similar to Power shell voor developers (20) More from Dennis Vroegop (10) Power shell voor developers10. > _
− REPL (Read Evaluate Print Loop)
− .NET
− Commands
− Parameters
− Objecten
− Command pipeline
12. > Commands
− [Verb]-[Prefix][Noun]
− Verb: Get, New, Update, … (Get-Verb)
− Prefix: VM, AD, Azure, Sql, …
− Noun: Switch, User, Website, Database
− Get-Service
− Get-VMSwitch
− New-ADUser
− Start-AzureWebsite
− Backup-SqlDatabase
13. > Command pipeline
− Get-Process | Sort ProcessName | Select *
− Select-Object select
− Sort-Object sort
− Where-Object where, ?
− ForEach-Object foreach, %
14. > Select-Object
− Specify which properties to return
− Select ProcessName,Description
− Select *
− Specify how many objects to return
− Select –First 5
− Select –First 5 –Skip 5
− Select –Last 10
− Get-Process | Select
ProcessName,Description –First 10
15. > Sort-Object
− Specify order of objects
− Sort ProcessName
− Specify direction
− Sort ProcessName -Descending
− Get-Process | Sort ProcessName,Description
16. > Where-Object
− Filter objects by property
− Where -Property ProcessName -EQ 'powershell'
− Filter objects using script
− Where { $_.ProcessName -eq 'powershell' }
− Get-Process |? { $_.ProcessName -like 'po*' }
17. > ForEach-Object
− Repeat for each object
− ForEach { Write-Host $_.ProcessName }
− Get-Process |% { Write-Host "$($_.ProcessName)" }
19. > Format-*
− Format-Table (ft)
− -AutoSize (ft –a)
− Format-List (fl)
− Format-Wide (fw)
− -Column (fw –c 3)
− Get-Command format-*
21. > ConvertTo-* / ConvertFrom-*
− ConvertTo-Json, ConvertFrom-Json
− ConvertTo-Xml (, Get-Content)
− ConvertTo-Csv, ConvertFrom-Csv
− ConvertTo-Html
− Get-Command convertto-*,convertfrom-*
22. > Advanced pipeline
− -PassThru
− Multiline with `
− Multi-command on single line with ;
− Select @{ Name = $_.Name; Type = 'Foo' }
− Force expression evaluation using brackets ()
24. > Hosts
− Console
− ISE (Integrated Script Environment)
− Visual Studio Extension (2015, 2013, 2012)
− Visual Studio Code Extension
− PowerGUI
− PowerShell Plus
− Custom
− [insert your application name here]
27. > $Profile
− Current user / All users
− Current host / All hosts
− $profile
− Current user, current host
− $profile.AllUsersAllHosts
− $profile.AllUsersCurrentHosts
− $profile.CurrentUsersAllHosts
− $profile.CurrentUsersCurrentHost
$profile.AllUsersAllHosts
C:WindowsSystem32WindowsPowerShellv1.0profile.ps1
$profile.AllUsersCurrentHosts
C:WindowsSystem32WindowsPowerShellv1.0Microsoft.PowerShell_profile.ps1
$profile.CurrentUsersAllHosts
C:UsersjswartDocumentsWindowsPowerShellprofile.ps1
$profile.CurrentUsersCurrentHost
C:UsersjswartDocumentsWindowsPowerShellMicrosoft.PowerShell_profile.ps1
$profile (console)
C:UsersjswartDocumentsWindowsPowerShellMicrosoft.PowerShell_profile.ps1
$profile (ISE)
C:UsersjswartDocumentsWindowsPowerShellMicrosoft.PowerShellISE_profile.ps1
28. > $Profile
$global:CurrentUser = [System.Security.Principal.WindowsIdentity]::GetCurrent()
function prompt
{
$Host.UI.RawUI.WindowTitle = "$($CurrentUser.Name) - $(Get-Location)"
Write-Host 'PS >' -NoNewline
return ' '
}
29. > $PSVersionTable
Name Value
---- -----
PSVersion 5.0.10586.122
PSCompatibleVersions {1.0, 2.0, 3.0, 4.0...}
BuildVersion 10.0.10586.122
CLRVersion 4.0.30319.42000
WSManStackVersion 3.0
PSRemotingProtocolVersion 2.3
SerializationVersion 1.1.0.1
30. > Strings
− Literals
− 'Name: $Name'
− "Name: $Name"
− Format
− 'Name: {0}' –f $Name
− Expression
− "Name: $user.Name"
− "Name: $($user.Name)"
Name: $Name
Name: Jeroen
Name: Jeroen
Name: Hashtable.Name
Name: Jeroen
31. > Strings & regular expressions
− Match
− 'PowerShell' –match 'sh'
− 'PowerShell' –match '^P'
− 'PowerShell' –match 'P$‘
− 'PowerShell' –cmatch 'p$'
− Replace
− 'PowerShell' -replace 'e','E'
True
True
False
False
PowErShEll
32. > Arrays & objects
− Command output is array or object
− When Parameter type is Array, provide
either array or single object as value
33. > Arrays
− $a = 1,2
− $a = @(1)
− $a = @()
− $a = 1..5
− $a += 6
− $a.GetType() -> System.Array
− $a.Length
− $a.Contains(1)
− $a[0]
34. > Objects (HashTable)
− $o = @{}
− $o = @{ Name = 'me' }
− $o = @{
Name = 'me'
PowerShell = $true
}
− $o = @{ Name = 'me'; PowerShell = $true }
35. > Objects (PSCustomObject)
$o = New-Object PSCustomObject `
| Add-Member -MemberType NoteProperty -Name 'Name' -Value 'me' -PassThru `
| Add-Member -MemberType NoteProperty -Name 'PowerShell' -Value $true -PassThru
36. > Objects
− $o.Name
− $o.'Name'
− $o = @{
Name = 'me'
PowerShell = $true
}
− $o = @{ Name = 'me'; PowerShell = $true }
37. > Scripts
− Collection of commands
− Conditional statements (if/else, etc.)
− Parameters
− Output
− Execute using . Or &
− Execute using full or relative path (.)
. .DoSomethingSmart.ps1
. '.DoSomethingSmart.ps1'
38. > Scripts – if/else
if ($condition) {
}
elseif ($otherCondition) {
}
else {
}
if (Test-Path -Path $path) {
}
if (Get-Service 'MSSQL*') {
}
Basic syntax Using commands returning a boolean
Using other commands
if ($name -eq 'PowerShell' ) {
}
Using logical operators
if ($condition -eq $true) {
}
Using explicit conditions
39. > Scripts – if/else
− -eq, -ne
− -lt, -gt, -le, -ge
− -like, -match, -notlike, -notmatch
− -contains, -in, -notcontains, -notin
− And their case-sensitive version (-ceq, -clike, etc.)
− And their (explicit) case-insensitive version (-ieq, -ilike, etc.)
− -not, -or, -and, -xor
− And their binary version (-bnot, -bor, etc.)
− -is, -isnot
40. > Scripts – switch/case
switch ($value) {
1 { }
2 { }
default { }
}
switch ($value) {
'1' { }
'2' { }
default { }
}
switch ($value) {
{ $_ -eq 1 } { }
{ $_ -in 2,3 } { }
{ $_ -like '4*' } { }
{ $_ -match '^5' } { }
default { }
}
Basic syntax
Using strings
Using expressions
41. > Scripts – foreach
foreach ($item in $items) {
# use $item
}
$items |% {
# use $_
}
Basic syntax
Alternative
42. > Scripts – for
for ($index = 0; $index -lt 10; $index++) {
# use $items[$index]
}
Basic syntax
43. > Scripts – try/catch
try {
throw 'Serious error'
throw [InvalidOperationException]'Serious error'
}
catch [InvalidOperationException] {
write-host 'InvalidOperationException'
}
catch {
}
finally {
}
44. > Scripts – parameters
− Name
− Default
− Type
− Mandatory
− ValueFromPipeline
− ParameterSetName
− Validation
− ValidateSet
− ValidateScript
− switch
param (
)
param (
$Value
)
param (
$Value = 'The default value'
)
param (
[string]$Value
)
param (
[Parameter(Mandatory = $true)]
[string]$Value
)
param (
[Parameter(ValueFromPipeline = $true)]
[string[]]$Value
)
param (
[Parameter(ParameterSetName = ‘ByValue')]
[string]$Value,
[Parameter(ParameterSetName = 'ByCount')]
[int]$Count
)
. .Script.ps1 -Value 'foo'
. .Script.ps1 –Count 42
param (
[ValidateSet('High', 'Low')]
[string]$Value
)
param (
[ValidateScript({
Test-Path -Path $_ -PathType Leaf
})]
[string]$Path
)
param (
[switch]$Force
)
if ($Force) {
}
if ($Force.IsPresent) {
}
. .Script.ps1 –Force True
. .Script.ps1 False
. .Script.ps1 –Force:$false False
param (
[bool]$Force
)
if ($Force) {
}
. .Script.ps1 –Force $true True
. .Script.ps1 –Force $false False
45. > Scripts – output
− return
− Write-Output
− Write-Host
− Write-Verbose
− CmdletBinding
− -Verbose
return 'The result'
The result
Write-Output 'The result'
The result
Write-Output 'The result'
Write-Output ‘More result'
The result
More result
Write-Host 'Message‘
Write-Host 'Message' -ForegroundColor Yellow
Write-Host 'Message' -BackgroundColor Magenta `
-ForegroundColor White
Write-Host ('Message {0}' -f 42)
[CmdletBinding()]
param (
)
Write-Verbose 'Verbose message‘
46. > Scripts – output
− Write-Verbose -Verbose $VerbosePreference
− Write-Debug -Debug $DebugPreference
− Write-Warning -WarningAction $WarningPreference
− Write-Error -ErrorAction $ErrorActionPreference
− Write-Information -InformationAction $InformationPreference
− Action/Preference
− SilentlyContinue
− Continue
− Stop
47. > Scripts – lifecycle
param (
)
# script-body here
. .Script.ps1 -Value '1','2'
'1','2' | . .Script.ps1
− $Value = '1','2'
− $Value = '2'
param (
[string[]]$Value
)
# script-body here
param (
[Parameter(ValueFromPipeline = $true)]
[string[]]$Value
)
# script-body here
$Value
48. > Scripts – lifecycle
param (
)
begin {
}
process {
# script-body here
}
end {
}
. .Script.ps1 -Value '1','2'
'1','2' | . .Script.ps1
− Begin
− Process ($Value = '1','2')
− End
− Begin
− Process ($Value = '1')
− Process ($Value = '2')
− End
param (
)
begin {
}
process {
# script-body here
}
end {
}
param (
[string[]]$Value
)
begin {
}
process {
# script-body here
}
end {
}
param (
[Parameter(ValueFromPipeline = $true)]
[string[]]$Value
)
begin {
}
process {
# script-body here
$Value
}
end {
}
50. > Functions
function Verb-PrefixNoun {
}
function Verb-PrefixNoun {
param (
[string]$Value
)
# function-body here
$Value
}
function Verb-PrefixNoun {
param (
[string[]]$Value
)
begin {
}
process {
# script-body here
$Value
}
end {
}
}
51. > Modules
− PowerShell Script or C#
− C#
− System.Management.Automation namespace
− Cmdlet base-class
− Cmdlet attribute
− PowerShell Script
− Collection of functions
− .psm1
− .psd1
52. > Modules
− Import-Module
− .psm1
− .psm1 + .psd1
− New-ModuleManifest
− Update-ModuleManifest
− Test-ModuleManifest
− Script-files
function Get-SomeStuff {
}
function Update-SomeStuff {
}
function Remove-SomeStuff {
}
@{
Author = 'Jeroen Swart'
RootModule = 'MyModule.psm1'
ModuleVersion = '1.0.0.0'
GUID = 'bbd0a9d3-8308-4e5b-9762-1cbc057dd1c4'
Description = '...'
PowerShellVersion = '4.0'
FunctionsToExport = (
'Get-SomeStuff',
'Update-SomeStuff',
'Remove-SomeStuff')
}
Get-ChildItem `
-Path "$PSScriptRootInternal" `
-Filter '*.ps1' |% {
. $_.FullName
}
Get-ChildItem `
-Path "$PSScriptRootFunctions" `
-Filter '*.ps1' |% {
. $_.FullName
}
53. > Modules
− Import-Module –Path '...'
− Import-Module –Name '...'
− System
− %windir%System32WindowsPowerShellv1.0Modules
− $pshomeModules
− All users
− %ProgramFiles%WindowsPowerShellModules
− "$($env:ProgramFiles)WindowsPowerShellModules"
− Current user
− %UserProfile%DocumentsWindowsPowerShellModules
− $homeDocumentsWindowsPowerShellModules
55. • NuGet
• Chocolatey
• PowerShell Package Management
• TFS Build
• TFS Release Management
• Remote PowerShell
• PowerShell DSC
• Server Management
> Select PowerShell | More
57. > NuGet
− zip, maar .nupkg
− lib
− net45
− net40
− portable-win+net45+wp8+win8+wpa81
− content
− tools
− init.ps1
− .psm1
− nuspec
58. > NuGet
− init.ps1
− installPath
− toolPath
− package
− project
− EnvDTE.Project
− ProjectItems
− DTE EnvDTE.DTE
59. > NuGet
− Add/modify files & content in a project
− Build and/or run the solution
− Code generation
− Entity Framework Migrations
− Manage windows & documents
− Enhance Visual Studio UI
61. > Chocolatey
− Windows Package Manager
− choco list
− choco install
− NuGet-based
− nuspec
− tools
− chocolateyInstall.ps1
− chocolateyUninstall.ps1
63. > Chocolatey
Install-ChocolateyPackage `
'notepadplusplus' `
'exe' `
'/S' `
'https://notepad-plus-plus.org/repository/6.x/6.8.8/npp.6.8.8.Installer.exe'
Notepadplusplus (chocolateyInstall.ps1)
$packageName = 'GoogleChrome'
$app = Get-WmiObject -Class Win32_Product | Where-Object {$_.Name -eq 'Google Chrome'}
if ($app) {
$msiArgs = $('/x' + $app.IdentifyingNumber + ' /q REBOOT=ReallySuppress')
Start-ChocolateyProcessAsAdmin $msiArgs 'msiexec'
}
GoogleChrome (chocolateyUninstall.ps1)
64. > PowerShell Modules
− xcopy
− System, All users, Current user
− Chocolatey package
− xcopy
− PowerShell Package Management
− PowerShell v5
66. > PowerShell Package Management
− Module
− Script
− Package
− Find, Install, Update, Publish, Save
− Find-Module
− Install-Package
68. • TFS Build
• TFS Release Management
> Select PowerShell | More
69. > TFS Build
− XAML Build
− Task-based build
− Script (in VC)
− Arguments
70. > TFS Release Management
− XAML
− Task-based
− TFS 2015 Update 2
71. > TFS Release Management
− Remote PowerShell
− PowerShell Scripts
− PowerShell Modules
− PowerShell DSC
− PowerShell Package Management (Chocolatey)
72. > TFS Release Management
Build
Drop-
location
RM
Target-
servers
Trigger release Execute script
Copy files to servers
73. > TFS Release Management
Build
Package
Source
RM
Target-
servers
Chocolatey Packages
PowerShell Modules
Trigger release
Retrieve packages
Install packages
75. > Remote PowerShell
− Enter-PSSession & Exit-PSSession
− New-PSSession & Remove-PSSession
− Invoke-Command -Session
76. > Remote PowerShell
− Enable remoting
− Enable-PSRemoting
− Check configuration
− Test-WSMan
− Limit access
− Set-Item `
wsman:localhostclienttrustedhosts [name] `
-Concatenate
-Force
77. > Remote PowerShell
− 'Double Hop'
− CredSSP & Credential
− Server
− Enable-WSManCredSSP -Role Server
− Client
− Enable-WSManCredSSP -Role Client `
–DelegateComputer [machinename]
78. > PowerShell DSC
$server = new-Object Microsoft.SqlServer.Management.Smo.Server("(local)")
if($Credential) {
$server.ConnectionContext.Login = $Credential.UserName
$server.ConnectionContext.SecurePassword = $credential.Password
}
$database = $server.Databases |? { $_.Name -eq $Name }
if (-not $database) {
$database = New-Object Microsoft.SqlServer.Management.Smo.Database($server, $Name)
$database.Create()
}
PowerShell Script
80. > PowerShell DSC
− Desired State Configuration
− Declarative
− Configuration
− Resource
− Get
− Test
− Set
83. > Server Management
− Server
− Processes
− Services
− Resources (RAM, CPU, …)
− IIS
− Websites
− App pools
− Logging
84. • notes in ppt
• MSDN
• Windows PowerShell
• PowerShell DSC
• PowerShell SDK
• Blogs
• Windows PowerShell Blog
• Hey Scripting Guy
• ...
• Books
• Windows PowerShell in Action
• Windows PowerShell Cookbook
• Windows PowerShell for Developers
• ...
> Get-Help
85. • PowerShell Workflow
• Debugging (incl. remote)
• Classes
• ISE
• Automation
• Extensions/Add-ons
• Unit testing (Pester)
• Azure (incl. PowerShell DSC)
• OSS Packages & Modules
> _
Editor's Notes YouTube: https://www.youtube.com/watch?v=V5Gjx4jM91A
Januari 2016: 72 groningen 38 amersfoort 2 Den Haag Get-Process
$p = Get-Process
$p
$p.GetType()
$p[0]
$p[0].GetType()
Get-Process –Name powershell
Get-Process –Name power*
Get-Process power*
Get-Process –n power*
Get-Command
Get-Command Get-Command
Get-Help Get-Command
Get-Help Get-Command -Full
Get-Help Get-Command -Online
(get-command Get-Verb).Definition
Get-Alias
Get-Alias cls,dir,kill
PassThru: e.g. RestartService
PowerShell recognizes incomplete commands; to force multiline use `
PowerShell does not use (or require) statements to end with ‘;’ , but you may use it, especially practical when invoking multiple commands in a single line
Select hashtable: think LINQ projections Get-Process
Get-Process | Select ProcessName, Description
Get-Process | Select ProcessName, Description -First 5
Get-Process | Select ProcessName, Description | Select -First 5
Get-Process | Select ProcessName, Description -First 5 | fl
Get-Process | Select ProcessName, Description -First 5 |Sort ProcessName -Descending | fl
Get-Service | Select -First 20
Get-Service | Select -First 20 | ft -a
Get-Service | fw -c 3
Get-Service | Out-GridView
Get-Service | Out-GridView -PassThru
Get-Service | Out-GridView -PassThru -Title 'Select a service to restart'
Get-Service | ConvertTo-Json
Get-Service | ConvertTo-Html | Out-File d:\get-service.html
Get-Service | ConvertTo-Html | Out-File d:\get-service.html;Start-Process d:\get-service.html
Get-Service | Select -First 1
(Get-Service | Select -First 1).Name
Get-Service | Select Name -First 5
(Get-Service | Select Name -First 5).Name
PowerShell Tools for Visual Studio
https://visualstudiogallery.msdn.microsoft.com/c9eb3ba8-0c59-4944-9a62-6eee37294597
Writing a Windows PowerShell Host Application
https://msdn.microsoft.com/en-us/library/ee706563(v=vs.85).aspx
DEMO #1
Write-Hello.ps1
param (
[Parameter(Mandatory = $true)]
[string]$Name
)
Write-Host 'Writing hello...'
Write-Output "Hello $Name"
> .\Write-Hello.ps1 -Name 'Jeroen'
> $h = .\Write-Hello.ps1 -Name 'Jeroen'
> $h
DEMO #2
Write-Hello.ps1
param (
[Parameter(Mandatory = $true, ValueFromPipeline = $true)]
[string[]]$Name
)
Write-Host 'Writing hello...'
$Name |% {
Write-Output "Hello $_"
}
> .\Write-Hello.ps1 -Name 'Jeroen','you'
> 'Jeroen','you' | .\Write-Hello.ps1
DEMO #3
Write-Hello.ps1
param (
[Parameter(Mandatory = $true, ValueFromPipeline = $true)]
[string[]]$Name
)
begin {
Write-Host 'Writing hello...'
}
process {
$Name |% {
Write-Output "Hello $_"
}
}
> 'Jeroen','you' | .\Write-Hello.ps1
> .\Write-Hello.ps1 -Name 'Jeroen','you'
DEMO #4
Write-Hello.ps1
param (
[Parameter(Mandatory = $true, ValueFromPipeline = $true)]
[string[]]$Name
)
begin {
Write-Host 'Writing hello...'
}
process {
$Name |% { "Hello $_" } |% {
Write-Verbose $_
Write-Output $_
}
}
> .\Write-Hello.ps1 -Name 'Jeroen','you'
> .\Write-Hello.ps1 -Name 'Jeroen','you' –Verbose
> $r = .\Write-Hello.ps1 -Name 'Jeroen','you' -Verbose
> $r
Understanding a Windows PowerShell Module: https://msdn.microsoft.com/en-us/library/dd878324(v=vs.85).aspx
How to Write a PowerShell Script Module: https://msdn.microsoft.com/en-us/library/dd878340(v=vs.85).aspx
How to Write a PowerShell Binary Module: https://msdn.microsoft.com/en-us/library/dd878342(v=vs.85).aspx
Writing a PowerShell module in C#, Part 1: The basics
http://www.powershellmagazine.com/2014/03/18/writing-a-powershell-module-in-c-part-1-the-basics/
Basics of Writing a PowerShell Module with C#, Part 2: Debugging
http://www.powershellmagazine.com/2014/04/08/basics-of-writing-a-powershell-module-with-c-part-2-debugging/
EnvDTE.Project: https://msdn.microsoft.com/en-us/library/envdte.project.aspx
EnvDTE.DTE: https://msdn.microsoft.com/en-us/library/envdte.dte.aspx
Show Write-Hello solution
init.ps1
Write-Hello.psm1
nuspec
Package.ps1
Publish.ps1
Run Package.ps1
show package
Create new project
add/show package source
add nuget package
open Package Manager Console
Get-Module
Write-Hello –Name ‘Jeroen’
https://chocolatey.org/ http://www.powershellgallery.com/ http://www.powershellgallery.com/ http://www.powershellgallery.com/ Create PowerShell module (at 'D:\Projects\PowerShell\WriteHello\‘)
Register local folder as source (at ‘D:\Packages’)
Get-PackageSource
Register-PackageSource -Name ‘Demo’ -Location ‘D:\Packages’ -ProviderName PowerShellGet -Trusted
Publish module to local source
Publish-Module -Path 'D:\Projects\PowerShell\WriteHello\' -Repository Demo
Install module from local source
Find-Module WriteHello
Find-Module WriteHello | Install-Module -Scope CurrentUser
Import-Module WriteHello
Debug.ps1
Get-Variable
dir env:
ApplyVersion.ps1
Parameters in task
Parameters in script http://powershell.com/cs/media/p/7257.aspx
Windows Server Core, Windows Server Nano & Windows Containers
Enable-PSRemoting, of winrm quickconfig
Trustedhosts zowel IP’s, als FQDN’s met wildcards To verify: Get-WSManCredSSP Met ‘vanilla’ PowerShell programmeer je ieder detail van iedere stap in het deployment-proces, inclusief iedere kleine uitzondering en afwijking.
Terwijl veel van deze stappen generiek en herbruikbaar zijn.
Je kunt hiervoor een library maken van herbruikbare functies; maar PowerShell DSC biedt dit al, in de vorm van herbruikbare resources. Naast Microsoft, wordt ook veel door de community aangeboden, en je kunt zelf eenvoudig resources toevoegen.
Dit voorbeeld is voor het aanmaken van een SQL Server database. In plaats van iedere stap uit te programmeren, beschrijf je met PowerShell DSC het gewenste eindresultaat.
Een volledig eindresultaat wordt beschreven in een ‘configuration’, welke is verdeelt in resources. Een resource kan een folder zijn met inhoud, een windows-feature die moet worden geactiveerd (zoals IIS), of een MSI of web-package die moet worden geinstalleerd.
Dit voorbeeld toont een resource voor het aanwezig zijn van een SQL Server database. DSC Configuration for deploying
Website
Batch-service
CPU Load
Get-WmiObject win32_processor | select LoadPercentage
Get-WmiObject win32_processor | Measure-Object -property LoadPercentage -Average | Select Average
Performance Counters
Get-Counter '\Memory\Available MBytes‘
Get-Counter -ListSet *memory* | Select-Object -ExpandProperty Counter
Get-Counter -ComputerName localhost '\Process(*)\% Processor Time' | Select-Object -ExpandProperty countersamples | Select-Object -Property instancename, cookedvalue| Sort-Object -Property cookedvalue -Descending| Select-Object -First 20| ft InstanceName,@{L='CPU';E={($_.Cookedvalue/100).toString('P')}} –AutoSize
function Get-MemoryUsage ($ComputerName=$ENV:ComputerName) {
if (Test-Connection -ComputerName $ComputerName -Count 1 -Quiet) { $ComputerSystem = Get-WmiObject -ComputerName $ComputerName -Class Win32_operatingsystem -Property CSName, TotalVisibleMemorySize, FreePhysicalMemory $MachineName = $ComputerSystem.CSName $FreePhysicalMemory = ($ComputerSystem.FreePhysicalMemory) / (1mb) $TotalVisibleMemorySize = ($ComputerSystem.TotalVisibleMemorySize) / (1mb) $TotalVisibleMemorySizeR = “{0:N2}” -f $TotalVisibleMemorySize $TotalFreeMemPerc = ($FreePhysicalMemory/$TotalVisibleMemorySize)*100 $TotalFreeMemPercR = “{0:N2}” -f $TotalFreeMemPerc
# print the machine details: “Name: $MachineName” “RAM: $TotalVisibleMemorySizeR GB” “Free Physical Memory: $TotalFreeMemPercR %”
}
}
Logging
cd d:\www\events\app_data
dir | select -last 1 | get-content |? { $_ -match 'error' }
Windows PowerShell
https://msdn.microsoft.com/en-us/powershell/mt173057.aspx
https://technet.microsoft.com/library/bb978526.aspx
PowerShell DSC
https://msdn.microsoft.com/en-us/powershell/dsc/overview
PowerShell SDK
https://msdn.microsoft.com/library/dd835506.aspx
Windows PowerShell Blog
https://blogs.msdn.microsoft.com/powershell/
Hey Scripting Guy
https://blogs.technet.microsoft.com/heyscriptingguy/
PowerShell ISE Add-Ons
http://social.technet.microsoft.com/wiki/contents/articles/2969.windows-powershell-ise-add-on-tools.aspx
OSS Packages: chocolatey.org
OSS Modules: powershellgallery.com
Azure PowerShell DSC
https://azure.microsoft.com/en-us/blog/vm-agent-and-extensions-part-1/
https://blogs.msdn.microsoft.com/powershell/2014/08/07/introducing-the-azure-powershell-dsc-desired-state-configuration-extension/
https://azure.microsoft.com/en-us/blog/new-additions-to-the-azure-vm-powershell-dsc-extension/