Powershellbeginner

Udemy course powershellbeginner

batch files and vbscript are no more used
powershell is based on .NET

  • v1 started 2005 , microsoft exchange first big adopeter
  • v2 in 2009
  • v3 in 2011
PS C:\Users\Administrator> $PSVersionTable.psversion

Major  Minor  Build  Revision
-----  -----  -----  --------
4      0      -1     -1

powershell v3.0 it is an update of windows not another program , windows framework 3.0

Buffer size hight 9999 so we see old output

first of all it is convenient update the help command

update-help

the command of help is

get-help

Execution policy

view the exec policy

PS C:\Users\Administrator> Get-ExecutionPolicy
Restricted

change the policy

PS C:\Users\Administrator> Set-ExecutionPolicy allsigned

Execution Policy Change
The execution policy helps protect you from scripts that you do not trust. Changing the execution policy might expose
you to the security risks described in the about_Execution_Policies help topic at
http://go.microsoft.com/fwlink/?LinkID=135170. Do you want to change the execution policy?
[Y] Yes  [N] No  [S] Suspend  [?] Help (default is "Y"): y

in this way you can run only script previously signed

instead is convenient set in this other way

PS C:\Users\Administrator> Set-ExecutionPolicy unrestricted

Execution Policy Change
The execution policy helps protect you from scripts that you do not trust. Changing the execution policy might expose
you to the security risks described in the about_Execution_Policies help topic at
http://go.microsoft.com/fwlink/?LinkID=135170. Do you want to change the execution policy?
[Y] Yes  [N] No  [S] Suspend  [?] Help (default is "Y"): y
PS C:\Users\Administrator> Get-ExecutionPolicy
Unrestricted

Profile

the history of powershell is 64k
if you want move the cursor and keep ctrl it moves using words and not letter

the ISE is a very useful editor for powershell, keep in mind that it use a different profile from powershell

PS C:\Users\Administrator> $profile
C:\Users\Administrator\Documents\WindowsPowerShell\Microsoft.PowerShellISE_profile.ps1

PS C:\Users\Administrator> $profile
C:\Users\Administrator\Documents\WindowsPowerShell\Microsoft.PowerShell_profile.ps1

the profile usually don't exist , you need to create
to works it is necessary Unrestricted for the execution policy, is you set once it remains also if you close and open the console

if you write this in the profile

Set-Location c:\
Set-Alias bob dir
$common_directory = 'c:\Windows'
  • the starting directoy will be c:\ instead of the c:\users\username
  • you can have bob like alias of dir
  • if you write $common_directory you'll get c:\Windows

Section 5 - Cmdlet

it gives all the command let available

Get-Command

it gives a list of all the verb (actions) that you can use if you want to create a new cmdlet

Get-Verb

it gives back all the cmdlet that start with Set

PS C:\Users\Administrator> Get-Command -Verb set

CommandType     Name                                               ModuleName
-----------     ----                                               ----------
Function        Set-BCAuthentication                               BranchCache
Function        Set-BCCache                                        BranchCache
Function        Set-BCDataCacheEntryMaxAge                         BranchCache
Function        Set-BCMinSMBLatency                                BranchCache
Function        Set-BCSecretKey                                    BranchCache
Function        Set-ClusteredScheduledTask                         ScheduledTasks
Function        Set-DAClientExperienceConfiguration                DirectAccessClientComponents
Function        Set-DAEntryPointTableItem                          DirectAccessClientComponents
Function        Set-Disk                                           Storage
Function        Set-DisplayResolution                              ServerCore

it gives back the noun of the service

PS C:\Users\Administrator> Get-Command -Noun Service

CommandType     Name                                               ModuleName
-----------     ----                                               ----------
Cmdlet          Get-Service                                        Microsoft.PowerShell.Management
Cmdlet          New-Service                                        Microsoft.PowerShell.Management
Cmdlet          Restart-Service                                    Microsoft.PowerShell.Management
Cmdlet          Resume-Service                                     Microsoft.PowerShell.Management

