SlideShare ist ein Scribd-Unternehmen logo
1 von 2
Downloaden Sie, um offline zu lesen
WINDOWS POWERSHELL 4.0 EXAMPLES
Created by http://powershellmagazine.com
Job scheduling allows you to schedule execution of a PowerShell background job for a
later time. First thing you do is create a job trigger. This defines when the job will
execute. Then you use the Register-ScheduledJob cmdlet to actually register the job on
the system. In the following example, every day at 3am we back up our important files:
$trigger = New-JobTrigger -Daily -At 3am
Register-ScheduledJob -Name DailyBackup -Trigger $trigger -ScriptBlock {Copy-Item
c:ImportantFiles d:Backup$((Get-Date).ToFileTime()) -Recurse -Force -PassThru}
Once the trigger has fired and the job has run, you can work with it the same way you
do with regular background jobs:
Get-Job -Name DailyBackup | Receive-Job
You can start a scheduled job manually, rather than waiting for the trigger to fire:
Start-Job -DefinitionName DailyBackup
The RunNow parameter for Register-ScheduledJob and Set-ScheduledJob eliminates
the need to set an immediate start date and time for jobs by using the -Trigger
parameter:
Register-ScheduledJob -Name Backup -ScriptBlock {Copy-Item c:ImportantFiles d:
Backup$((Get-Date).ToFileTime()) -Recurse -Force -PassThru} -RunNow
In PowerShell 4.0, the PipelineVariable lets you save the results of a piped command
(or part of a piped command) as a variable that can be passed through the remainder
of the pipeline. Its alias is "pv".
Get-ChildItem *.ps1 -pv a | Get-Acl | foreach {"{0} size is {1}" -f $a.Name, $a.length}
How to schedule a job PipelineVariable Common Parameter
Windows PowerShell 4.0 supports method invocation using dynamic method names.
$fn = "ToString"
"Hello".ToString()
"Hello".$fn()
"Hello".("To" + "String")()
 
