Merge pull request #1576 from PowerShell/migreene

PowerShellGet demo and "getting started" doc changes
This commit is contained in:
Dongbo Wang 2016-08-05 10:59:54 -07:00 committed by GitHub
commit 70aea51cb1
4 changed files with 220 additions and 7 deletions

View File

@ -31,16 +31,25 @@ Uninstall-Script Fabrikam-Script -Verbose
#endregion
#region Using PowerShellGet find and install other demos
#region Using PowerShellGet find and install modules
# Value: equivalent of pypi
# Look for all the modules we'll be demoing today
Find-Module -Tag 'PowerShellCore_Demo'
# Save module to specified location
Save-Module -Tag 'PowerShellCore_Demo' -Path /tmp
# Pipe this to Install-Module to install them
Find-Module -Tag 'PowerShellCore_Demo' | Install-Module -Verbose
Get-InstalledModule
# Update all installed modules
Update-Module
#endregion
#region Using PowerShellGet with tags
# Look for all the scripts we'll be demoing today
Find-Script -Tag 'PowerShellCore_Demo'
@ -50,3 +59,19 @@ Find-Script -Tag 'PowerShellCore_Demo' | Install-Script -Verbose
Get-InstalledScript
#endregion
#region Working with PowerShellGet repositories
# List available PS repositories
Get-PSRepository
# Register a new private feed
Register-PSRepository -Name "myPrivateGallery" SourceLocation "https://www.myget.org/F/powershellgetdemo/api/v2" -InstallationPolicy Trusted
# Change the trust level for a repositories
Set-PSRepository -Name "myPrivateGallery" -InstallationPolicy "Untrusted"
# Remove a private feed
Unregister-PSRepository -Name "myPrivateGallery"
#endregion

View File

@ -0,0 +1,61 @@
How to Create and Run PowerShell Scripts
====
You can combine a series of commands in a text file and save it with the file extension '.ps1', and the file will become a PowerShell script.
This would begin by opening your favorite text editor and pasting in the following example.
``` PowerShell
# Script to return current IPv4 addresses on a Linux or MacOS host
$ipInfo = ifconfig | Select-String 'inet'
$ipInfo = [regex]::matches($ipInfo,"addr:\b(?:\d{1,3}\.){3}\d{1,3}\b") | ForEach-Object value
foreach ($ip in $ipInfo) {
$ip.Replace('addr:','')
}
```
Then save the file to something memorable, such as .\NetIP.ps1.
In the future when you need to get the IP addresses for the node, you can simplify this task by executing the script.
``` PowerShell
PS> .\NetIP.ps1
10.0.0.1
127.0.0.1
```
You can accomplish this same task on Windows.
```PowerShell
# One line script to return current IPv4 addresses on a Windows host
Get-NetIPAddress | Where-Object {$_.AddressFamily -eq 'IPv4'} | ForEach-Object IPAddress
```
As before, save the file as .\NetIP.ps1 and execute within a PowerShell environment.
Note: If you are using Windows, make sure you set the PowerShell's execution policy to "RemoteSigned" in this case.
See [Running PowerShell Scripts Is as Easy as 1-2-3](run-ps) for more details.
```PowerShell
PS C:\> NetIP.ps1
127.0.0.1
10.0.0.1
```
Creating a script that can accomplish the same task on multiple operating systems
----
If you would like to author one script that will return the IP address across Linux, MacOS, or Windows, you could accomplish this using an IF statement.
```PowerShell
# Script to return current IPv4 addresses for Linux, MacOS, or Windows
$IP = if ($IsLinux -or $IsOSX) {
$ipInfo = ifconfig | Select-String 'inet'
$ipInfo = [regex]::matches($ipInfo,"addr:\b(?:\d{1,3}\.){3}\d{1,3}\b") | ForEach-Object value
foreach ($ip in $ipInfo) {
$ip.Replace('addr:','')
}
}
else {
Get-NetIPAddress | Where-Object {$_.AddressFamily -eq 'IPv4'} | ForEach-Object IPAddress
}
# Remove loopback address from output regardless of platform
$IP | Where-Object {$_ -ne '127.0.0.1'}
```
[run-ps]:http://windowsitpro.com/powershell/running-powershell-scripts-easy-1-2-3

View File