for example Get-Service ,

it gives back some examples

PS C:\Users\Administrator> Get-Help Get-Service -Example

NAME
    Get-Service

SYNOPSIS
    Gets the services on a local or remote computer.

    -------------------------- EXAMPLE 1 --------------------------

if it is don't give you give back examples you need to run update-help

list all the alias

PS C:\Users\Administrator> Get-Alias

CommandType     Name                                               ModuleName
-----------     ----                                               ----------
Alias           % -> ForEach-Object
Alias           ? -> Where-Object
Alias           ac -> Add-Content
Alias           asnp -> Add-PSSnapin
Alias           cat -> Get-Content
Alias           cd -> Set-Location
Alias           chdir -> Set-Location

create an alias and export to a text

PS C:\Users\Administrator> Set-Alias lista dir
PS C:\Users\Administrator> Export-Alias -Path myaliases.txt -name lista

Section 6 Variables

Poweshell can change the type of a variable depends from its value

variable

set a variable with a type

PS C:\Users\Administrator> [string]$x= 'my string'
PS C:\Users\Administrator> $x.GetType()

IsPublic IsSerial Name                                     BaseType
-------- -------- ----                                     --------
True     True     String                                   System.Object

remove a variable

PS C:\Users\Administrator> $x
my string
PS C:\Users\Administrator> $x = $null
PS C:\Users\Administrator> $x

PS C:\Users\Administrator>

boolean variables

PS C:\Users\Administrator> $boolean_true = $true
PS C:\Users\Administrator> $boolean_true
True
PS C:\Users\Administrator> $boolean_false = $false
PS C:\Users\Administrator> $boolean_false
False
PS C:\Users\Administrator> $boolean_true -eq $true
True
PS C:\Users\Administrator> $boolean_true -eq $false
False
PS C:\Users\Administrator>

getType function

PS C:\Users\Administrator> [bool]$is_in_exstince = $true
PS C:\Users\Administrator> $is_in_exstince
True
PS C:\Users\Administrator> $is_in_exstince.GetType()

IsPublic IsSerial Name                                     BaseType
-------- -------- ----                                     --------
True     True     Boolean                                  System.ValueType

PS C:\Users\Administrator> $x='alla'
PS C:\Users\Administrator> $x.GetType()

IsPublic IsSerial Name                                     BaseType
-------- -------- ----                                     --------
True     True     String                                   System.Object

single and double quote evaluation (it is like in puppet)

PS C:\Users\Administrator>
PS C:\Users\Administrator> $x = '1234'
PS C:\Users\Administrator> $x
1234
PS C:\Users\Administrator> $double_quote = "this is a string - $x"
PS C:\Users\Administrator> $single_quote = 'this is a string - $x'
PS C:\Users\Administrator> $double_quote
this is a string - 1234
PS C:\Users\Administrator> $single_quote
this is a string - $x

string and integer concatenation sum

PS C:\Users\Administrator> [int]$integer_one = 1
PS C:\Users\Administrator> $integer_two = 2
PS C:\Users\Administrator> $integer_oner + $integer_two
2
PS C:\Users\Administrator> $string_one = '1'
PS C:\Users\Administrator> $string_two = '2'
PS C:\Users\Administrator> $string_two + $string_two
22
PS C:\Users\Administrator> $string_one + $string_two
12
array

an array can also contains other arrays and mixed values

declare an array

PS C:\Users\Administrator> $array = @(1,'stringvariable',5)
PS C:\Users\Administrator> $array
1
stringvariable
5
PS C:\Users\Administrator> $array.GetType()

IsPublic IsSerial Name                                     BaseType
-------- -------- ----                                     --------
True     True     Object[]                                 System.Array

PS C:\Users\Administrator> $array = @()
PS C:\Users\Administrator> $array
PS C:\Users\Administrator>