#Select a method from an array:
$index = 1; "Hello".(@("ToUpper", "ToLower")[$index])()
Dynamic method invocation
Starting with PowerShell 4.0, we can specify that a script requires administrative
privileges by including a #Requires statement with the -RunAsAdministrator switch
parameter.
#Requires -RunAsAdministrator
#Requires -RunAsAdministrator
There is no built-in cmdlet to generate a password, but we can leverage a vast number
of .NET Framework classes. System.Web.Security.Membership class has a static
method GeneratePassword(). First, we need to load an assembly containing this class,
and then we use GeneratePassword() to define password length and a number of non-
alphanumeric characters.
$Assembly = Add-Type -AssemblyName System.Web
[System.Web.Security.Membership]::GeneratePassword(8,3)
How do we know all that? With a little help from the Get-Member cmdlet (and
simplified where syntax):
[System.Web.Security.Membership] | Get-Member -MemberType method -Static|
where name -match password
How to generate complex password
The Test-NetConnection cmdlet (available on Windows 8.1 / Server 2012 R2) displays
diagnostic information for a connection.
#Returns detailed diagnostic information for microsoft.com
Test-NetConnection -ComputerName microsoft.com -InformationLevel Detailed
#Returns a Boolean value based on connectivity status
Test-NetConnection -ComputerName microsoft.com -Port 80 -InformationLevel Quiet
Diagnosing network connectivity
The new Get-FileHash cmdlet computes the hash value for a file. There are multiple
hash algorithms supported with this cmdlet.
Get-FileHash C:downloadsWindowsOS.iso -Algorithm SHA384
Working with a file hash
WINDOWS POWERSHELL 4.0 EXAMPLES
Created by http://powershellmagazine.com
The Invoke-WebRequest cmdlet parses the response, exposing collections of forms,
links, images, and other significant HTML elements. The following example returns all
the URLs from a webpage:
$iwr = Invoke-WebRequest http://blogs.msdn.com/b/powershell
$iwr.Links
The next example returns an RSS feed from the PowerShell team blog:
$irm = Invoke-RestMethod blogs.msdn.com/b/powershell/rss.aspx
$irm | Select-Object PubDate, Title
If you, for example, need to execute one of the -PSSession cmdlets using alternate
credentials you must specify the credentials for the Credential parameter every time
you call the command. In PowerShell 3.0 and later, we can supply alternate credentials
by using new $PSDefaultParameterValues preference variable. For more information,
see about_Parameters_Default_Values.
$PSDefaultParameterValues = @{'*-PSSession:Credential'=Get-Credential}
How to parse webpage elements
The Invoke-RestMethod cmdlet sends an HTTP(S) request to a REST-compliant web
service. You can use it to consume data exposed by, for example, the OData service for
TechEd North America 2014 content. Put information about TechEd NA 2014 sessions
into a $sessions variable. Let's iterate through that collection of XML elements and
create custom PowerShell objects using [PSCustomObject]. Pipe the output to an Out-
GridView command specifying the PassThru parameter to send selected items from the
interactive window down the pipeline, as input to an Export-Csv command. (While you
are in a grid view window, try to filter only PowerShell Hands-on Labs, for example). If
you have Excel installed the last command opens a CSV file in Excel.
$sessions = Invoke-RestMethod https://odata.eventpointdata.com/tena2014/
Sessions.svc/Sessions
$sessions | ForEach-Object {
$properties = $_.content.properties
[PSCustomObject]@{
Code = $properties.Code
Day = $properties.Day_US
StartTime = $properties.Start_US
EndTime = $properties.Finish_US
Speaker = $properties.PrimarySpeaker
Title = $properties.Title
Abstract = $properties.Abstract
}
} | Out-GridView -PassThru | Export-Csv $env:TEMPsessions.csv -NoTypeInformation
Invoke-Item $env:TEMPsessions.csv
How to fetch data exposed by OData services
How to set custom default values for the parameters
In Windows PowerShell 3.0, Save-Help worked only for modules that are installed on
the local computer. PowerShell 4.0 enables Save-Help to work for remote modules.
Use Invoke-Command to get the remote module and call Save-Help:
$m = Invoke-Command -ComputerName RemoteServer -ScriptBlock { Get Module  -
Name DhcpServer -ListAvailable }
Save-Help -Module $m -DestinationPath C:SavedHelp
Use a PSSession to get the remote module and call Save-Help:
$s = New-PSSession -ComputerName RemoteServer
$m = Get-Module -PSSession $s -Name DhcpServer -ListAvailable
Save-Help -Module $m -DestinationPath C:SavedHelp
Use a CimSession to get the remote module and call Save-Help:
$c = New-CimSession -ComputerName RemoteServer
$m = Get-Module -CimSession $c -Name DhcpServer -ListAvailable
Save-Help -Module $m -DestinationPath C:SavedHelp
Save-Help
In PowerShell 2.0, if you had some local variable that you wanted to use when
executing a script block remotely, you had to do something like:
$localVar = 42
Invoke-Command -ComputerName Server 1 { param($localVar) echo $localVar } -
ArgumentList $localVar
In PowerShell 3.0 and later, you can use Using scope (prefix variable name with
$using:):
Invoke-Command -ComputerName Server1 { echo $using:localVar }
How to access local variables in a remote session

Weitere ähnliche Inhalte

Was ist angesagt?

Flask patterns
Flask patternsFlask patterns
Flask patterns
it-people
 