@ -259,15 +259,18 @@ Mode LastWriteTime Length Name
-a---- 5/16/2016 1:15 PM 32972 test.log
```
How to Create and Run PowerShell scripts
Working with Objects
----
- You can use ISE, Visual Studio Code or your favorite editor to create a PowerShell script and save the script with a .ps1 file extension (for example, helloworld.ps1)
- To run the script, cd to your current folder and type ./yourscript.ps1 (for example, ./helloworld.ps1).
When cmdlets are executed in PowerShell, the output is an Object, as opposed to just text.
This provides the ability to store a lot of information
Note: If you are using Windows, make sure you set the PowerShell's execution policy to "RemoteSigned" in this case.
See [Running PowerShell Scripts Is as Easy as 1-2-3] [run-ps] for more details.
Discovering available Methods
----
PowerShell Functions
----
[run-ps]:http://windowsitpro.com/powershell/running-powershell-scripts-easy-1-2-3
Recommended Training and Reading
----

View File

@ -0,0 +1,124 @@
Working with PowerShell Objects
====
When cmdlets are executed in PowerShell, the output is an Object, as opposed to only returning text.
This provides the ability to store information as properties.
As a result, handling large amounts of data and getting only specific properties is a trivial task.
As a simple example, the following function retrieves information about storage Devices on a Linux or MacOS operating system platform.
This is accomplished by parsing the output of an existing command, *parted -l* in administrative context, and creating an object from the raw text by using the *New-Object* cmdlet.
```PowerShell
Function Get-DiskInfo {
$disks = sudo parted -l | Select-String "Disk /dev/sd*" -Context 1,0
$diskinfo = @()
foreach ($disk in $disks) {
$diskline1 = $disk.ToString().Split("`n")[0].ToString().Replace(' Model: ','')
$diskline2 = $disk.ToString().Split("`n")[1].ToString().Replace('> Disk ','')
$i = New-Object psobject -Property @{'Friendly Name' = $diskline1; Device=$diskline2.Split(': ')[0]; 'Total Size'=$diskline2.Split(':')[1]}
$diskinfo += $i
}
$diskinfo
}
```
Execute the function and store the results as a variable.
Now retrieve the value of the variable.
The results are formatted as a table with the default view.
*Note: in this example, the disks are virtual disks in a Microsoft Azure virtual machine.*
```PowerShell
PS /home/psuser> $d = Get-DiskInfo
[sudo] password for psuser:
PS /home/psuser> $d
Friendly Name Total Size Device
------------- ---------- ------
Msft Virtual Disk (scsi) 31.5GB /dev/sda
Msft Virtual Disk (scsi) 145GB /dev/sdb
```
Passing the variable down the pipeline to *Get-Member* reveals available methods and properties.
This is because the value of *$d* is not just text output.
The value is actually an array of .Net objects with methods and properties.
The properties include Device, Friendly Name, and Total Size.
```PowerShell
PS /home/psuser> $d | Get-Member
TypeName: System.Management.Automation.PSCustomObject
Name MemberType Definition
---- ---------- ----------
Equals Method bool Equals(System.Object obj)
GetHashCode Method int GetHashCode()
GetType Method type GetType()
ToString Method string ToString()
Device NoteProperty string Device=/dev/sda
Friendly Name NoteProperty string Friendly Name=Msft Virtual Disk (scsi)
Total Size NoteProperty string Total Size= 31.5GB
```
To confirm, we can call the GetType() method interactively from the console.
```PowerShell
PS /home/psuser> $d.GetType()
IsPublic IsSerial Name BaseType
-------- -------- ---- --------
True True Object[] System.Array
```
To index in to the array and return only specific objects, use the square brackets.
```PowerShell
PS /home/psuser> $d[0]
Friendly Name Total Size Device
------------- ---------- ------
Msft Virtual Disk (scsi) 31.5GB /dev/sda
PS /home/psuser> $d[0].GetType()
IsPublic IsSerial Name BaseType
-------- -------- ---- --------
True False PSCustomObject System.Object
```
To return a specific property, the property name can be called interactively from the console.
```PowerShell
PS /home/psuser> $d.Device
/dev/sda
/dev/sdb
```
To output a view of the information other than default, such as a view with only specific properties selected, pass the value to the *Select-Object* cmdlet.
```PowerShell
PS /home/psuser> $d | Select-Object Device, 'Total Size'
Device Total Size
------ ----------
/dev/sda 31.5GB
/dev/sdb 145GB
```
Finally, the example below demonstrates use of the *ForEach-Object* cmdlet to iterate through the array and manipulate the value of a specific property of each object.
In this case the Total Size property, which was given in Gigabytes, is changed to Megabytes.
Alternatively, index in to a position in the array as shown below in the third example.
```PowerShell
PS /home/psuser> $d | ForEach-Object 'Total Size'
31.5GB
145GB
PS /home/psuser> $d | ForEach-Object {$_.'Total Size' / 1MB}
32256
148480
PS /home/psuser> $d[1].'Total Size' / 1MB
148480
```