add elements to an array

PS C:\Users\Administrator> $array +=3
PS C:\Users\Administrator> $array
3
PS C:\Users\Administrator> $array +=7
PS C:\Users\Administrator> $array +='tttt'
PS C:\Users\Administrator> $array
3
7
tttt
PS C:\Users\Administrator>

arrays index

PS C:\Users\Administrator> $array[0]
3
PS C:\Users\Administrator> $array[2]
tttt
PS C:\Users\Administrator> $array.Count
3
PS C:\Users\Administrator>
hash table

it doesn't keep the order

PS C:\Users\Administrator> [hashtable]$hash_table = @{'keyA'='valueA1';'keyB'='valueB2'}
PS C:\Users\Administrator> $hash_table

Name                           Value
----                           -----
keyB                           valueB2
keyA                           valueA1

get , add, change, remove items

PS C:\Users\Administrator> $hash_table.get_item('keyA')
valueA1
PS C:\Users\Administrator> $hash_table.add('key3','valueC')
PS C:\Users\Administrator> $hash_table

Name                           Value
----                           -----
keyA                           valueA1
key3                           valueC
keyB                           valueB2

PS C:\Users\Administrator> $hash_table.set_item('keyA','AAAAAA')
PS C:\Users\Administrator> $hash_table

Name                           Value
----                           -----
keyA                           AAAAAA
key3                           valueC
keyB                           valueB2