Building Web Services with Zend Framework (PHP Benelux meeting 20100713 Vliss...
Building Web Services with Zend Framework (PHP Benelux meeting 20100713 Vliss...Building Web Services with Zend Framework (PHP Benelux meeting 20100713 Vliss...
Building Web Services with Zend Framework (PHP Benelux meeting 20100713 Vliss...
King Foo
 

Was ist angesagt? (20)

Django
DjangoDjango
Django
 
Windows PowerShell
Windows PowerShellWindows PowerShell
Windows PowerShell
 
feature toggles for ops
feature toggles for opsfeature toggles for ops
feature toggles for ops
 
Rest api with Python
Rest api with PythonRest api with Python
Rest api with Python
 
Why and How Powershell will rule the Command Line - Barcamp LA 4
Why and How Powershell will rule the Command Line - Barcamp LA 4Why and How Powershell will rule the Command Line - Barcamp LA 4
Why and How Powershell will rule the Command Line - Barcamp LA 4
 
8 Minutes On Rack
8 Minutes On Rack8 Minutes On Rack
8 Minutes On Rack
 
Flask patterns
Flask patternsFlask patterns
Flask patterns
 
Filling the flask
Filling the flaskFilling the flask
Filling the flask
 
Introduction to PowerShell
Introduction to PowerShellIntroduction to PowerShell
Introduction to PowerShell
 
Php database connectivity
Php database connectivityPhp database connectivity
Php database connectivity
 
Config BuildConfig
Config BuildConfigConfig BuildConfig
Config BuildConfig
 
Flask – Python
Flask – PythonFlask – Python
Flask – Python
 
Flask - Backend com Python - Semcomp 18
Flask - Backend com Python - Semcomp 18Flask - Backend com Python - Semcomp 18
Flask - Backend com Python - Semcomp 18
 
Perl Web Client
Perl Web ClientPerl Web Client
Perl Web Client
 
Powershell alias
Powershell aliasPowershell alias
Powershell alias
 
Nubilus Perl
Nubilus PerlNubilus Perl
Nubilus Perl
 
dotCloud and go
dotCloud and godotCloud and go
dotCloud and go
 
Building Web Services with Zend Framework (PHP Benelux meeting 20100713 Vliss...
Building Web Services with Zend Framework (PHP Benelux meeting 20100713 Vliss...Building Web Services with Zend Framework (PHP Benelux meeting 20100713 Vliss...
Building Web Services with Zend Framework (PHP Benelux meeting 20100713 Vliss...
 
Ansible inside
Ansible insideAnsible inside
Ansible inside
 
Learning Dtrace
Learning DtraceLearning Dtrace
Learning Dtrace
 

Andere mochten auch

SEV090114FshBTS_Lo
SEV090114FshBTS_LoSEV090114FshBTS_Lo
SEV090114FshBTS_Lo
Jill Amos
 

Andere mochten auch (20)

Zurich Presentation
Zurich PresentationZurich Presentation
Zurich Presentation
 
Lee Aase Social Media Presentation - Spring 2010
Lee Aase Social Media Presentation - Spring 2010Lee Aase Social Media Presentation - Spring 2010
Lee Aase Social Media Presentation - Spring 2010
 
Social Media with a Star Trek Flair
Social Media with a Star Trek FlairSocial Media with a Star Trek Flair
Social Media with a Star Trek Flair
 
Entrepreneurs: Building for Smart & Sustainable Growth
Entrepreneurs: Building for Smart & Sustainable GrowthEntrepreneurs: Building for Smart & Sustainable Growth
Entrepreneurs: Building for Smart & Sustainable Growth
 
Thinkspace Twitter Sammamish Chamber
Thinkspace Twitter Sammamish ChamberThinkspace Twitter Sammamish Chamber
Thinkspace Twitter Sammamish Chamber
 
Samyak Veera
Samyak VeeraSamyak Veera
Samyak Veera
 
Sass - Making CSS fun again.
Sass - Making CSS fun again.Sass - Making CSS fun again.
Sass - Making CSS fun again.
 
Unit 3 Writing to communicate ideas of others
Unit 3 Writing to communicate ideas of othersUnit 3 Writing to communicate ideas of others
Unit 3 Writing to communicate ideas of others
 
Podcasting 108
Podcasting 108Podcasting 108
Podcasting 108
 
Maori Law
Maori Law Maori Law
Maori Law
 
Best Buy Web 2.0
Best Buy Web 2.0Best Buy Web 2.0
Best Buy Web 2.0
 
SEV090114FshBTS_Lo
SEV090114FshBTS_LoSEV090114FshBTS_Lo
SEV090114FshBTS_Lo
 
Social Media in City and County Government
Social Media in City and County GovernmentSocial Media in City and County Government
Social Media in City and County Government
 
Going Viral against HIV and STIs
Going Viral against HIV and STIsGoing Viral against HIV and STIs
Going Viral against HIV and STIs
 
HR Executive Forum Presentation
HR Executive Forum PresentationHR Executive Forum Presentation
HR Executive Forum Presentation
 
Facebook in Media Relations
Facebook in Media RelationsFacebook in Media Relations
Facebook in Media Relations
 
The Internet and Patient/Provider Partnerships
The Internet and Patient/Provider PartnershipsThe Internet and Patient/Provider Partnerships
The Internet and Patient/Provider Partnerships
 
14000sq.ft Office on Lease in Westgate at Prahladnagar-SG Highway
14000sq.ft Office on Lease in Westgate at Prahladnagar-SG Highway14000sq.ft Office on Lease in Westgate at Prahladnagar-SG Highway
14000sq.ft Office on Lease in Westgate at Prahladnagar-SG Highway
 
Everything I Screwed Up While Scaling Up - By Andy Liu
Everything I Screwed Up While Scaling Up - By Andy LiuEverything I Screwed Up While Scaling Up - By Andy Liu
Everything I Screwed Up While Scaling Up - By Andy Liu
 
Reshape09
Reshape09Reshape09
Reshape09
 

Ähnlich wie Power shell examples_v4

Phpne august-2012-symfony-components-friends
Phpne august-2012-symfony-components-friendsPhpne august-2012-symfony-components-friends
Phpne august-2012-symfony-components-friends
Michael Peacock
 
VPN Access Runbook
VPN Access RunbookVPN Access Runbook
VPN Access Runbook
Taha Shakeel
 
ZendCon2010 The Doctrine Project
ZendCon2010 The Doctrine ProjectZendCon2010 The Doctrine Project
ZendCon2010 The Doctrine Project
Jonathan Wage
 
symfony on action - WebTech 207
symfony on action - WebTech 207symfony on action - WebTech 207
symfony on action - WebTech 207
patter
 

Ähnlich wie Power shell examples_v4 (20)

WINDOWS ADMINISTRATION AND WORKING WITH OBJECTS : PowerShell ISE
WINDOWS ADMINISTRATION AND WORKING WITH OBJECTS : PowerShell ISEWINDOWS ADMINISTRATION AND WORKING WITH OBJECTS : PowerShell ISE
WINDOWS ADMINISTRATION AND WORKING WITH OBJECTS : PowerShell ISE
 
Sql storeprocedure
Sql storeprocedureSql storeprocedure
Sql storeprocedure
 
Phpne august-2012-symfony-components-friends
Phpne august-2012-symfony-components-friendsPhpne august-2012-symfony-components-friends
Phpne august-2012-symfony-components-friends
 
VPN Access Runbook
VPN Access RunbookVPN Access Runbook
VPN Access Runbook
 
Symfony2 from the Trenches
Symfony2 from the TrenchesSymfony2 from the Trenches
Symfony2 from the Trenches
 
CodeIgniter PHP MVC Framework
CodeIgniter PHP MVC FrameworkCodeIgniter PHP MVC Framework
CodeIgniter PHP MVC Framework
 
ZendCon2010 The Doctrine Project
ZendCon2010 The Doctrine ProjectZendCon2010 The Doctrine Project
ZendCon2010 The Doctrine Project
 
Local SQLite Database with Node for beginners
Local SQLite Database with Node for beginnersLocal SQLite Database with Node for beginners
Local SQLite Database with Node for beginners
 
Better Testing With PHP Unit
Better Testing With PHP UnitBetter Testing With PHP Unit
Better Testing With PHP Unit
 
Zend Framework 1.9 Setup & Using Zend_Tool
Zend Framework 1.9 Setup & Using Zend_ToolZend Framework 1.9 Setup & Using Zend_Tool
Zend Framework 1.9 Setup & Using Zend_Tool
 
Symfony2 - from the trenches
Symfony2 - from the trenchesSymfony2 - from the trenches
Symfony2 - from the trenches
 
MongoDB World 2019: Creating a Self-healing MongoDB Replica Set on GCP Comput...
MongoDB World 2019: Creating a Self-healing MongoDB Replica Set on GCP Comput...MongoDB World 2019: Creating a Self-healing MongoDB Replica Set on GCP Comput...
MongoDB World 2019: Creating a Self-healing MongoDB Replica Set on GCP Comput...
 
WordPress Plugin development
WordPress Plugin developmentWordPress Plugin development
WordPress Plugin development
 
Thymeleaf and Spring Controllers.ppt
Thymeleaf and Spring Controllers.pptThymeleaf and Spring Controllers.ppt
Thymeleaf and Spring Controllers.ppt
 
SharePoint Administration with PowerShell
SharePoint Administration with PowerShellSharePoint Administration with PowerShell
SharePoint Administration with PowerShell
 
関西PHP勉強会 php5.4つまみぐい
関西PHP勉強会 php5.4つまみぐい関西PHP勉強会 php5.4つまみぐい
関西PHP勉強会 php5.4つまみぐい
 
PowerShell-2
PowerShell-2PowerShell-2
PowerShell-2
 
SCasia 2018 MSFT hands on session for Azure Batch AI
SCasia 2018 MSFT hands on session for Azure Batch AISCasia 2018 MSFT hands on session for Azure Batch AI
SCasia 2018 MSFT hands on session for Azure Batch AI
 
Kicking off with Zend Expressive and Doctrine ORM (PHP Srbija 2017)
Kicking off with Zend Expressive and Doctrine ORM (PHP Srbija 2017)Kicking off with Zend Expressive and Doctrine ORM (PHP Srbija 2017)
Kicking off with Zend Expressive and Doctrine ORM (PHP Srbija 2017)
 
symfony on action - WebTech 207
symfony on action - WebTech 207symfony on action - WebTech 207
symfony on action - WebTech 207
 

Kürzlich hochgeladen

Artificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsArtificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and Myths
Joaquim Jorge
 
Histor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slideHistor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slide
vu2urc
 

Kürzlich hochgeladen (20)

Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
 
A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)
 
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
 
[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf
 
Breaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountBreaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path Mount
 
Data Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonData Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt Robison
 
A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024
 
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationFrom Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
 
Boost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityBoost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivity
 
The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024
 
Factors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptxFactors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptx
 
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
 
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
 
🐬 The future of MySQL is Postgres 🐘
🐬  The future of MySQL is Postgres   🐘🐬  The future of MySQL is Postgres   🐘
🐬 The future of MySQL is Postgres 🐘
 
Artificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsArtificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and Myths
 
Histor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slideHistor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slide
 
Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...
 
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
 
Real Time Object Detection Using Open CV
Real Time Object Detection Using Open CVReal Time Object Detection Using Open CV
Real Time Object Detection Using Open CV
 
2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...
 

Power shell examples_v4

  • 1. WINDOWS POWERSHELL 4.0 EXAMPLES Created by http://powershellmagazine.com Job scheduling allows you to schedule execution of a PowerShell background job for a later time. First thing you do is create a job trigger. This defines when the job will execute. Then you use the Register-ScheduledJob cmdlet to actually register the job on the system. In the following example, every day at 3am we back up our important files: $trigger = New-JobTrigger -Daily -At 3am Register-ScheduledJob -Name DailyBackup -Trigger $trigger -ScriptBlock {Copy-Item c:ImportantFiles d:Backup$((Get-Date).ToFileTime()) -Recurse -Force -PassThru} Once the trigger has fired and the job has run, you can work with it the same way you do with regular background jobs: Get-Job -Name DailyBackup | Receive-Job You can start a scheduled job manually, rather than waiting for the trigger to fire: Start-Job -DefinitionName DailyBackup The RunNow parameter for Register-ScheduledJob and Set-ScheduledJob eliminates the need to set an immediate start date and time for jobs by using the -Trigger parameter: Register-ScheduledJob -Name Backup -ScriptBlock {Copy-Item c:ImportantFiles d: Backup$((Get-Date).ToFileTime()) -Recurse -Force -PassThru} -RunNow In PowerShell 4.0, the PipelineVariable lets you save the results of a piped command (or part of a piped command) as a variable that can be passed through the remainder of the pipeline. Its alias is "pv". Get-ChildItem *.ps1 -pv a | Get-Acl | foreach {"{0} size is {1}" -f $a.Name, $a.length} How to schedule a job PipelineVariable Common Parameter Windows PowerShell 4.0 supports method invocation using dynamic method names. $fn = "ToString" "Hello".ToString() "Hello".$fn() "Hello".("To" + "String")()   #Select a method from an array: $index = 1; "Hello".(@("ToUpper", "ToLower")[$index])() Dynamic method invocation Starting with PowerShell 4.0, we can specify that a script requires administrative privileges by including a #Requires statement with the -RunAsAdministrator switch parameter. #Requires -RunAsAdministrator #Requires -RunAsAdministrator There is no built-in cmdlet to generate a password, but we can leverage a vast number of .NET Framework classes. System.Web.Security.Membership class has a static method GeneratePassword(). First, we need to load an assembly containing this class, and then we use GeneratePassword() to define password length and a number of non- alphanumeric characters. $Assembly = Add-Type -AssemblyName System.Web [System.Web.Security.Membership]::GeneratePassword(8,3) How do we know all that? With a little help from the Get-Member cmdlet (and simplified where syntax): [System.Web.Security.Membership] | Get-Member -MemberType method -Static| where name -match password How to generate complex password The Test-NetConnection cmdlet (available on Windows 8.1 / Server 2012 R2) displays diagnostic information for a connection. #Returns detailed diagnostic information for microsoft.com Test-NetConnection -ComputerName microsoft.com -InformationLevel Detailed #Returns a Boolean value based on connectivity status Test-NetConnection -ComputerName microsoft.com -Port 80 -InformationLevel Quiet Diagnosing network connectivity The new Get-FileHash cmdlet computes the hash value for a file. There are multiple hash algorithms supported with this cmdlet. Get-FileHash C:downloadsWindowsOS.iso -Algorithm SHA384 Working with a file hash
  • 2. WINDOWS POWERSHELL 4.0 EXAMPLES Created by http://powershellmagazine.com The Invoke-WebRequest cmdlet parses the response, exposing collections of forms, links, images, and other significant HTML elements. The following example returns all the URLs from a webpage: $iwr = Invoke-WebRequest http://blogs.msdn.com/b/powershell $iwr.Links The next example returns an RSS feed from the PowerShell team blog: $irm = Invoke-RestMethod blogs.msdn.com/b/powershell/rss.aspx $irm | Select-Object PubDate, Title If you, for example, need to execute one of the -PSSession cmdlets using alternate credentials you must specify the credentials for the Credential parameter every time you call the command. In PowerShell 3.0 and later, we can supply alternate credentials by using new $PSDefaultParameterValues preference variable. For more information, see about_Parameters_Default_Values. $PSDefaultParameterValues = @{'*-PSSession:Credential'=Get-Credential} How to parse webpage elements The Invoke-RestMethod cmdlet sends an HTTP(S) request to a REST-compliant web service. You can use it to consume data exposed by, for example, the OData service for TechEd North America 2014 content. Put information about TechEd NA 2014 sessions into a $sessions variable. Let's iterate through that collection of XML elements and create custom PowerShell objects using [PSCustomObject]. Pipe the output to an Out- GridView command specifying the PassThru parameter to send selected items from the interactive window down the pipeline, as input to an Export-Csv command. (While you are in a grid view window, try to filter only PowerShell Hands-on Labs, for example). If you have Excel installed the last command opens a CSV file in Excel. $sessions = Invoke-RestMethod https://odata.eventpointdata.com/tena2014/ Sessions.svc/Sessions $sessions | ForEach-Object { $properties = $_.content.properties [PSCustomObject]@{ Code = $properties.Code Day = $properties.Day_US StartTime = $properties.Start_US EndTime = $properties.Finish_US Speaker = $properties.PrimarySpeaker Title = $properties.Title Abstract = $properties.Abstract } } | Out-GridView -PassThru | Export-Csv $env:TEMPsessions.csv -NoTypeInformation Invoke-Item $env:TEMPsessions.csv How to fetch data exposed by OData services How to set custom default values for the parameters In Windows PowerShell 3.0, Save-Help worked only for modules that are installed on the local computer. PowerShell 4.0 enables Save-Help to work for remote modules. Use Invoke-Command to get the remote module and call Save-Help: $m = Invoke-Command -ComputerName RemoteServer -ScriptBlock { Get Module  - Name DhcpServer -ListAvailable } Save-Help -Module $m -DestinationPath C:SavedHelp Use a PSSession to get the remote module and call Save-Help: $s = New-PSSession -ComputerName RemoteServer $m = Get-Module -PSSession $s -Name DhcpServer -ListAvailable Save-Help -Module $m -DestinationPath C:SavedHelp Use a CimSession to get the remote module and call Save-Help: $c = New-CimSession -ComputerName RemoteServer $m = Get-Module -CimSession $c -Name DhcpServer -ListAvailable Save-Help -Module $m -DestinationPath C:SavedHelp Save-Help In PowerShell 2.0, if you had some local variable that you wanted to use when executing a script block remotely, you had to do something like: $localVar = 42 Invoke-Command -ComputerName Server 1 { param($localVar) echo $localVar } - ArgumentList $localVar In PowerShell 3.0 and later, you can use Using scope (prefix variable name with $using:): Invoke-Command -ComputerName Server1 { echo $using:localVar } How to access local variables in a remote session