PS C:\Users\Administrator> $hash_table.Remove(('key3')
>> $hash_table
PS C:\Users\Administrator>

section 7 condicional logic

if else

$x = 10
if ($x -eq 1) {
    Write-Host 'x is equal to one'
} else {
    Write-Host 'x is equal to something else'
}

if ($x -ne 1) {
    Write-Host 'x is not equal to one'
}

$y= $null
if ($y) {
    Write-Host 'y is equal to something other than null or boolean false'
}else {
    Write-Host 'y is equal to null or boolean false'
}
$a = 3
switch ($a) {
    1 {"the color is red"}
    2 {"the color is blue"}
    3 {"the color is orange"}
    4 {"the color is green"}
    default {"the color is not determined"}
}

#wildcard means start by
# it didn't work for me
$a = "ddd"
switch -wildcard($a) {
    "a" {"the color is red"}
    "b" {"the color is blue"}
    "c" {"the color is orange"}
    "d" {"the color is green"}
    default {"the color is not determined"}
}

Section 8 Loop

  • For loop: you know how many elements you have
  • ForEach loop: you don't know how many elements you have, it is a bit slower respect for loop
  • do while: something needs to happen to interrupt the loop

For loop, it prints from 0 to 5 included

for ($i = 0; $i -le 5; $i++) {
    write-host $i
}
$cars= @('peogeout','fiat','ferrari')
$cars_count=$cars.Count
for ($i = 0; $i -lt $cars_count; $i++) {
    write-host $i
    Write-Host $cars[$i]
}

For each

$cars= @('peogeout','fiat','ferrari')
foreach ($item in $cars) {
    Write-Host $item
}

do while

$x=0
do {
    Write-Host $x
    $x+=1
} while ($x -le 5)

the get process didn't work on my environment

do {

} while (Get-Process notepad -ErrorAction SilentlyContinue)
$strtime= get-date
write-host "the applicatio notepada was closed $strtime"

break construct

$array=@(1,2,3,4)
foreach ($item in $array) {
    Write-Host $item
    if ($item -eq 3) {
        break
    }
}

if you have two loops nested and you exit you can use "break 2"

it will print only 3

$array=@(1,2,3,4,5)
for ($i=0; $i -lt $array.count; $i++){
    if ($array[$i] -ne 3 ){
        continue
    }
    echo $array[$i]
}
$text_file =@('file1.txt','file2.txt','file3.txt')
foreach ($file in $text_file) {
    if((get-content $file) -contains 'this is content file2' {
        continue
    }
    Write-Host $file
}

Section 9 Object and the pipeline

object is a variable, it is the father variable.
object have methods and properties

get all the service running or stoppend on the machines

PS C:\Users\Administrator> Get-Service

Status   Name               DisplayName
------   ----               -----------
Stopped  AeLookupSvc        Application Experience
Stopped  ALG                Application Layer Gateway Service
Stopped  AppIDSvc           Application Identity
Stopped  Appinfo            Application Information
Stopped  AppMgmt            Application Management
Stopped  AppReadiness       App Readiness
Stopped  AppXSvc            AppX Deployment Service (AppXSVC)
Stopped  AudioEndpointBu... Windows Audio Endpoint Builder
Stopped  Audiosrv           Windows Audio
Running  AWSLiteAgent       AWS Lite Guest Agent
Running  BFE                Base Filtering Engine

if you pipe with the member it will expand the other fields of the obj returned

PS C:\Users\Administrator> Get-Service | Get-Member

   TypeName: System.ServiceProcess.ServiceController

Name                      MemberType    Definition
----                      ----------    ----------
Name                      AliasProperty Name = ServiceName
RequiredServices          AliasProperty RequiredServices = ServicesDependedOn
Disposed                  Event         System.EventHandler Disposed(System.Object, System.EventArgs)
Close                     Method        void Close()
Continue                  Method        void Continue()
CreateObjRef              Method        System.Runtime.Remoting.ObjRef CreateObjRef(type requestedType)
Dispose                   Method        void Dispose(), void IDisposable.Dispose()
Equals                    Method        bool Equals(System.Object obj)
ExecuteCommand            Method        void ExecuteCommand(int command)

wrap the obj

PS C:\Users\Administrator> $service= Get-Service wuauserv
PS C:\Users\Administrator> $service

Status   Name               DisplayName
------   ----               -----------
Stopped  wuauserv           Windows Update

give the expand list of properties not the summary

PS C:\Users\Administrator> $service | Select-Object *

Name                : wuauserv
RequiredServices    : {rpcss}
CanPauseAndContinue : False
CanShutdown         : False
CanStop             : False
DisplayName         : Windows Update
DependentServices   : {}
MachineName         : .
ServiceName         : wuauserv
ServicesDependedOn  : {rpcss}
ServiceHandle       : SafeServiceHandle
Status              : Stopped
ServiceType         : Win32ShareProcess
Site                :
Container           :

start and stop, note that the variable is a snapshot in one moment it is not updated

PS C:\Users\Administrator> $service.Status
Stopped

PS C:\Users\Administrator> $service.Start()
PS C:\Users\Administrator> $service.Status
Stopped
PS C:\Users\Administrator> Get-Service wuauserv

Status   Name               DisplayName
------   ----               -----------
Running  wuauserv           Windows Update

PS C:\Users\Administrator>

compare object show the differences between two array using the arrows

$array1 = @(1,2,3,4,5)
$array2 = @(1,6,3,8,9)
Compare-Object $array1 $array2

                               InputObject SideIndicator                             
                               ----------- -------------                             
                                         6 =>                                        
                                         8 =>                                        
                                         9 =>                                        
                                         2 <=                                        
                                         4 <=                                        
                                         5 <=

if you add the option to include equal it shows also the equals
PS C:\Users\Administrator> $array1 = @(1,2,3,4,5)
$array2 = @(1,3,6,8,9)
Compare-Object $array1 $array2 -IncludeEqual

                               InputObject SideIndicator                             
                               ----------- -------------                             
                                         1 ==                                        
                                         3 ==                                        
                                         6 =>                                        
                                         8 =>                                        
                                         9 =>                                        
                                         2 <=                                        
                                         4 <=                                        
                                         5 <=

Create Custom Objects
  • first way
PS C:\Users\Administrator> $properties = @{Hair='brown'; Eyes='blue';Weight=130;Sex='female'}
$person = New-Object -TypeName PSObject -Property $properties;
$person

Eyes                              Hair                              Sex                                                        Weight
----                              ----                              ---                                                        ------
blue                              brown                             female                                                        130
  • second way
PS C:\Users\Administrator> $annie = New-Object System.Object
$annie | Add-Member -Type NoteProperty -name Hair -value 'brown'
$annie | Add-Member -Type NoteProperty -name Eyes -value 'blue'
$annie | Add-Member -Type NoteProperty -name Weight -value 130
$annie | Add-Member -Type NoteProperty -name Sex -value 'female'
$annie

Hair                              Eyes                                                        Weight Sex                             
----                              ----                                                        ------ ---                             
brown                             blue                                                           130 female

order the objects

$annie = New-Object System.Object
$annie | Add-Member -Type NoteProperty -name Hair -value 'brown'
$annie | Add-Member -Type NoteProperty -name Eyes -value 'blue'
$annie | Add-Member -Type NoteProperty -name Weight -value 130
$annie | Add-Member -Type NoteProperty -name Sex -value 'female'

$joe = New-Object System.Object
$joe | Add-Member -Type NoteProperty -name Hair -value 'black'
$joe | Add-Member -Type NoteProperty -name Eyes -value 'blue'
$joe | Add-Member -Type NoteProperty -name Weight -value 220
$joe | Add-Member -Type NoteProperty -name Sex -value 'Male'
$people = @($annie,$joe)

$people | Sort-Object Weight -Descending | Select-Object Hair, Eyes

Hair                                                               Eyes                                                              
----                                                               ----                                                              
black                                                              blue                                                              
brown                                                              blue

$_. is the variable that identify the current object on the pipeline

in this way you can see the type of obj returned and use a properties or a method of the obj

Get-ChildItem C:\Windows | Get-Member

   TypeName: System.IO.FileInfo

Name                      MemberType     Definition                                  
----                      ----------     ----------                                  
Mode                      CodeProperty   System.String Mode{get=Mode;}               
AppendText                Method         System.IO.StreamWriter AppendText()         
CopyTo                    Method         System.IO.FileInfo CopyTo(string destFile...
Create                    Method         System.IO.FileStream Create()               
CreateObjRef              Method         System.Runtime.Remoting.ObjRef CreateObjR...
CreateText                Method         System.IO.StreamWriter CreateText()         
Decrypt                   Method         void Decrypt()                              
Delete                    Method         void Delete()                               
Encrypt                   Method         void Encrypt()                              
Equals                    Method         bool Equals(System.Object obj)              
GetAccessControl          Method         System.Security.AccessControl.FileSecurit...
GetHashCode               Method         int GetHashCode()

where clause and ordering

PS C:\Users\Administrator> Get-ChildItem C:\Windows | Where-Object {$_.Length -gt 200KB} | Sort-Object Lenght
   Directory: C:\Windows

Mode                LastWriteTime     Length Name                                    
----                -------------     ------ ----                                    
-a---         1/27/2015  11:47 PM    2501368 explorer.exe                            
-a---        10/29/2014   1:46 AM    1001472 HelpPane.exe

Format-Table

PS C:\Users\Administrator> Get-Service | Sort-Object Status | Select * | Format-Table

Name          RequiredServi CanPauseAndCo   CanShutdown      CanStop DisplayName  DependentSer MachineName  ServiceName  ServicesDepe
              ces                  ntinue                                         vices                                  ndedOn      
----          ------------- -------------   -----------      ------- -----------  ------------ -----------  -----------  ------------
AeLookupSvc   {}                    False         False        False Applicati... {}           .            AeLookupSvc  {}          
SstpSvc       {}                    False         False        False Secure So... {RemoteAc... .            SstpSvc      {}          
SSDPSRV       {HTTP}                False         False        False SSDP Disc... {upnphost}   .            SSDPSRV      {HTTP}      
sppsvc        {RpcSs}               False         False        False Software ... {}           .            sppsvc       {RpcSs}

With Out-GridView shows an external window that you can resize and change

Get-Service | Sort-Object Status | Select * | Out-GridView

Section: 10 - Powershell & WMI

it is based on NameSpaces —> Classes —> Properties

the most common namespace is root\cimv2
Much easier WMI than VBscript

when we do things with wmi basically we read data from c:\windows\system32\repository

this give all the namespaces of the machine, from the root namespace select the class __Namespace

gwmi -Namespace root -Class __Namespace | Select name

name                                                                                 
----                                                                                 
subscription                                                                         
DEFAULT                                                                              
MicrosoftWmiNet                                                                      
CIMV2                                                                                
msdtc                                                                                
Cli                                                                                  
nap

find all the classes in root\cim2 but they are too much

Get-WmiObject -List

do some kind of filter

PS C:\Users\Administrator> gwmi -List | ? {($_.Name -like 'Win32_*') -and ($_.Name -like '*Disk*') } | Sort-Object Name

   NameSpace: ROOT\cimv2

Name                                Methods              Properties                               
----                                -------              ----------                               
Win32_DiskDrive                     {SetPowerState, R... {Availability, BytesPerSector, Capabil...
Win32_DiskDrivePhysicalMedia        {}                   {Antecedent, Dependent}                  
Win32_DiskDriveToDiskPartition      {}                   {Antecedent, Dependent}                  
Win32_DiskPartition                 {SetPowerState, R... {Access, Availability, BlockSize, Boot...
Win32_DiskQuota                     {}                   {DiskSpaceUsed, Limit, QuotaVolume, St...
Win32_LogicalDisk                   {SetPowerState, R... {Access, Availability, BlockSize, Capt...
Win32_LogicalDiskRootDirectory      {}                   {GroupComponent, PartComponent}          
Win32_LogicalDiskToPartition        {}                   {Antecedent, Dependent, EndingAddress,...
Win32_LogonSessionMappedDisk        {}                   {Antecedent, Dependent}                  
Win32_MappedLogicalDisk             {SetPowerState, R... {Access, Availability, BlockSize, Capt...
Win32_PerfFormattedData_Counters... {}                   {Caption, Description, FileSystemBytes...
Win32_PerfFormattedData_PerfDisk... {}                   {AvgDiskBytesPerRead, AvgDiskBytesPerT...
Win32_PerfFormattedData_PerfDisk... {}                   {AvgDiskBytesPerRead, AvgDiskBytesPerT...
Win32_PerfRawData_Counters_FileS... {}                   {Caption, Description, FileSystemBytes...
Win32_PerfRawData_PerfDisk_Logic... {}                   {AvgDiskBytesPerRead, AvgDiskBytesPerR...
Win32_PerfRawData_PerfDisk_Physi... {}                   {AvgDiskBytesPerRead, AvgDiskBytesPerR...

from that list we can dig more deeply inside the phisical drive or the partition with these commands

gwmi -Namespace 'root\cimv2' -Class Win32_DiskDrive
gwmi -Namespace 'root\cimv2' -Class Win32_LogicalDisk

Very popolar class Win32_ComputerSystem
two query for the same result

PS C:\Users\Administrator> gwmi -Class Win32_ComputerSystem | Select-Object Model

Model                                                                                             
-----                                                                                             
HVM domU                                                                                          
gwmi -Query 'Select model FROM Win32_ComputerSystem' | Select-Object Model

% and ForEachObject are aliases , If you want use a $ inside a string you need to use the double $ with the ()

PS C:\Users\Administrator> gwmi -Class Win32_logicaldisk | % {"Drive $($_.deviceid) has $($_.Freespace/1GB) GB Free"}
Drive C: has 10.6762771606445 GB Free
Drive D: has 3.96923828125 GB Free
Drive E: has 4.96795654296875 GB Free

PS C:\Users\Administrator> 
gwmi -Class Win32_logicaldisk | % {"Drive $($_.deviceid) has " + "{0:N0}" -f ($_.Freespace/1GB) + 'GB Free'}

Drive C: has 11GB Free
Drive D: has 4GB Free
Drive E: has 5GB Free
Drive F: has 1GB Free
Drive G: has 1GB Free

Section: 11 - Modules: A Brief Overview

all the module loaded in your section, with the command inside every module

PS C:\Users\Administrator> Get-Module -All

ModuleType Version    Name                                ExportedCommands                                           
---------- -------    ----                                ----------------                                           
Script     1.0.0.0    ISE                                 {Get-IseSnippet, Import-IseSnippet, New-IseSnippet}        
Binary     3.0.0.0    Microsoft.PowerShell.Commands.Ma... {Add-Content, Clear-Content, Clear-ItemProperty, Join-Pa...
Binary     3.0.0.0    Microsoft.PowerShell.Commands.Ut... {Get-FormatData, Export-FormatData, Format-List, Format-...
Manifest   3.1.0.0    Microsoft.PowerShell.Management     {Add-Computer, Add-Content, Checkpoint-Computer, Clear-C...
Script     0.0        Microsoft.PowerShell.Utility        {Get-FileHash, GetStreamHash}                              
Manifest   3.1.0.0    Microsoft.PowerShell.Utility        {Add-Member, Add-Type, Clear-Variable, Compare-Object...}

all the module available in your file system

PS C:\Users\Administrator> Get-Module -ListAvailable

    Directory: C:\Windows\system32\WindowsPowerShell\v1.0\Modules

ModuleType Version    Name                                ExportedCommands                                           
---------- -------    ----                                ----------------                                           
Manifest   2.0.0.0    AppLocker                           {Get-AppLockerFileInformation, Get-AppLockerPolicy, New-...
Manifest   2.0.0.0    Appx                                {Add-AppxPackage, Get-AppxPackage, Get-AppxPackageManife...
Manifest   1.0        BestPractices                       {Get-BpaModel, Get-BpaResult, Invoke-BpaModel, Set-BpaRe...
Manifest   1.0.0.0    BitsTransfer                        {Add-BitsFile, Complete-BitsTransfer, Get-BitsTransfer, ...
Manifest   1.0.0.0    BranchCache                         {Add-BCDataCacheExtension, Clear-BCCache, Disable-BC, Di...
Manifest   1.0.0.0    CimCmdlets                          {Get-CimAssociatedInstance, Get-CimClass, Get-CimInstanc...
Manifest   1.0.0.0    DirectAccessClientComponents        {Disable-DAManualEntryPointSelection, Enable-DAManualEnt...
Script     3.0        Dism                                {Add-AppxProvisionedPackage, Add-WindowsDriver, Add-Wind...
Manifest   1.0.0.0    DnsClient                           {Resolve-DnsName, Clear-DnsClientCache, Get-DnsClient, G...
......................................................................

    Directory: C:\Program Files (x86)\AWS Tools\PowerShell

ModuleType Version    Name                                ExportedCommands                                           
---------- -------    ----                                ----------------                                           
Binary     3.1.36.1   AWSPowerShell                       {Clear-AGStageCache, Get-AGAccount, Get-AGApiKey, Get-AG...

import and remove module, from power shell 3.0 the import module is not necessary it will be done automatically

PS C:\Users\Administrator> Import-Module bitstransfer

PS C:\Users\Administrator> remove-Module bitstransfer

PS C:\Users\Administrator>

Section: 12 - Providers: A Brief Overview

A provider is like a datastore

PS C:\Users\Administrator> get-psprovider

Name                 Capabilities                                             Drives                                                 
----                 ------------                                             ------                                                 
Alias                ShouldProcess                                            {Alias}                                                
Environment          ShouldProcess                                            {Env}                                                  
FileSystem           Filter, ShouldProcess, Credentials                       {C, D, E, F...}                                        
Function             ShouldProcess                                            {Function}                                             
Registry             ShouldProcess, Transactions                              {HKLM, HKCU}                                           
Variable             ShouldProcess                                            {Variable}

the variable provider show all the variable loaded in your session

PS C:\Users\Administrator> cd variable:
ls

Name                           Value                                                                                                 
----                           -----                                                                                                 
$                              get-psprovider                                                                                        
?                              True                                                                                                  
^                              get-psprovider                                                                                        
args                           {}                                                                                                    
ConfirmPreference              High                                                                                                  
ConsoleFileName                                                                                                                      
DebugPreference                SilentlyContinue                                                                                      
Error                          {}                                                                                                    
ErrorActionPreference          Continue                                                                                              
ErrorView                      NormalView                                                                                            
ExecutionContext               System.Management.Automation.EngineIntrinsics                                                         
false                          False                                                                                                 
FormatEnumerationLimit         4                                                                                                     
HOME                           C:\Users\Administrator                                                                                
Host                           System.Management.Automation.Internal.Host.InternalHost                                               
input                          System.Collections.ArrayList+ArrayListEnumeratorSimple                                                
MaximumAliasCount              4096                                                                                                  
MaximumDriveCount              4096                                                                                                  
MaximumErrorCount              256                                                                                                   
MaximumFunctionCount           4096

if you define a new variable it will happer in the variable provider

$new_variable = 'test'
cd variable:
ls

to see the drive and also the other things mapped like drive for example the registry

PS Variable:\> Get-PSDrive

Name           Used (GB)     Free (GB) Provider      Root                                                             CurrentLocation
----           ---------     --------- --------      ----                                                             ---------------
Alias                                  Alias                                                                                         
C                  19.12         10.53 FileSystem    C:\                                                          Users\Administrator
Cert                                   Certificate   \                                                                               
D                    .03          3.97 FileSystem    D:\                                                                             
HKCU                                   Registry      HKEY_CURRENT_USER                                                               
HKLM                                   Registry      HKEY_LOCAL_MACHINE

you can navigate in the registry or in the certificate like a file system

PS HKLM:\> cd HKLM:
ls
cd software

    Hive: HKEY_LOCAL_MACHINE

Name                           Property                                                                                              
----                           --------                                                                                              
BCD00000000                                                                                                                          
HARDWARE                                                                                                                             
SAM                                                                                                                                  
ls : Requested registry access is not allowed.
At line:2 char:1
+ ls
+ ~~
    + CategoryInfo          : PermissionDenied: (HKEY_LOCAL_MACHINE\SECURITY:String) [Get-ChildItem], SecurityException
    + FullyQualifiedErrorId : System.Security.SecurityException,Microsoft.PowerShell.Commands.GetChildItemCommand

SOFTWARE                                                                                                                             
SYSTEM                                                                                                                               

PS HKLM:\software>

Section final

final script

if ((Get-Module -ListAvailable | Where-Object {$_.name -eq 'ActiveDirectory'}) -eq $null) {
    Write-Host 'the active directory module is not available'
    return
}
write-host 'module present'

#load the content in the variable
$pc_list = Get-Content 'C:\ips.txt'
write-host $pc_list
#remove from content the element with single space
$pc_list = $pc_list | Where-Object { $_ -ne ''}
write-host $pc_list

$online_pcs = @()
# for each obj in the list to a ping with test conncetion, with the option -Quiet tell if 
#is responding or not, if it is respoinding add to the list of online pcs
$pc_list | ForEach-Object { if ((Test-Connection $_ -Quiet) -eq $true) {$online_pcs+= $_}}
Write-Host $online_pcs
Salvo diversa indicazione, il contenuto di questa pagina è sotto licenza Creative Commons Attribution-ShareAlike 3.0 License