Memoru

System Engineering and Programming and IT

1909-powershell-datetime

1909-powershell-datetime

overview

Image from Gyazo

jupyter notebook

Usage

basic

In [23]:
Get-Date
02 September 2019 20:58:03


In [24]:
Get-Date -format "yy/MM/dd hh:mm"
19/09/02 08:58
In [25]:
Get-Date -format "yyMMdd_hhmm"
190902_0858

Get-Help

In [26]:
Get-Help Get-Date
NAME
    Get-Date
    
SYNOPSIS
    Gets the current date and time.
    
    
SYNTAX
    Get-Date [[-Date] <DateTime>] [-Day <Int32>] [-DisplayHint {Date | Time | DateTime}] [-Format <String>] [-Hour 
    <Int32>] [-Millisecond <Int32>] [-Minute <Int32>] [-Month <Int32>] [-Second <Int32>] [-Year <Int32>] 
    [<CommonParameters>]
    
    Get-Date [[-Date] <DateTime>] [-Day <Int32>] [-DisplayHint {Date | Time | DateTime}] [-Hour <Int32>] [-Millisecond 
    <Int32>] [-Minute <Int32>] [-Month <Int32>] [-Second <Int32>] [-UFormat <String>] [-Year <Int32>] 
    [<CommonParameters>]
    
    
DESCRIPTION
    The Get-Date cmdlet gets a DateTime object that represents the current date or a date that you specify. It can 
    format the date and time in several Windows and UNIX formats. You can use Get-Date to generate a date or time 
    character string, and then send the string to other cmdlets or programs.
    

RELATED LINKS
    Online Version: http://go.microsoft.com/fwlink/?LinkId=821781
    New-TimeSpan 
    Set-Date 

REMARKS
    To see the examples, type: "get-help Get-Date -examples".
    For more information, type: "get-help Get-Date -detailed".
    For technical information, type: "get-help Get-Date -full".
    For online help, type: "get-help Get-Date -online"


In [27]:
Get-Help Get-Date -online

Get-Command and Get-Alias

In [29]:
Get-Command -Noun Date
CommandType     Name                                               Version    Source                                   
-----------     ----                                               -------    ------                                   
Cmdlet          Get-Date                                           3.1.0.0    Microsoft.PowerShell.Utility             
Cmdlet          Set-Date                                           3.1.0.0    Microsoft.PowerShell.Utility             


Identification of Type

In [30]:
(Get-Date) -is [datetime]
True
In [32]:
(Get-Date).GetType().Fullname
System.DateTime

Get-Member

In [33]:
(Get-Date) | Get-Member -MemberType Property | Format-Table Name, Definition
Name        Definition                       
----        ----------                       
Date        datetime Date {get;}             
Day         int Day {get;}                   
DayOfWeek   System.DayOfWeek DayOfWeek {get;}
DayOfYear   int DayOfYear {get;}             
Hour        int Hour {get;}                  
Kind        System.DateTimeKind Kind {get;}  
Millisecond int Millisecond {get;}           
Minute      int Minute {get;}                
Month       int Month {get;}                 
Second      int Second {get;}                
Ticks       long Ticks {get;}                
TimeOfDay   timespan TimeOfDay {get;}        
Year        int Year {get;}                  


In [34]:
(Get-Date) | Get-Member -MemberType Method | Format-Table Name, Definition
Name                 Definition                                                                                        
----                 ----------                                                                                        
Add                  datetime Add(timespan value)                                                                      
AddDays              datetime AddDays(double value)                                                                    
AddHours             datetime AddHours(double value)                                                                   
AddMilliseconds      datetime AddMilliseconds(double value)                                                            
AddMinutes           datetime AddMinutes(double value)                                                                 
AddMonths            datetime AddMonths(int months)                                                                    
AddSeconds           datetime AddSeconds(double value)                                                                 
AddTicks             datetime AddTicks(long value)                                                                     
AddYears             datetime AddYears(int value)                                                                      
CompareTo            int CompareTo(System.Object value), int CompareTo(datetime value), int IComparable.CompareTo(Sy...
Equals               bool Equals(System.Object value), bool Equals(datetime value), bool IEquatable[datetime].Equals...
GetDateTimeFormats   string[] GetDateTimeFormats(), string[] GetDateTimeFormats(System.IFormatProvider provider), st...
GetHashCode          int GetHashCode()                                                                                 
GetObjectData        void ISerializable.GetObjectData(System.Runtime.Serialization.SerializationInfo info, System.Ru...
GetType              type GetType()                                                                                    
GetTypeCode          System.TypeCode GetTypeCode(), System.TypeCode IConvertible.GetTypeCode()                         
IsDaylightSavingTime bool IsDaylightSavingTime()                                                                       
Subtract             timespan Subtract(datetime value), datetime Subtract(timespan value)                              
ToBinary             long ToBinary()                                                                                   
ToBoolean            bool IConvertible.ToBoolean(System.IFormatProvider provider)                                      
ToByte               byte IConvertible.ToByte(System.IFormatProvider provider)                                         
ToChar               char IConvertible.ToChar(System.IFormatProvider provider)                                         
ToDateTime           datetime IConvertible.ToDateTime(System.IFormatProvider provider)                                 
ToDecimal            decimal IConvertible.ToDecimal(System.IFormatProvider provider)                                   
ToDouble             double IConvertible.ToDouble(System.IFormatProvider provider)                                     
ToFileTime           long ToFileTime()                                                                                 
ToFileTimeUtc        long ToFileTimeUtc()                                                                              
ToInt16              int16 IConvertible.ToInt16(System.IFormatProvider provider)                                       
ToInt32              int IConvertible.ToInt32(System.IFormatProvider provider)                                         
ToInt64              long IConvertible.ToInt64(System.IFormatProvider provider)                                        
ToLocalTime          datetime ToLocalTime()                                                                            
ToLongDateString     string ToLongDateString()                                                                         
ToLongTimeString     string ToLongTimeString()                                                                         
ToOADate             double ToOADate()                                                                                 
ToSByte              sbyte IConvertible.ToSByte(System.IFormatProvider provider)                                       
ToShortDateString    string ToShortDateString()                                                                        
ToShortTimeString    string ToShortTimeString()                                                                        
ToSingle             float IConvertible.ToSingle(System.IFormatProvider provider)                                      
ToString             string ToString(), string ToString(string format), string ToString(System.IFormatProvider provi...
ToType               System.Object IConvertible.ToType(type conversionType, System.IFormatProvider provider)           
ToUInt16             uint16 IConvertible.ToUInt16(System.IFormatProvider provider)                                     
ToUInt32             uint32 IConvertible.ToUInt32(System.IFormatProvider provider)                                     
ToUInt64             uint64 IConvertible.ToUInt64(System.IFormatProvider provider)                                     
ToUniversalTime      datetime ToUniversalTime()                                                                        


Methods

calculate

In [37]:
$first_off_dtm = Get-Date
$first_off_dtm_str = Get-Date (Get-Date $first_off_dtm -f 'yyyy/MM/dd') -f 'yyyy/MM/dd HH:mm'
$last_on_dtm_str = Get-Date ((Get-Date $first_off_dtm_str).AddDays(1).AddMinutes(-1)) -f 'yyyy/MM/dd HH:mm'
$first_off_dtm_str
$last_on_dtm_str
$first_off_dtm = Get-Date
$first_off_dtm_str = Get-Date (Get-Date $first_off_dtm -f 'yyyy/MM/dd') -f 'yyyy/MM/dd HH:mm'
$last_on_dtm_str = Get-Date ((Get-Date $first_off_dtm_str).AddDays(1).AddMinutes(-1)) -f 'yyyy/MM/dd HH:mm'
$first_off_dtm_str
2019/09/02 00:00
$last_on_dtm_str
2019/09/02 23:59

date -> str (formatting)

In [39]:
@("d","D","f","F","g","G","M","O","R","s","t","T","u","U","Y") | 
    foreach {$date=Get-Date -F $_ ;"$_, $date"}
d, 02/09/2019
D, 02 September 2019
f, 02 September 2019 21:07
F, 02 September 2019 21:07:01
g, 02/09/2019 21:07
G, 02/09/2019 21:07:01
M, 2 September
O, 2019-09-02T21:07:01.9259624+09:00
R, Mon, 02 Sep 2019 21:07:01 GMT
s, 2019-09-02T21:07:01
t, 21:07
T, 21:07:01
u, 2019-09-02 21:07:01Z
U, 02 September 2019 12:07:01
Y, September 2019
In [41]:
Get-Date -F 'yyyy/MM/dd HH:mm:ss.ffffff'
2019/09/02 21:07:24.807954
In [43]:
(Get-Date -F O).Replace('-','').Replace('T','_').Replace(':','').Replace('+','_GMT+')
20190902_210741.5350748_GMT+0900

str -> datetime

In [45]:
Get-Date '2019/09/01'
01 September 2019 00:00:00


In [47]:
Get-Date '2019/08/28 22:12'
28 August 2019 22:12:00


serialization

In [52]:
Get-Date | Export-Clixml date.clixml

In [54]:
cat date.clixml
<Objs Version="1.1.0.1" xmlns="">http://schemas.microsoft.com/powershell/2004/04">
  <Obj RefId="0">
    <DT>2019-09-02T21:11:13.7820526+09:00</DT>
    <MS>
      <Obj N="DisplayHint" RefId="1">
        <TN RefId="0">
          <T>Microsoft.PowerShell.Commands.DisplayHintType</T>
          <T>System.Enum</T>
          <T>System.ValueType</T>
          <T>System.Object</T>
        </TN>
        <ToString>DateTime</ToString>
        <I32>2</I32>
      </Obj>
    </MS>
  </Obj>
</Objs>
In [56]:
Import-Clixml date.clixml | set -Name dtm_cli

In [58]:
02 September 2019 21:11:13


In [60]:
$dtm_cli.GetType().Fullname
System.DateTime

timespan

In [62]:
Get-Command -Noun Time*
CommandType     Name                                               Version    Source                                   
-----------     ----                                               -------    ------                                   
Cmdlet          Get-TimeZone                                       3.1.0.0    Microsoft.PowerShell.Management          
Cmdlet          New-TimeSpan                                       3.1.0.0    Microsoft.PowerShell.Utility             
Cmdlet          Set-TimeZone                                       3.1.0.0    Microsoft.PowerShell.Management          


In [64]:
Get-Help New-Timespan
NAME
    New-TimeSpan
    
SYNOPSIS
    Creates a TimeSpan object.
    
    
SYNTAX
    New-TimeSpan [-Days <Int32>] [-Hours <Int32>] [-Minutes <Int32>] [-Seconds <Int32>] [<CommonParameters>]
    
    New-TimeSpan [[-Start] <DateTime>] [[-End] <DateTime>] [<CommonParameters>]
    
    
DESCRIPTION
    The New-TimeSpan cmdlet creates a TimeSpan object that represents a time interval. You can use a TimeSpan object 
    to add or subtract time from DateTime objects.
    
    Without parameters, a New-Timespan command returns a timespan object that represents a time interval of zero.
    

RELATED LINKS
    Online Version: http://go.microsoft.com/fwlink/?LinkId=821837
    Get-Date 
    Set-Date 

REMARKS
    To see the examples, type: "get-help New-TimeSpan -examples".
    For more information, type: "get-help New-TimeSpan -detailed".
    For technical information, type: "get-help New-TimeSpan -full".
    For online help, type: "get-help New-TimeSpan -online"


In [65]:
Get-Help New-Timespan -online
NAME
    New-TimeSpan
    
SYNOPSIS
    Creates a TimeSpan object.
    
    
SYNTAX
    New-TimeSpan [-Days <Int32>] [-Hours <Int32>] [-Minutes <Int32>] [-Seconds <Int32>] [<CommonParameters>]
    
    New-TimeSpan [[-Start] <DateTime>] [[-End] <DateTime>] [<CommonParameters>]
    
    
DESCRIPTION
    The New-TimeSpan cmdlet creates a TimeSpan object that represents a time interval. You can use a TimeSpan object 
    to add or subtract time from DateTime objects.
    
    Without parameters, a New-Timespan command returns a timespan object that represents a time interval of zero.
    

RELATED LINKS
    Online Version: http://go.microsoft.com/fwlink/?LinkId=821837
    Get-Date 
    Set-Date 

REMARKS
    To see the examples, type: "get-help New-TimeSpan -examples".
    For more information, type: "get-help New-TimeSpan -detailed".
    For technical information, type: "get-help New-TimeSpan -full".
    For online help, type: "get-help New-TimeSpan -online"


Get-Member

In [66]:
$timespn = New-Timespan

In [74]:
$timespn | Get-Member -MemberType Property | ft Name, Definition
Name              Definition                     
----              ----------                     
Days              int Days {get;}                
Hours             int Hours {get;}               
Milliseconds      int Milliseconds {get;}        
Minutes           int Minutes {get;}             
Seconds           int Seconds {get;}             
Ticks             long Ticks {get;}              
TotalDays         double TotalDays {get;}        
TotalHours        double TotalHours {get;}       
TotalMilliseconds double TotalMilliseconds {get;}
TotalMinutes      double TotalMinutes {get;}     
TotalSeconds      double TotalSeconds {get;}     


In [76]:
$timespn | Get-Member -MemberType Method | ft Name, Definition
Name        Definition                                                                                                 
----        ----------                                                                                                 
Add         timespan Add(timespan ts)                                                                                  
CompareTo   int CompareTo(System.Object value), int CompareTo(timespan value), int IComparable.CompareTo(System.Obje...
Duration    timespan Duration()                                                                                        
Equals      bool Equals(System.Object value), bool Equals(timespan obj), bool IEquatable[timespan].Equals(timespan o...
GetHashCode int GetHashCode()                                                                                          
GetType     type GetType()                                                                                             
Negate      timespan Negate()                                                                                          
Subtract    timespan Subtract(timespan ts)                                                                             
ToString    string ToString(), string ToString(string format), string ToString(string format, System.IFormatProvider...


In [78]:
$dtm_begin = Get-Date '2019/08/30 13:32'
$dtm_end = Get-Date '2019/08/30 17:09'
$span = New-Timespan $dtm_begin $dtm_end
$dtm_begin = Get-Date '2019/08/30 13:32'
$dtm_end = Get-Date '2019/08/30 17:09'
$span = New-Timespan $dtm_begin $dtm_end

In [80]:
$span | format-list

Days              : 0
Hours             : 3
Minutes           : 37
Seconds           : 0
Milliseconds      : 0
Ticks             : 130200000000
TotalDays         : 0.150694444444444
TotalHours        : 3.61666666666667
TotalMinutes      : 217
TotalSeconds      : 13020
TotalMilliseconds : 13020000



In [82]:
'{0:g}' -f $span
3:37:00
In [84]:
$str = '{0:g}' -f $span
$str.Substring(0, $str.length -3)
$str = '{0:g}' -f $span
$str.Substring(0, $str.length -3)
3:37

In [86]:
$dtm_begin2 = Get-Date '2019/08/30 16:44'
$dtm_end2 = Get-Date '2019/08/31 1:09'
$span2 = New-Timespan $dtm_begin2 $dtm_end2
$str2 = '{0:g}' -f $span2
$str2.Substring(0, $str2.length -3)
$dtm_begin2 = Get-Date '2019/08/30 16:44'
$dtm_end2 = Get-Date '2019/08/31 1:09'
$span2 = New-Timespan $dtm_begin2 $dtm_end2
$str2 = '{0:g}' -f $span2
$str2.Substring(0, $str2.length -3)
8:25

reference

</div>

1909-powershell-alias

1909-powershell-alias

overview

jupyter notebook

contents

Basic

In [10]:
Path                 
----                 
G:\workspace\pwshnote


In [122]:
dir | set -Name dirs
$dirs[0..10] + "`r`n and more ...."
dir | set -Name dirs
$dirs[0..10] + "`r`n and more ...."


    Directory: G:\workspace\pwshnote


Mode                LastWriteTime         Length Name                                                                  
----                -------------         ------ ----                                                                  
d-----       02/09/2019     08:26                .ipynb_checkpoints                                                    
d-----       01/09/2019     17:52                data                                                                  
d-----       01/09/2019     06:11                temp                                                                  
-a----       02/09/2019     09:36            231 .gitignore                                                            
-a----       29/07/2019     21:02          20614 1907-keylogger-sample.ipynb                                           
-a----       01/09/2019     11:34          27941 1908-powershell-about-operators.ipynb                                 
-a----       01/09/2019     11:21          63452 1908-powershell-about_types.ipynb                                     
-a----       16/08/2019     19:11           5757 1908-powershell-alias-grep.ipynb                                      
-a----       27/08/2019     12:33          36948 1908-powershell-array.ipynb                                           
-a----       31/08/2019     11:59          25028 1908-powershell-datetime.ipynb                                        
-a----       22/08/2019     12:20          38156 1908-powershell-format-list-all.ipynb                                 

 and more ....



In [4]:
ls index.*

    Directory: G:\workspace\pwshnote


Mode                LastWriteTime         Length Name                                                                  
----                -------------         ------ ----                                                                  
-a----       07/05/2019     16:05         337989 index.html                                                            
-a----       16/08/2019     19:13            871 index.md                                                              


In [6]:
cat README.md
# pwshnote
## overview
- a repository for powershell jupyter notebook
- To try a powershell script on jupyter notebook
- GitHub Page
    + https://sakai-memoru.github.io/pwshnote/
// -- end of README.md
In [8]:
type .gitignore
### vim

# Swap
[._]*.s[a-v][a-z]
[._]*.sw[a-p]
[._]s[a-v][a-z]
[._]sw[a-p]

# Session
Session.vim

# Temporary
.netrwhist
*~
# Auto-generated tag files
tags
# Persistent undo
[._]*.un~


Get-Help

In [12]:
Get-Help Get-Alias
NAME
    Get-Alias
    
SYNOPSIS
    Gets the aliases for the current session.
    
    
SYNTAX
    Get-Alias [-Definition <String[]>] [-Exclude <String[]>] [-Scope <String>] [<CommonParameters>]
    
    Get-Alias [[-Name] <String[]>] [-Exclude <String[]>] [-Scope <String>] [<CommonParameters>]
    
    
DESCRIPTION
    The Get-Alias cmdlet gets the aliases in the current session. This includes built-in aliases, aliases that you 
    have set or imported, and aliases that you have added to your Windows PowerShell profile.
    
    By default, Get-Alias takes an alias and returns the command name. When you use the Definition parameter, 
    Get-Alias takes a command name and returns its aliases.
    
    Beginning in Windows PowerShell 3.0, Get-Alias displays non-hyphenated alias names in an <alias> -> <definition> 
    format to make it even easier to find the information that you need.
    

RELATED LINKS
    Online Version: http://go.microsoft.com/fwlink/?LinkId=821778
    About Aliases 
    Export-Alias 
    Import-Alias 
    New-Alias 
    Set-Alias 

REMARKS
    To see the examples, type: "get-help Get-Alias -examples".
    For more information, type: "get-help Get-Alias -detailed".
    For technical information, type: "get-help Get-Alias -full".
    For online help, type: "get-help Get-Alias -online"


In [111]:
Help about_alias | set -Name store
$store[0..15] + "`r`n and more ...."
$store[0..15] + "`r`n and more ...."
TOPIC
    about_aliases

SHORT DESCRIPTION
    Describes how to use alternate names for cmdlets and commands in Windows
    PowerShell. 

LONG DESCRIPTION
    An alias is an alternate name or nickname for a cmdlet or for a command
    element, such as a function, script, file, or executable file. You
    can use the alias instead of the command name in any Windows PowerShell
    commands.
    
    To create an alias, use the New-Alias cmdlet. For example, the following
    command creates the "gas" alias for the Get-AuthenticodeSignature cmdlet:


 and more ....


Help about_alias | set -Name store

Get-Commands

In [47]:
Get-Command -Noun Alias
CommandType     Name                                               Version    Source                                   
-----------     ----                                               -------    ------                                   
Cmdlet          Export-Alias                                       3.1.0.0    Microsoft.PowerShell.Utility             
Cmdlet          Get-Alias                                          3.1.0.0    Microsoft.PowerShell.Utility             
Cmdlet          Import-Alias                                       3.1.0.0    Microsoft.PowerShell.Utility             
Cmdlet          New-Alias                                          3.1.0.0    Microsoft.PowerShell.Utility             
Cmdlet          Set-Alias                                          3.1.0.0    Microsoft.PowerShell.Utility             


Alias

In [114]:
Get-Alias | set -Name ary
$ary[0..15] + "`r`n and more ...."
Get-Alias | set -Name ary
$ary[0..15] + "`r`n and more ...."

CommandType     Name                                               Version    Source                                   
-----------     ----                                               -------    ------                                   
Alias           % -> ForEach-Object                                                                                    
Alias           ? -> Where-Object                                                                                      
Alias           ac -> Add-Content                                                                                      
Alias           asnp -> Add-PSSnapin                                                                                   
Alias           cat -> Get-Content                                                                                     
Alias           cd -> Set-Location                                                                                     
Alias           CFS -> ConvertFrom-String                          3.1.0.0    Microsoft.PowerShell.Utility             
Alias           chdir -> Set-Location                                                                                  
Alias           clc -> Clear-Content                                                                                   
Alias           clear -> Clear-Host                                                                                    
Alias           clhy -> Clear-History                                                                                  
Alias           cli -> Clear-Item                                                                                      
Alias           clp -> Clear-ItemProperty                                                                              
Alias           cls -> Clear-Host                                                                                      
Alias           clv -> Clear-Variable                                                                                  
Alias           cnsn -> Connect-PSSession                                                                              

 and more ....




In [79]:
Get-Alias | Out-String -Stream | select-string 'Content'
Alias           ac -> Add-Content                                                                                      
Alias           cat -> Get-Content                                                                                     
Alias           clc -> Clear-Content                                                                                   
Alias           gc -> Get-Content                                                                                      
Alias           sc -> Set-Content                                                                                      
Alias           type -> Get-Content                                                                                    


In [94]:
Get-Alias | Out-String -Stream | sls 'process'
Alias           gps -> Get-Process                                                                                     
Alias           kill -> Stop-Process                                                                                   
Alias           ps -> Get-Process                                                                                      
Alias           saps -> Start-Process                                                                                  
Alias           spps -> Stop-Process                                                                                   
Alias           start -> Start-Process                                                                                 


In [81]:
Get-Alias -Definition '*Item'
CommandType     Name                                               Version    Source                                   
-----------     ----                                               -------    ------                                   
Alias           cli -> Clear-Item                                                                                      
Alias           copy -> Copy-Item                                                                                      
Alias           cp -> Copy-Item                                                                                        
Alias           cpi -> Copy-Item                                                                                       
Alias           del -> Remove-Item                                                                                     
Alias           dir -> Get-ChildItem                                                                                   
Alias           erase -> Remove-Item                                                                                   
Alias           gci -> Get-ChildItem                                                                                   
Alias           gi -> Get-Item                                                                                         
Alias           ii -> Invoke-Item                                                                                      
Alias           ls -> Get-ChildItem                                                                                    
Alias           mi -> Move-Item                                                                                        
Alias           move -> Move-Item                                                                                      
Alias           mv -> Move-Item                                                                                        
Alias           ni -> New-Item                                                                                         
Alias           rd -> Remove-Item                                                                                      
Alias           ren -> Rename-Item                                                                                     
Alias           ri -> Remove-Item                                                                                      
Alias           rm -> Remove-Item                                                                                      
Alias           rmdir -> Remove-Item                                                                                   
Alias           rni -> Rename-Item                                                                                     
Alias           si -> Set-Item                                                                                         


In [29]:
Get-Alias | Where-Object {$_.Name -eq 'cat'} | Format-List *

HelpUri             : https://go.microsoft.com/fwlink/?LinkID=113310
ResolvedCommandName : Get-Content
DisplayName         : cat -> Get-Content
ReferencedCommand   : Get-Content
ResolvedCommand     : Get-Content
Definition          : Get-Content
Options             : AllScope
Description         : 
OutputType          : {System.Byte, System.String}
Name                : cat
CommandType         : Alias
Source              : 
Version             : 
Visibility          : Public
ModuleName          : 
Module              : 
RemotingCapability  : PowerShell
Parameters          : {[ReadCount, System.Management.Automation.ParameterMetadata], [TotalCount, 
                      System.Management.Automation.ParameterMetadata], [Tail, 
                      System.Management.Automation.ParameterMetadata], [Path, 
                      System.Management.Automation.ParameterMetadata]...}
ParameterSets       : 



In [39]:
Get-Alias | Where-Object {$_.Definition -match 'Content'} | Sort-Object Definition | Format-Table Definition, Name, HelpUri
In [41]:
Get-Alias | Where-Object {$_.Definition -match 'Item$'} | Sort-Object Definition | Format-Table Definition, Name, HelpUri
In [86]:
Get-Alias -Definition '*Location' | Sort-Object Definition | Format-Table Definition, Name, HelpUri
In [91]:
gal -Def '*Path' | sort Definition | ft Definition, Name, HelpUri
Definition   Name HelpUri                                       
----------   ---- -------                                       
Convert-Path cvpa https://go.microsoft.com/fwlink/?LinkID=113289
Resolve-Path rvpa https://go.microsoft.com/fwlink/?LinkID=113384


In [51]:
Get-Alias | Where {$_.Definition -match 'Object$'} | Sort Definition | Select Definition, Name, HelpUri
In [59]:
Get-Alias | Where {$_.Definition -match '^Format'} | Sort Definition | Select Definition, Name, HelpUri | format-table *
Get-Alias | Where {$_.Definition -match 'Format'} | Sort Definition | Select Definition, Name, HelpUri | format-table *

Definition    Name HelpUri                                       
----------    ---- -------                                       
Format-Custom fc   https://go.microsoft.com/fwlink/?LinkID=113301
Format-Hex    fhx  https://go.microsoft.com/fwlink/?LinkId=526919
Format-List   fl   https://go.microsoft.com/fwlink/?LinkID=113302
Format-Table  ft   https://go.microsoft.com/fwlink/?LinkID=113303
Format-Wide   fw   https://go.microsoft.com/fwlink/?LinkID=113304


Frequenctly Using

In [63]:
$ary_for_frequent_use_obj = @(
  'where','?','foreach','%','select','sort', 'group','measure','tee'
)
Get-Alias | Where {$_.Name -in $ary_for_frequent_use_obj} | Sort Definition | Select Definition, Name, HelpUri
In [73]:
$ary_for_frequent_cmd = @(
  'man', 'help', 'echo','write','cat','type','pwd','dir','ls','cd','chdir','clear','copy','cp', 'del','move','mv','ren','rm','rmdir', 'del', 'set'
)
Get-Alias | Where {$_.Name -in $ary_for_frequent_cmd} | Sort Definition | Select Definition, Name, HelpUri
In [75]:
$ary_other = @(
  'ise', 'ps', 'kill','curl','wget','sleep','history'
)
Get-Alias | Where {$_.Name -in $ary_other} | Sort Definition | Select Definition, Name, HelpUri
In [77]:
$ary_other_rare = @(
  'sls', 'fl', 'ft','gm','gal'
)
Get-Alias | Where {$_.Name -in $ary_other_rare} | Sort Definition | Select Definition, Name, HelpUri

Appendix

In [116]:
Get-Alias
CommandType     Name                                               Version    Source                                   
-----------     ----                                               -------    ------                                   
Alias           % -> ForEach-Object                                                                                    
Alias           ? -> Where-Object                                                                                      
Alias           ac -> Add-Content                                                                                      
Alias           asnp -> Add-PSSnapin                                                                                   
Alias           cat -> Get-Content                                                                                     
Alias           cd -> Set-Location                                                                                     
Alias           CFS -> ConvertFrom-String                          3.1.0.0    Microsoft.PowerShell.Utility             
Alias           chdir -> Set-Location                                                                                  
Alias           clc -> Clear-Content                                                                                   
Alias           clear -> Clear-Host                                                                                    
Alias           clhy -> Clear-History                                                                                  
Alias           cli -> Clear-Item                                                                                      
Alias           clp -> Clear-ItemProperty                                                                              
Alias           cls -> Clear-Host                                                                                      
Alias           clv -> Clear-Variable                                                                                  
Alias           cnsn -> Connect-PSSession                                                                              
Alias           compare -> Compare-Object                                                                              
Alias           copy -> Copy-Item                                                                                      
Alias           cp -> Copy-Item                                                                                        
Alias           cpi -> Copy-Item                                                                                       
Alias           cpp -> Copy-ItemProperty                                                                               
Alias           curl -> Invoke-WebRequest                                                                              
Alias           cvpa -> Convert-Path                                                                                   
Alias           dbp -> Disable-PSBreakpoint                                                                            
Alias           del -> Remove-Item                                                                                     
Alias           diff -> Compare-Object                                                                                 
Alias           dir -> Get-ChildItem                                                                                   
Alias           dnsn -> Disconnect-PSSession                                                                           
Alias           ebp -> Enable-PSBreakpoint                                                                             
Alias           echo -> Write-Output                                                                                   
Alias           epal -> Export-Alias                                                                                   
Alias           epcsv -> Export-Csv                                                                                    
Alias           epsn -> Export-PSSession                                                                               
Alias           erase -> Remove-Item                                                                                   
Alias           etsn -> Enter-PSSession                                                                                
Alias           exsn -> Exit-PSSession                                                                                 
Alias           fc -> Format-Custom                                                                                    
Alias           fhx -> Format-Hex                                  3.1.0.0    Microsoft.PowerShell.Utility             
Alias           fl -> Format-List                                                                                      
Alias           foreach -> ForEach-Object                                                                              
Alias           ft -> Format-Table                                                                                     
Alias           fw -> Format-Wide                                                                                      
Alias           gal -> Get-Alias                                                                                       
Alias           gbp -> Get-PSBreakpoint                                                                                
Alias           gc -> Get-Content                                                                                      
Alias           gcb -> Get-Clipboard                               3.1.0.0    Microsoft.PowerShell.Management          
Alias           gci -> Get-ChildItem                                                                                   
Alias           gcm -> Get-Command                                                                                     
Alias           gcs -> Get-PSCallStack                                                                                 
Alias           gdr -> Get-PSDrive                                                                                     
Alias           ghy -> Get-History                                                                                     
Alias           gi -> Get-Item                                                                                         
Alias           gin -> Get-ComputerInfo                            3.1.0.0    Microsoft.PowerShell.Management          
Alias           gjb -> Get-Job                                                                                         
Alias           gl -> Get-Location                                                                                     
Alias           gm -> Get-Member                                                                                       
Alias           gmo -> Get-Module                                                                                      
Alias           gp -> Get-ItemProperty                                                                                 
Alias           gps -> Get-Process                                                                                     
Alias           gpv -> Get-ItemPropertyValue                                                                           
Alias           group -> Group-Object                                                                                  
Alias           gsn -> Get-PSSession                                                                                   
Alias           gsnp -> Get-PSSnapin                                                                                   
Alias           gsv -> Get-Service                                                                                     
Alias           gtz -> Get-TimeZone                                3.1.0.0    Microsoft.PowerShell.Management          
Alias           gu -> Get-Unique                                                                                       
Alias           gv -> Get-Variable                                                                                     
Alias           gwmi -> Get-WmiObject                                                                                  
Alias           h -> Get-History                                                                                       
Alias           history -> Get-History                                                                                 
Alias           icm -> Invoke-Command                                                                                  
Alias           iex -> Invoke-Expression                                                                               
Alias           ihy -> Invoke-History                                                                                  
Alias           ii -> Invoke-Item                                                                                      
Alias           ipal -> Import-Alias                                                                                   
Alias           ipcsv -> Import-Csv                                                                                    
Alias           ipmo -> Import-Module                                                                                  
Alias           ipsn -> Import-PSSession                                                                               
Alias           irm -> Invoke-RestMethod                                                                               
Alias           ise -> powershell_ise.exe                                                                              
Alias           iwmi -> Invoke-WmiMethod                                                                               
Alias           iwr -> Invoke-WebRequest                                                                               
Alias           kill -> Stop-Process                                                                                   
Alias           lp -> Out-Printer                                                                                      
Alias           ls -> Get-ChildItem                                                                                    
Alias           man -> help                                                                                            
Alias           md -> mkdir                                                                                            
Alias           measure -> Measure-Object                                                                              
Alias           mi -> Move-Item                                                                                        
Alias           mount -> New-PSDrive                                                                                   
Alias           move -> Move-Item                                                                                      
Alias           mp -> Move-ItemProperty                                                                                
Alias           mv -> Move-Item                                                                                        
Alias           nal -> New-Alias                                                                                       
Alias           ndr -> New-PSDrive                                                                                     
Alias           ni -> New-Item                                                                                         
Alias           nmo -> New-Module                                                                                      
Alias           npssc -> New-PSSessionConfigurationFile                                                                
Alias           nsn -> New-PSSession                                                                                   
Alias           nv -> New-Variable                                                                                     
Alias           ogv -> Out-GridView                                                                                    
Alias           oh -> Out-Host                                                                                         
Alias           popd -> Pop-Location                                                                                   
Alias           ps -> Get-Process                                                                                      
Alias           pushd -> Push-Location                                                                                 
Alias           pwd -> Get-Location                                                                                    
Alias           r -> Invoke-History                                                                                    
Alias           rbp -> Remove-PSBreakpoint                                                                             
Alias           rcjb -> Receive-Job                                                                                    
Alias           rcsn -> Receive-PSSession                                                                              
Alias           rd -> Remove-Item                                                                                      
Alias           rdr -> Remove-PSDrive                                                                                  
Alias           ren -> Rename-Item                                                                                     
Alias           ri -> Remove-Item                                                                                      
Alias           rjb -> Remove-Job                                                                                      
Alias           rm -> Remove-Item                                                                                      
Alias           rmdir -> Remove-Item                                                                                   
Alias           rmo -> Remove-Module                                                                                   
Alias           rni -> Rename-Item                                                                                     
Alias           rnp -> Rename-ItemProperty                                                                             
Alias           rp -> Remove-ItemProperty                                                                              
Alias           rsn -> Remove-PSSession                                                                                
Alias           rsnp -> Remove-PSSnapin                                                                                
Alias           rujb -> Resume-Job                                                                                     
Alias           rv -> Remove-Variable                                                                                  
Alias           rvpa -> Resolve-Path                                                                                   
Alias           rwmi -> Remove-WmiObject                                                                               
Alias           sajb -> Start-Job                                                                                      
Alias           sal -> Set-Alias                                                                                       
Alias           saps -> Start-Process                                                                                  
Alias           sasv -> Start-Service                                                                                  
Alias           sbp -> Set-PSBreakpoint                                                                                
Alias           sc -> Set-Content                                                                                      
Alias           scb -> Set-Clipboard                               3.1.0.0    Microsoft.PowerShell.Management          
Alias           select -> Select-Object                                                                                
Alias           set -> Set-Variable                                                                                    
Alias           shcm -> Show-Command                                                                                   
Alias           si -> Set-Item                                                                                         
Alias           sl -> Set-Location                                                                                     
Alias           sleep -> Start-Sleep                                                                                   
Alias           sls -> Select-String                                                                                   
Alias           sort -> Sort-Object                                                                                    
Alias           sp -> Set-ItemProperty                                                                                 
Alias           spjb -> Stop-Job                                                                                       
Alias           spps -> Stop-Process                                                                                   
Alias           spsv -> Stop-Service                                                                                   
Alias           start -> Start-Process                                                                                 
Alias           stz -> Set-TimeZone                                3.1.0.0    Microsoft.PowerShell.Management          
Alias           sujb -> Suspend-Job                                                                                    
Alias           sv -> Set-Variable                                                                                     
Alias           swmi -> Set-WmiInstance                                                                                
Alias           tee -> Tee-Object                                                                                      
Alias           trcm -> Trace-Command                                                                                  
Alias           type -> Get-Content                                                                                    
Alias           wget -> Invoke-WebRequest                                                                              
Alias           where -> Where-Object                                                                                  
Alias           wjb -> Wait-Job                                                                                        
Alias           write -> Write-Output                                                                                  


In [124]:
Help about_alias
TOPIC
    about_aliases

SHORT DESCRIPTION
    Describes how to use alternate names for cmdlets and commands in Windows
    PowerShell. 

LONG DESCRIPTION
    An alias is an alternate name or nickname for a cmdlet or for a command
    element, such as a function, script, file, or executable file. You
    can use the alias instead of the command name in any Windows PowerShell
    commands.
    
    To create an alias, use the New-Alias cmdlet. For example, the following
    command creates the "gas" alias for the Get-AuthenticodeSignature cmdlet:

        New-Alias -Name gas -Value Get-AuthenticodeSignature

    After you create the alias for the cmdlet name, you can use the alias 
    instead of the cmdlet name. For example, to get the Authenticode signature
    for the SqlScript.ps1 file, type:

        Get-AuthenticodeSignature SqlScript.ps1

    Or, type:

        gas SqlScript.ps1


    If you create "word" as the alias for Microsoft Office Word, you can type
    "word" instead of the following:


        "C:\Program Files\Microsoft Office\Office11\Winword.exe" 

BUILT-IN ALIASES
    Windows PowerShell includes a set of built-in aliases, including "cd" and
    "chdir" for the Set-Location cmdlet, and "ls" and "dir" for the
    Get-ChildItem cmdlet. 

    To get all the aliases on the computer, including the built-in aliases,
    type:

        Get-Alias


ALIAS CMDLETS
    Windows PowerShell includes the following cmdlets, which are designed for
    working with aliases: 

        - Get-Alias. Gets all the aliases in the current session.
        - New-Alias. Creates a new alias.
        - Set-Alias. Creates or changes an alias.
        - Export-Alias. Exports one or more aliases to a file.
        - Import-Alias. Imports an alias file into Windows PowerShell. 

    For detailed information about the cmdlets, type:

Get-Help <cmdlet-Name> -Detailed

    For example, type:

Get-Help Export-Alias -Detailed

CREATING AN ALIAS
    To create a new alias, use the New-Alias cmdlet. For example, to create the
    "gh" alias for Get-Help, type:

New-Alias -Name gh -Value Get-Help

    You can use the alias in commands, just as you would use the full cmdlet
    name, and you can use the alias with parameters.

    For example, to get detailed Help for the Get-WmiObject cmdlet, type:

Get-Help Get-WmiObject -Detailed

    Or, type:

gh Get-WmiObject -Detailed

SAVING ALIASES
    The aliases that you create are saved only in the current session. To use
    the aliases in a different session, add the alias to your Windows 
    PowerShell profile. Or, use the Export-Alias cmdlet to save the aliases to
    a file. 
    
    For more information, type:

        Get-Help about_Profiles

GETTING ALIASES
    To get all the aliases in the current session, including the built-in
    aliases, the aliases in your Windows PowerShell profiles, and the aliases
    that you have created in the current session, type:

Get-Alias
  
    To get particular aliases, use the Name parameter of the Get-Alias cmdlet.
    For example, to get aliases that begin with "p", type:

Get-Alias -Name p*

    To get the aliases for a particular item, use the Definition parameter.
    For example, to get the aliases for the Get-ChildItem cmdlet type:

Get-Alias -Definition Get-ChildItem

 GET-ALIAS OUTPUT

     Get-Alias returns only one type of object, an AliasInfo object 
     (System.Management.Automation.AliasInfo). However, beginning in
     Windows PowerShell 3.0, the name of aliases that don't include a
     hyphen, such as "cd" are displayed in the following format:
 
         <alias> -> <definition>

     For example,

         ac -> Add-Content  

     This makes it very quick and easy to get the information that you
     need. 

     The arrow-based alias name format is not used for aliases that
     include a hyphen. These are likely to be preferred substitute 
     names for cmdlets and functions, instead of typical abbreviations
     or nicknames, and the author might not want them to be as evident.


ALTERNATE NAMES FOR COMMANDS WITH PARAMETERS
    You can assign an alias to a cmdlet, script, function, or executable file.
    However, you cannot assign an alias to a command and its parameters.
    For example, you can assign an alias to the Get-Eventlog cmdlet, but you
    cannot assign an alias to the "Get-Eventlog -LogName System" command.

    However, you can create a function that includes the command. To create a
    function, type the word "function" followed by a name for the function.
    Type the command, and enclose it in braces ({}).

    For example, the following command creates the syslog function. This
    function represents the "Get-Eventlog -LogName System" command:

function syslog {Get-Eventlog -LogName System}

    You can now type "syslog" instead of the command. And, you can create
    aliases for the syslog function.

    For more information about functions, type:

Get-Help about_Functions

ALIAS OBJECTS
     Windows PowerShell aliases are represented by objects that are instances
     of the System.Management.Automation.AliasInfo class. For more information
     about this type of object, see "AliasInfo Class" in the Microsoft 
     Developer Network (MSDN) library at 
     http://go.microsoft.com/fwlink/?LinkId=143644.

     To view the properties and methods of the alias objects, get the
     aliases. Then, pipe them to the Get-Member cmdlet. For example:

Get-Alias | Get-Member

     To view the values of the properties of a specific alias, such as the 
     "dir" alias, get the alias. Then, pipe it to the Format-List cmdlet. For
     example, the following command gets the "dir" alias. Next, the command
     pipes the alias to the Format-List cmdlet. Then, the command uses the 
     Property parameter of Format-List with a wildcard character (*) to display
     all the properties of the "dir" alias. The following command performs
     these tasks:

Get-Alias -Name dir | Format-List -Property *

WINDOWS POWERSHELL ALIAS PROVIDER
    Windows PowerShell includes the Alias provider. The Alias provider lets you
    view the aliases in Windows PowerShell as though they were on a file system
    drive. 

    The Alias provider exposes the Alias: drive. To go into the Alias: drive,
    type:

Set-Location Alias:

    To view the contents of the drive, type:

Get-ChildItem

    To view the contents of the drive from another Windows PowerShell drive,
    begin the path with the drive name. Include the colon (:). For example:

Get-ChildItem -Path Alias:

    To get information about a particular alias, type the drive name and
    the alias name. Or, type a name pattern. For example, to get all the 
    aliases that begin with "p", type:

Get-ChildItem -Path Alias:p*

    For more information about the Windows PowerShell Alias provider,
    type:

Get-Help Alias


SEE ALSO

    New-Alias
    Get-Alias
    set-alias
    export-alias
    import-alias
    get-psprovider
    get-psdrive
    about_functions
    about_profiles
    about_providers













In [ ]:

</div>

1908-powershell-hashtable

1908-powershell-hashtable

overview

Image from Gyazo

jupyter notebook

Usage

basic

In [1]:
$d = @{
  'script' = 'powershell'
  'os' = 'windows 10'
  'date' = Get-Date
}

In [2]:
$d
Name                           Value                                                                                   
----                           -----                                                                                   
date                           02/09/2019 13:47:21                                                                     
script                         powershell                                                                              
os                             windows 10                                                                              


In [3]:
$d['script']
In [4]:
$d.GetType()
IsPublic IsSerial Name                                     BaseType                                                    
-------- -------- ----                                     --------                                                    
True     True     Hashtable                                System.Object                                               


In [5]:
$d['os'].GetType()
IsPublic IsSerial Name                                     BaseType                                                    
-------- -------- ----                                     --------                                                    
True     True     String                                   System.Object                                               


In [6]:
$d['date'].GetType()
IsPublic IsSerial Name                                     BaseType                                                    
-------- -------- ----                                     --------                                                    
True     True     DateTime                                 System.ValueType                                            


Get-Help

In [7]:
Get-Help -Category HelpFile | where-object {$_.Name -match "hash"}
Name                              Category  Module                    Synopsis                                         
----                              --------  ------                    --------                                         
about_Hash_Tables                 HelpFile                            Describes how to create, use, and sort hash ta...


In [72]:
Get-Help about_Hash* | set -Name store
$store -split "`r`n" | set -Name ary_store
$ary_store[0..25] + 'and more .....'
Get-Help about_Hash* | set -Name store
$store -split "`r`n" | set -Name ary_store
$ary_store[0..25] + 'and more .....'
TOPIC
    about_Hash_Tables

SHORT DESCRIPTION
    Describes how to create, use, and sort hash tables in Windows PowerShell.


LONG DESCRIPTION
    A hash table, also known as a dictionary or associative array, is a
    compact data structure that stores one or more key/value pairs. For
    example, a hash table might contain a series of IP addresses and
    computer names, where the IP addresses are the keys and the computer
    names are the values, or vice versa.

    In Windows PowerShell, each hash table is a Hashtable 
    (System.Collections.Hashtable) object.  You can use the properties
    and methods of Hashtable objects in Windows PowerShell.

    Beginning in Windows PowerShell 3.0, you can use the [ordered]
    attribute to create an ordered dictionary
    (System.Collections.Specialized.OrderedDictionary) in Windows PowerShell.
    
    Ordered dictionaries differ from hash tables in that the keys always
    appear in the order in which you list them. The order of keys in a hash
    table is not determined.

and more .....


Initialize

Empty object

In [74]:
$dic = @{}

truthiness and falsiness
In [10]:
if($dic){'true'}else{'false'}
true
In [11]:
if($dic.Count){'true'}else{'false'}
false
In [12]:
$dic.Count
0

Get-Member

In [78]:
$dic | Get-Member -MemberType Property | select Name, Definition
Name           Definition                                  
----           ----------                                  
Count          int Count {get;}                            
IsFixedSize    bool IsFixedSize {get;}                     
IsReadOnly     bool IsReadOnly {get;}                      
IsSynchronized bool IsSynchronized {get;}                  
Keys           System.Collections.ICollection Keys {get;}  
SyncRoot       System.Object SyncRoot {get;}               
Values         System.Collections.ICollection Values {get;}


In [14]:
$dic | Get-Member -MemberType Method | Format-Table Name, Definition
Name              Definition                                                                                           
----              ----------                                                                                           
Add               void Add(System.Object key, System.Object value), void IDictionary.Add(System.Object key, System.O...
Clear             void Clear(), void IDictionary.Clear()                                                               
Clone             System.Object Clone(), System.Object ICloneable.Clone()                                              
Contains          bool Contains(System.Object key), bool IDictionary.Contains(System.Object key)                       
ContainsKey       bool ContainsKey(System.Object key)                                                                  
ContainsValue     bool ContainsValue(System.Object value)                                                              
CopyTo            void CopyTo(array array, int arrayIndex), void ICollection.CopyTo(array array, int index)            
Equals            bool Equals(System.Object obj)                                                                       
GetEnumerator     System.Collections.IDictionaryEnumerator GetEnumerator(), System.Collections.IDictionaryEnumerator...
GetHashCode       int GetHashCode()                                                                                    
GetObjectData     void GetObjectData(System.Runtime.Serialization.SerializationInfo info, System.Runtime.Serializati...
GetType           type GetType()                                                                                       
OnDeserialization void OnDeserialization(System.Object sender), void IDeserializationCallback.OnDeserialization(Syst...
Remove            void Remove(System.Object key), void IDictionary.Remove(System.Object key)                           
ToString          string ToString()                                                                                    


Methods

In [15]:
$dic = @{}
$dic | Get-Member -MemberType Method | foreach-object { $_.Name}
$dic = @{}
$dic | Get-Member -MemberType Method | foreach-object { $_.Name} 
Add
Clear
Clone
Contains
ContainsKey
ContainsValue
CopyTo
Equals
GetEnumerator
GetHashCode
GetObjectData
GetType
OnDeserialization
Remove
ToString


Add

In [18]:
$dic = @{}

In [19]:
$dic.Add('one', 1)
$dic.Add('Two', 2)
$dic.Add('Three', 3)
$dic.Add('one', 1)
$dic.Add('Two', 2)
$dic.Add('Three', 3)

In [20]:
$dic
Name                           Value                                                                                   
----                           -----                                                                                   
one                            1                                                                                       
Three                          3                                                                                       
Two                            2                                                                                       


foreach

In [21]:
foreach($itm in $dic.GetEnumerator())
{
  echo $itm.Key $itm.Value
}
one
1
Three
3
Two
2
In [22]:
foreach($key in $dic.Keys)
{
  echo $Key ($dic[$key] + 10)
}
one
11
Three
13
Two
12

contains

In [23]:
$dic
Name                           Value                                                                                   
----                           -----                                                                                   
one                            1                                                                                       
Three                          3                                                                                       
Two                            2                                                                                       


In [24]:
$dic.Contains('one')
True
In [25]:
$dic.Contains('four')
False
In [26]:
$dic.ContainsValue(4)
False
In [27]:
$dic.ContainsValue(2)
True

Remove and Clear

In [28]:
$dic
Name                           Value                                                                                   
----                           -----                                                                                   
one                            1                                                                                       
Three                          3                                                                                       
Two                            2                                                                                       


In [29]:
$dic.Remove('Two')

In [30]:
$dic
Name                           Value                                                                                   
----                           -----                                                                                   
one                            1                                                                                       
Three                          3                                                                                       


In [31]:
$dic.Remove('Four')

In [32]:
$dic
Name                           Value                                                                                   
----                           -----                                                                                   
one                            1                                                                                       
Three                          3                                                                                       


In [33]:
$dic.Clear()

In [34]:
echo "dic = $dic"
dic = System.Collections.Hashtable
In [35]:
echo "dic---" $dic "+++"
dic---
+++

Clone

In [36]:
$dic_org = @{
  'first' = '1st'
  'second' = '2nd'
  'third' = '3rd'
  'fourth' = '4th'
}

In [37]:
$dic_org
Name                           Value                                                                                   
----                           -----                                                                                   
third                          3rd                                                                                     
first                          1st                                                                                     
second                         2nd                                                                                     
fourth                         4th                                                                                     


In [38]:
$dic_dist = $dic_org

In [39]:
$dic_dist['first'] = '1st step'

In [40]:
$dic_dist
Name                           Value                                                                                   
----                           -----                                                                                   
third                          3rd                                                                                     
first                          1st step                                                                                
second                         2nd                                                                                     
fourth                         4th                                                                                     


In [41]:
$dic_org
Name                           Value                                                                                   
----                           -----                                                                                   
third                          3rd                                                                                     
first                          1st step                                                                                
second                         2nd                                                                                     
fourth                         4th                                                                                     


In [42]:
$dic_dist_deep = $dic_org.Clone()
$dic_dist_deep['first'] = '1st'
$dic_dist_deep = $dic_org.Clone()
$dic_dist_deep['first'] = '1st'

In [43]:
$dic_dist_deep['first']
1st
In [44]:
$dic_org['first']
1st step

hash -> string

In [45]:
$dic_for_conv = @{
  'one' = 1
  'two' = 2
  'three' = 3
}
$dic_for_conv = @{
>>   'one' = 1
>>   'two' = 2
>>   'three' = 3
>> }
>> 

In [46]:
$dic_for_conv
Name                           Value                                                                                   
----                           -----                                                                                   
one                            1                                                                                       
three                          3                                                                                       
two                            2                                                                                       


In [47]:
write-host $dic_for_conv
System.Collections.DictionaryEntry System.Collections.DictionaryEntry System.Collections.DictionaryEntry
In [48]:
echo "dic_for_conv = $dic_for_conv"
dic_for_conv = System.Collections.Hashtable
In [49]:
echo "dic_for_conv = " $dic_for_conv
dic_for_conv = 

Name                           Value                                                                                   
----                           -----                                                                                   
one                            1                                                                                       
three                          3                                                                                       
two                            2                                                                                       


In [50]:
$dic_for_conv.ToString()
System.Collections.Hashtable
In [51]:
$dic_for_conv | Convertto-Csv
#TYPE System.Collections.Hashtable
"IsReadOnly","IsFixedSize","IsSynchronized","Keys","Values","SyncRoot","Count"
"False","False","False","System.Collections.Hashtable+KeyCollection","System.Collections.Hashtable+ValueCollection","System.Object","3"
  • Convertto-Csv Image from Gyazo
In [52]:
$dic_for_conv | Convertto-Csv -NoTypeInformation
"IsReadOnly","IsFixedSize","IsSynchronized","Keys","Values","SyncRoot","Count"
"False","False","False","System.Collections.Hashtable+KeyCollection","System.Collections.Hashtable+ValueCollection","System.Object","3"
In [53]:
$dic_for_conv | Get-Member -MemberType Property

   TypeName: System.Collections.Hashtable

Name           MemberType Definition                                  
----           ---------- ----------                                  
Count          Property   int Count {get;}                            
IsFixedSize    Property   bool IsFixedSize {get;}                     
IsReadOnly     Property   bool IsReadOnly {get;}                      
IsSynchronized Property   bool IsSynchronized {get;}                  
Keys           Property   System.Collections.ICollection Keys {get;}  
SyncRoot       Property   System.Object SyncRoot {get;}               
Values         Property   System.Collections.ICollection Values {get;}


In [54]:
$dic_for_conv | Convertto-Json
{
    "one":  1,
    "three":  3,
    "two":  2
}

Convertto-Json Convertto-Json

In [55]:
echo "dic_for_conv Json = " ; $dic_for_conv | Convertto-Json
dic_for_conv Json = 
{
    "one":  1,
    "three":  3,
    "two":  2
}

hash -> psobj

In [56]:
$jsn = $dic_for_conv | Convertto-Json -Compress

In [57]:
echo "dic_for_conv Json = $jsn"
dic_for_conv Json = {"one":1,"three":3,"two":2}
In [58]:
$psobj = $jsn | ConvertFrom-Json
$psobj
$psobj = $jsn | ConvertFrom-Json
$psobj

one three two
--- ----- ---
  1     3   2



In [59]:
$psobj.ToString()

In [60]:
$psobj | Convertto-Csv -NoType
"one","three","two"
"1","3","2"
In [61]:
$psobj | Convertto-Json -Compre
{"one":1,"three":3,"two":2}
In [82]:
$dic_for_conv | Convertto-Json | ConvertFrom-Json | set -Name psobj2
$dic_for_conv | Convertto-Json | ConvertFrom-Json | set -Name psobj2


In [84]:
$psobj2
one three two
--- ----- ---
  1     3   2


Serialize

In [62]:
$dic_for_serialized = @{
  'one' = '1st'
  'two' = '2nd'
  'three' = '3rd'
}
$dic_for_serialized = @{
>>   'one' = '1st'
>>   'two' = '2nd'
>>   'three' = '3rd'
>> }
>> 

In [63]:
$dic_for_serialized | Export-Clixml dic_for_serialized.clixml

In [64]:
Path                 
----                 
G:\workspace\pwshnote


In [65]:
dir $pwd/*.clixml

    Directory: G:\workspace\pwshnote


Mode                LastWriteTime         Length Name                                                                  
----                -------------         ------ ----                                                                  
-a----       02/09/2019     13:47            990 dic_for_serialized.clixml                                             


In [66]:
cat dic_for_serialized.clixml
<Objs Version="1.1.0.1" xmlns="">http://schemas.microsoft.com/powershell/2004/04">
  <Obj RefId="0">
    <TN RefId="0">
      <T>System.Collections.Hashtable</T>
      <T>System.Object</T>
    </TN>
    <DCT>
      <En>
        <S N="Key">one</S>
        <S N="Value">1st</S>
      </En>
      <En>
        <S N="Key">three</S>
        <S N="Value">3rd</S>
      </En>
      <En>
        <S N="Key">two</S>
        <S N="Value">2nd</S>
      </En>
    </DCT>
  </Obj>
</Objs>
In [67]:
$dic_for_deserialized = Import-Clixml dic_for_serialized.clixml

In [68]:
$dic_for_deserialized
Name                           Value                                                                                   
----                           -----                                                                                   
one                            1st                                                                                     
three                          3rd                                                                                     
two                            2nd                                                                                     


appendix

In [69]:
Get-Help about_Hash_Tables
TOPIC
    about_Hash_Tables

SHORT DESCRIPTION
    Describes how to create, use, and sort hash tables in Windows PowerShell.


LONG DESCRIPTION
    A hash table, also known as a dictionary or associative array, is a
    compact data structure that stores one or more key/value pairs. For
    example, a hash table might contain a series of IP addresses and
    computer names, where the IP addresses are the keys and the computer
    names are the values, or vice versa.

    In Windows PowerShell, each hash table is a Hashtable 
    (System.Collections.Hashtable) object.  You can use the properties
    and methods of Hashtable objects in Windows PowerShell.

    Beginning in Windows PowerShell 3.0, you can use the [ordered]
    attribute to create an ordered dictionary
    (System.Collections.Specialized.OrderedDictionary) in Windows PowerShell.
    
    Ordered dictionaries differ from hash tables in that the keys always
    appear in the order in which you list them. The order of keys in a hash
    table is not determined.

    The keys and value in hash tables are also .NET objects. They are most
    often strings or integers, but they can have any object type. You can also
    create nested hash tables, in which the value of a key is another hash table.

    Hash tables are frequently used because they are very efficient for finding
    and retrieving data. You can use hash tables to store lists and to create
    calculated properties in Windows PowerShell. And, Windows PowerShell has a
    cmdlet, ConvertFrom-StringData, that converts strings to a hash table.


  Syntax
     The syntax of a hash table is as follows:

          @{ <name> = <value>; [<name> = <value> ] ...}

     The syntax of an ordered dictionary is as follows:

          [ordered]@{ <name> = <value>; [<name> = <value> ] ...}

     The [ordered] attribute was introduced in Windows PowerShell 3.0.


  Creating Hash Tables
     To create a hash table, follow these guidelines:

          - Begin the hash table with an at sign (@).

          - Enclose the hash table in braces ({}).

          - Enter one or more key/value pairs for the content of the hash 
            table.

          - Use an equal sign (=) to separate each key from its value.

          - Use a semicolon (;) or a line break to separate the
            key/value pairs.

          - Key that contains spaces must be enclosed in quotation marks.
            Values must be valid Windows PowerShell expressions. Strings 
            must appear in quotation marks, even if they do not include
            spaces.

          - To manage the hash table, save it in a variable.
          
          - When assigning an ordered hash table to a variable, place
            the [ordered] attribute before the "@" symbol. If you place
            it before the variable name, the command fails.


      To create an empty hash table in the value of $hash, type:

          $hash = @{}


      You can also add keys and values to a hash table when you create it. For
      example, the following statement creates a hash table with three keys.

          $hash = @{ Number = 1; Shape = "Square"; Color = "Blue"}


  Creating Ordered Dictionaries
    You can create an ordered dictionary by adding an object of the 
    OrderedDictiory type, but the easiest way to create an ordered 
    dictionary is use the [Ordered] attribute.

    The [ordered] attribute is introduced in Windows PowerShell 3.0.

    Place the attribute immediately before the "@" symbol.

          $hash = [ordered]@{ Number = 1; Shape = "Square"; Color = "Blue"}
    
    You can use ordered dictionaries in the same way that you use hash tables.
    Either type can be used as the value of parameters that take a hash table
    or dictionary (iDictionary). 


    You cannot use the [ordered] attribute to convert or cast a hash
    hash table. If you place the ordered attribute before the variable 
    name, the command fails with the following error message.

        PS C:\> [ordered]$hash = @{}
        At line:1 char:1
        + [ordered]$hash = @{}
        + ~~~~~~~~~~~~~~
        The ordered attribute can be specified only on a hash literal node.
        + CategoryInfo          : ParserError: (:) [], ParentContainsErrorRecordException
        + FullyQualifiedErrorId : OrderedAttributeOnlyOnHashLiteralNode

    To correct the expression, move the [ordered] attribute.     
        PS C:\> $hash = [ordered]@{}


    You can cast an ordered dictionary to a hash table, but you cannot 
    recover the ordered attribute, even if you clear the variable and 
    enter new values. To re-establish the order, you must remove and
    recreate the variable.

        PS C:\> [hashtable]$hash = [ordered]@{ Number = 1; Shape = "Square"; Color = "Blue"}
        PS C:\ps-test> $hash

        Name                           Value
        ----                           -----
        Color                          Blue
        Shape                          Square
        Number                         1


  Displaying Hash Tables 
     To display a hash table that is saved in a variable, type the variable
     name. By default, a hash tables is displayed as a table with one column 
     for keys and one for values.

          C:\PS> $hash
        
          Name                           Value
          ----                           -----
          Shape                          Square
          Color                          Blue
          Number                         1


     Hash tables have Keys and Values properties. Use dot notation to display
     all of the keys or all of the values.

          C:\PS> $hash.keys
          Number
          Shape
          Color
        
          C:\PS> $hash.values
          1
          Square
          Blue
         

     Each key name is also a property of the hash table, and its value is 
     the value of the key-name property. Use the following format to display the
     property values.

          $hashtable.<key>
          <value>     

     For example:

          C:\PS> $hash.Number
          1

          C:\PS> $hash.Color
          Blue
     
    
     Hash tables have a Count property that indicates the number of key-value
     pairs in the hash table.

          C:\PS> $hash.count
          3


     Hash table tables are not arrays, so you cannot use an integer as an
     index into the hash table, but you can use a key name to index into the
     hash table. If the key is a string value, enclose the key name in quotation
     marks.

     For example:

          C:\PS> $hash["Number"]
          1


  Adding and Removing Keys and Values
      To add keys and values to a hash table, use the following command
      format.  

          $hash["<key>"] = "<value>"

      For example, to add a "Time" key with a value of "Now" to the hash
      table, use the following statement format.

          $hash["Time"] = "Now"

      You can also add keys and values to a hash table by using the Add
      method of the System.Collections.Hashtable object. The Add method 
      has the following syntax:

          Add(Key, Value)

      For example, to add a "Time" key with a value of "Now" to the hash
      table, use the following statement format.

          $hash = $hash.Add("Time", "Now")

      And, you can add keys and values to a hash table by using the addition 
      operator (+) to add a hash table to an existing hash table. For example,
      the following statement adds a "Time" key with a value of "Now" to the 
      hash table in the $hash variable.

          $hash = $hash + @{Time="Now"}


      You can also add values that are stored in variables.
      
          $t = "Today"
          $now = (Get-Date)
          
          $hash.Add($t, $now)      

      
      You cannot use a subtraction operator to remove a key/value pair from
      a hash table, but you can use the Remove method of the Hashtable object.
      The Remove method takes the key as its value. 

      The Remove method has the following syntax:

          Remove(Key)          
     

      For example, to remove the Time=Now key/value pair from the hash table in
      the value of the $hash variable, type: 

          $hash.$Remove("Time")


      You can use all of the properties and methods of Hashtable objects in
      Windows PowerShell, including Contains, Clear, Clone, and CopyTo. For
      more information about Hashtable objects, see 
      "System.Collections.Hashtable" on MSDN.



  Object Types in HashTables  
      The keys and values in a hash table can have any .NET object type, 
      and a single hash table can have keys and values of multiple types.

      The following statement creates a hash table of process name strings
      and process object values and saves it in the $p variable.


          $p = @{"PowerShell" = (get-process PowerShell); 
          "Notepad" = (get-process notepad)}


      You can display the hash table in $p and use the key-name properties
      to display the values.


          C:\PS> $p

          Name                           Value
          ----                           -----
          PowerShell                     System.Diagnostics.Process (PowerShell)
          Notepad                        System.Diagnostics.Process (notepad)

     

          C:\PS> $p.PowerShell        
      
          Handles  NPM(K)    PM(K)      WS(K) VM(M)   CPU(s)     Id ProcessName
          -------  ------    -----      ----- -----   ------     -- -----------
              441      24    54196      54012   571     5.10   1788 PowerShell


          C:\PS> $p.keys | foreach {$p.$_.handles}
          441
          251


       The keys in a hash table can also be any .NET type. The following
       statement adds a key/value pair to the hash table in the $p variable.
       The key is a Service object that represents the WinRM service, and the
       value is the current status of the service.

        
           C:\PS> $p = $p + @{(Get-Service WinRM) = ((Get-Service WinRM).Status)}


       You can display and access the new key/value pair by using the same
       methods that you use for other pairs in the hash table.

           C:\PS> $p

           Name                           Value
           ----                           -----
           PowerShell                     System.Diagnostics.Process (PowerShell)
           Notepad                        System.Diagnostics.Process (notepad)
           System.ServiceProcess.Servi... Running

       
           C:\PS> $p.keys
           PowerShell
           Notepad

           Status   Name               DisplayName
           ------   ----               -----------
           Running  winrm              Windows Remote Management (WS-Manag...

            
           C:\PS> $p.keys | foreach {$_.name}
           winrm        


       
       The keys and values in a hash table can also be Hashtable objects. The
       following statement adds key/value pair to the hash table in the $p 
       variable in which the key is a string, Hash2, and the value is a hash
       table with three key/value pairs.


          C:\PS> $p = $p + @{"Hash2"= @{a=1; b=2; c=3}}


       You can display and access the new values by using the same methods.

          C:\PS> $p


          Name                           Value
          ----                           -----
          PowerShell                     System.Diagnostics.Process (PowerShell)
          Notepad                        System.Diagnostics.Process (notepad)
          System.ServiceProcess.Servi... Running
          Hash2                          {a, b, c}


          C:\PS> $p.Hash2

          Name                           Value
          ----                           -----
          a                              1
          b                              2
          c                              3


          C:\PS> $p.Hash2.b
          2
     


  Sorting Keys and Values
      The items in a hash table are intrinsically unordered. The key/value
      pairs might appear in a different order each time that you display
      them.

      Although you cannot sort a hash table, you can use the GetEnumerator
      method of hash tables to enumerate the keys and values, and then use
      the Sort-Object cmdlet to sort the enumerated values for display.

      For example, the following commands enumerate the keys and values
      in the hash table in the $p variable and then sort the keys in 
      alphabetical order.

          C:\PS> $p.GetEnumerator() | Sort-Object -Property key

          Name                           Value
          ----                           -----
          Notepad                        System.Diagnostics.Process (notepad)
          PowerShell                     System.Diagnostics.Process (PowerShell)
          System.ServiceProcess.Servi... Running


          
      The following command uses the same procedure to sort the hash values in 
      descending order.


          C:\PS> $p.getenumerator() | Sort-Object -Property Value -Descending

          Name                           Value
          ----                           -----
          PowerShell                     System.Diagnostics.Process (PowerShell)
          Notepad                        System.Diagnostics.Process (notepad)
          System.ServiceProcess.Servi... Running


  Creating Objects from Hash Tables
      Beginning in Windows PowerShell 3.0, you can create an object from a
      hash table of properties and property values.

       The syntax is as follows:
        [<class-name>]@{<property-name>=<property-value>;<property-name>=<property-value>}

      This method works only for classes that have a null 
      constructor, that is, a constructor that has no parameters. 
      The object properties must be public and settable.

      For more information, see about_Object_Creation.


  ConvertFrom-StringData
      The ConvertFrom-StringData cmdlet converts a string or a here-string of 
      key/value pairs into a hash table. You can use the 
      ConvertFrom-StringData cmdlet safely in the Data section of a script, 
      and you can use it with the Import-LocalizedData cmdlet to display user
      messages in the user-interface (UI) culture of the current user.


      Here-strings are especially useful when the values in the hash table 
      include quotation marks. (For more information about here-strings, see
      about_Quoting_Rules.)


      The following example shows how to create a here-string of the user 
      messages in the previous example and how to use ConvertFrom-StringData
      to convert them from a string into a hash table.


      The following command creates a here-string of the key/value pairs and
      then saves it in the $string variable.


          C:\PS> $string = @"
          Msg1 = Type "Windows".
          Msg2 = She said, "Hello, World."
          Msg3 = Enter an alias (or "nickname").
          "@

   
    This command uses the ConvertFrom-StringData cmdlet to convert the 
    here-string into a hash table.


        C:\PS> ConvertFrom-StringData $string

        Name                           Value
        ----                           -----
        Msg3                           Enter an alias (or "nickname").
        Msg2                           She said, "Hello, World."
        Msg1                           Type "Windows".

    For more information about here-strings, see about_Quoting_Rules.


SEE ALSO
    about_Arrays
    about_Object_Creation
    about_Quoting_Rules
    about_Script_Internationalization 
    ConvertFrom-StringData
    Import-LocalizedData
    "System.Collections.Hashtable" on MSDN












In [ ]:

</div>

1908-powershell-array

1908-powershell-array

jupyter notebook

変数としてのarray の定義

Literalによる定義

In [1]:
$ary = @('power','shell')

In [2]:
$ary
power
shell
In [3]:
$ary_empty = @()

空の配列

In [4]:
$ary_empty

In [5]:
$ary_other_def = 'power', 'shell', 'other', 'array'

In [6]:
$ary_other_def
power
shell
other
array

$ary.GetType()

In [7]:
$ary.GetType() | Format-List

Module                     : CommonLanguageRuntimeLibrary
Assembly                   : mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089
TypeHandle                 : System.RuntimeTypeHandle
DeclaringMethod            : 
BaseType                   : System.Array
UnderlyingSystemType       : System.Object[]
FullName                   : System.Object[]
AssemblyQualifiedName      : System.Object[], mscorlib, Version=4.0.0.0, Culture=neutral, 
                             PublicKeyToken=b77a5c561934e089
Namespace                  : System
GUID                       : 00000000-0000-0000-0000-000000000000
IsEnum                     : False
GenericParameterAttributes : 
IsSecurityCritical         : False
IsSecuritySafeCritical     : False
IsSecurityTransparent      : True
IsGenericTypeDefinition    : False
IsGenericParameter         : False
GenericParameterPosition   : 
IsGenericType              : False
IsConstructedGenericType   : False
ContainsGenericParameters  : False
StructLayoutAttribute      : 
Name                       : Object[]
MemberType                 : TypeInfo
DeclaringType              : 
ReflectedType              : 
MetadataToken              : 33554432
GenericTypeParameters      : {}
DeclaredConstructors       : {Void .ctor(Int32)}
DeclaredEvents             : {}
DeclaredFields             : {}
DeclaredMembers            : {Void Set(Int32, System.Object), System.Object& Address(Int32), System.Object Get(Int32), 
                             Void .ctor(Int32)}
DeclaredMethods            : {Void Set(Int32, System.Object), System.Object& Address(Int32), System.Object Get(Int32)}
DeclaredNestedTypes        : {}
DeclaredProperties         : {}
ImplementedInterfaces      : {System.ICloneable, System.Collections.IList, System.Collections.ICollection, 
                             System.Collections.IEnumerable...}
TypeInitializer            : 
IsNested                   : False
Attributes                 : AutoLayout, AnsiClass, Class, Public, Sealed, Serializable
IsVisible                  : True
IsNotPublic                : False
IsPublic                   : True
IsNestedPublic             : False
IsNestedPrivate            : False
IsNestedFamily             : False
IsNestedAssembly           : False
IsNestedFamANDAssem        : False
IsNestedFamORAssem         : False
IsAutoLayout               : True
IsLayoutSequential         : False
IsExplicitLayout           : False
IsClass                    : True
IsInterface                : False
IsValueType                : False
IsAbstract                 : False
IsSealed                   : True
IsSpecialName              : False
IsImport                   : False
IsSerializable             : True
IsAnsiClass                : True
IsUnicodeClass             : False
IsAutoClass                : False
IsArray                    : True
IsByRef                    : False
IsPointer                  : False
IsPrimitive                : False
IsCOMObject                : False
HasElementType             : True
IsContextful               : False
IsMarshalByRef             : False
GenericTypeArguments       : {}
CustomAttributes           : {[System.SerializableAttribute()]}



$ary | Get-Member

In [28]:
$ary | Get-Member | format-table Name, Definition
Name             Definition                                                                                            
----             ----------                                                                                            
Clone            System.Object Clone(), System.Object ICloneable.Clone()                                               
CompareTo        int CompareTo(System.Object value), int CompareTo(string strB), int IComparable.CompareTo(System.Ob...
Contains         bool Contains(string value)                                                                           
CopyTo           void CopyTo(int sourceIndex, char[] destination, int destinationIndex, int count)                     
EndsWith         bool EndsWith(string value), bool EndsWith(string value, System.StringComparison comparisonType), b...
Equals           bool Equals(System.Object obj), bool Equals(string value), bool Equals(string value, System.StringC...
GetEnumerator    System.CharEnumerator GetEnumerator(), System.Collections.IEnumerator IEnumerable.GetEnumerator(), ...
GetHashCode      int GetHashCode()                                                                                     
GetType          type GetType()                                                                                        
GetTypeCode      System.TypeCode GetTypeCode(), System.TypeCode IConvertible.GetTypeCode()                             
IndexOf          int IndexOf(char value), int IndexOf(char value, int startIndex), int IndexOf(char value, int start...
IndexOfAny       int IndexOfAny(char[] anyOf), int IndexOfAny(char[] anyOf, int startIndex), int IndexOfAny(char[] a...
Insert           string Insert(int startIndex, string value)                                                           
IsNormalized     bool IsNormalized(), bool IsNormalized(System.Text.NormalizationForm normalizationForm)               
LastIndexOf      int LastIndexOf(char value), int LastIndexOf(char value, int startIndex), int LastIndexOf(char valu...
LastIndexOfAny   int LastIndexOfAny(char[] anyOf), int LastIndexOfAny(char[] anyOf, int startIndex), int LastIndexOf...
Normalize        string Normalize(), string Normalize(System.Text.NormalizationForm normalizationForm)                 
PadLeft          string PadLeft(int totalWidth), string PadLeft(int totalWidth, char paddingChar)                      
PadRight         string PadRight(int totalWidth), string PadRight(int totalWidth, char paddingChar)                    
Remove           string Remove(int startIndex, int count), string Remove(int startIndex)                               
Replace          string Replace(char oldChar, char newChar), string Replace(string oldValue, string newValue)          
Split            string[] Split(Params char[] separator), string[] Split(char[] separator, int count), string[] Spli...
StartsWith       bool StartsWith(string value), bool StartsWith(string value, System.StringComparison comparisonType...
Substring        string Substring(int startIndex), string Substring(int startIndex, int length)                        
ToBoolean        bool IConvertible.ToBoolean(System.IFormatProvider provider)                                          
ToByte           byte IConvertible.ToByte(System.IFormatProvider provider)                                             
ToChar           char IConvertible.ToChar(System.IFormatProvider provider)                                             
ToCharArray      char[] ToCharArray(), char[] ToCharArray(int startIndex, int length)                                  
ToDateTime       datetime IConvertible.ToDateTime(System.IFormatProvider provider)                                     
ToDecimal        decimal IConvertible.ToDecimal(System.IFormatProvider provider)                                       
ToDouble         double IConvertible.ToDouble(System.IFormatProvider provider)                                         
ToInt16          int16 IConvertible.ToInt16(System.IFormatProvider provider)                                           
ToInt32          int IConvertible.ToInt32(System.IFormatProvider provider)                                             
ToInt64          long IConvertible.ToInt64(System.IFormatProvider provider)                                            
ToLower          string ToLower(), string ToLower(cultureinfo culture)                                                 
ToLowerInvariant string ToLowerInvariant()                                                                             
ToSByte          sbyte IConvertible.ToSByte(System.IFormatProvider provider)                                           
ToSingle         float IConvertible.ToSingle(System.IFormatProvider provider)                                          
ToString         string ToString(), string ToString(System.IFormatProvider provider), string IConvertible.ToString(S...
ToType           System.Object IConvertible.ToType(type conversionType, System.IFormatProvider provider)               
ToUInt16         uint16 IConvertible.ToUInt16(System.IFormatProvider provider)                                         
ToUInt32         uint32 IConvertible.ToUInt32(System.IFormatProvider provider)                                         
ToUInt64         uint64 IConvertible.ToUInt64(System.IFormatProvider provider)                                         
ToUpper          string ToUpper(), string ToUpper(cultureinfo culture)                                                 
ToUpperInvariant string ToUpperInvariant()                                                                             
Trim             string Trim(Params char[] trimChars), string Trim()                                                   
TrimEnd          string TrimEnd(Params char[] trimChars)                                                               
TrimStart        string TrimStart(Params char[] trimChars)                                                             
Chars            char Chars(int index) {get;}                                                                          
Length           int Length {get;}                                                                                     


In [10]:
Get-Member -InputObject $ary -MemberType Method | format-table Name, Definition
Name          Definition                                                                                               
----          ----------                                                                                               
Add           int IList.Add(System.Object value)                                                                       
Address       System.Object&, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 Address(int )
Clear         void IList.Clear()                                                                                       
Clone         System.Object Clone(), System.Object ICloneable.Clone()                                                  
CompareTo     int IStructuralComparable.CompareTo(System.Object other, System.Collections.IComparer comparer)          
Contains      bool IList.Contains(System.Object value)                                                                 
CopyTo        void CopyTo(array array, int index), void CopyTo(array array, long index), void ICollection.CopyTo(arr...
Equals        bool Equals(System.Object obj), bool IStructuralEquatable.Equals(System.Object other, System.Collectio...
Get           System.Object Get(int )                                                                                  
GetEnumerator System.Collections.IEnumerator GetEnumerator(), System.Collections.IEnumerator IEnumerable.GetEnumerat...
GetHashCode   int GetHashCode(), int IStructuralEquatable.GetHashCode(System.Collections.IEqualityComparer comparer)   
GetLength     int GetLength(int dimension)                                                                             
GetLongLength long GetLongLength(int dimension)                                                                        
GetLowerBound int GetLowerBound(int dimension)                                                                         
GetType       type GetType()                                                                                           
GetUpperBound int GetUpperBound(int dimension)                                                                         
GetValue      System.Object GetValue(Params int[] indices), System.Object GetValue(int index), System.Object GetValu...
IndexOf       int IList.IndexOf(System.Object value)                                                                   
Initialize    void Initialize()                                                                                        
Insert        void IList.Insert(int index, System.Object value)                                                        
Remove        void IList.Remove(System.Object value)                                                                   
RemoveAt      void IList.RemoveAt(int index)                                                                           
Set           void Set(int , System.Object )                                                                           
SetValue      void SetValue(System.Object value, int index), void SetValue(System.Object value, int index1, int inde...
ToString      string ToString()                                                                                        


In [11]:
$ary.Count
2
In [12]:
$ary.ToString()
System.Object[]
In [13]:
$ary.Add('Jupyter')
Exception calling "Add" with "1" argument(s): "Collection was of a fixed size."
At line:1 char:1
+ $ary.Add('Jupyter')
+ ~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : NotSpecified: (:) [], MethodInvocationException
    + FullyQualifiedErrorId : NotSupportedException
 
In [14]:
$ary += 'Jupyter'

In [15]:
Get-Member -InputObject $ary -MemberType Property | format-table Name, Definition
Name           Definition                   
----           ----------                   
IsFixedSize    bool IsFixedSize {get;}      
IsReadOnly     bool IsReadOnly {get;}       
IsSynchronized bool IsSynchronized {get;}   
Length         int Length {get;}            
LongLength     long LongLength {get;}       
Rank           int Rank {get;}              
SyncRoot       System.Object SyncRoot {get;}


In [16]:
$ary
power
shell
Jupyter
In [34]:
$ary | out-Default
power
shell
Jupyter
In [17]:
$ary | foreach-object {$_.GetType().FullName; '>>' + $_}
System.String
>>power
System.String
>>shell
System.String
>>Jupyter
In [18]:
foreach($ar in $ary)
{
  $ar.GetType().FullName
  '>>' + $ar
}
System.String
>>power
System.String
>>shell
System.String
>>Jupyter
In [19]:
$ary.ToString()
System.Object[]
In [20]:
$ary | ConvertTo-Csv
#TYPE System.String
"Length"
"5"
"5"
"7"
In [21]:
$ary | ConvertTo-Csv -NoTypeInformation
"Length"
"5"
"5"
"7"
  • =>渡されたObjectのPropertyをカラムにして、CSVが作成される。この場合、Stringが渡されるので、そのPropertyのLengthがCSVとなる。
In [22]:
ConvertTo-Csv -inputObject $ary -NoTypeInformation
"Count","Length","LongLength","Rank","SyncRoot","IsReadOnly","IsFixedSize","IsSynchronized"
"3","3","3","1","System.Object[]","False","True","False"
In [23]:
ConvertTo-Json -inputObject $ary
[
    "power",
    "shell",
    "Jupyter"
]
In [24]:
$ary | Convertto-Json
[
    "power",
    "shell",
    "Jupyter"
]
In [25]:
$ary -join ','
power,shell,Jupyter
In [26]:
Get-Help about_array
TOPIC
    about_Arrays

SHORT DESCRIPTION
    Describes arrays, which are data structures designed to store 
    collections of items.

LONG DESCRIPTION
    An array is a data structure that is designed to store a collection 
    of items. The items can be the same type or different types.

    Beginning in Windows PowerShell 3.0, a collection of zero or one
    object has some properties of arrays. 


 CREATING AND INITIALIZING AN ARRAY
    To create and initialize an array, assign multiple values to a variable.
    The values stored in the array are delimited with a comma and separated
    from the variable name by the assignment operator (=). 

    For example, to create an array named $A that contains the seven
    numeric (int) values of 22, 5, 10, 8, 12, 9, and 80, type:

        $A = 22,5,10,8,12,9,80

    You can also create and initialize an array by using the range 
    operator (..). For example, to create and initialize an array named 
    "$B" that contains the values 5 through 8, type:

        $B = 5..8

    As a result, $B contains four values: 5, 6, 7, and 8.

    When no data type is specified, Windows PowerShell creates each array as
    an object array (type: System.Object[]). To determine the data type of an array, 
    use the GetType() method. For example, to determine the data type of the
    $a array, type:

        $a.GetType()

    To create a strongly typed array, that is, an array that can contain only
    values of a particular type, cast the variable as an array type, such 
    as string[], long[], or int32[]. To cast an array, precede the variable
    name with an array type enclosed in brackets. For example, to create a
    32-bit integer array named $ia containing four integers (1500, 2230, 3350,
    and 4000), type:

        [int32[]]$ia = 1500,2230,3350,4000

    As a result, the $ia array can contain only integers.

    You can create arrays that are cast to any supported type in the
    Microsoft .NET Framework. For example, the objects that Get-Process 
    retrieves to represent processes are of the System.Diagnostics.Process 
    type. To create a strongly typed array of process objects, enter the 
    following command:

        [Diagnostics.Process[]]$zz = Get-Process

 THE ARRAY SUB-EXPRESSION OPERATOR
    The array sub-expression operator creates an array, even if it 
    contains zero or one object.

    The syntax of the array operator is as follows:
        @( ... )

    You can use the array operator to create an array of zero or 
    one object. 

        PS C:\>$a = @("One")
        PS C:\>$a.Count
        1

        PS C:\>$b = @()
        PS C:\>$b.Count
        0

    The array operator is particularly useful in scripts when
    you are getting objects, but do not know how many objects 
    you will get. 

        PS C:\> $p = @(Get-Process Notepad)

 
    For more information about the array sub-expression operator,
    see about_Operators.

 
  READING AN ARRAY
    You can refer to an array by using its variable name. To display all 
    the elements in the array, type the array name. For example:

$a

    You can refer to the elements in an array by using an index, beginning
    at position 0. Enclose the index number in brackets. For example,
    to display the first element in the $a array, type:

        $a[0]

    To display the third element in the $a array, type:

        $a[2]

    Negative numbers count from the end of the array. For example, "-1" 
    refers to the last element of the array. To display the last three elements
    of the array, type:

        $a[-3..-1]

    However, be cautious when using this notation.

        $a[0..-2]

    This command does not refer to all the elements of the array, except for 
    the last one. It refers to the first, last, and second-to-last elements
    in the array.
   
    You can use the range operator to display a subset of all the values in an 
    array. For example, to display the data elements at index position 1 
    through 3, type:

        $a[1..3]

    You can use the plus operator (+) to combine a range with a list of
    elements in an array. For example, to display the elements at index
    positions 0, 2, and 4 through 6, type:

        $a[0,2+4..6]

    To determine how many items are in an array, use the Length property
    or its Count alias.

        $a.Count


    You can also use looping constructs, such as ForEach, For, and While loops,
    to refer to the elements in an array. For example, to use a ForEach loop
    to display the elements in the $a array, type: 

        foreach ($element in $a) {$element}
 
    The Foreach loop iterates through the array and returns each value in
    the array until reaching the end of the array.

    The For loop is useful when you are incrementing counters while examining
    the elements in an array. For example, to use a For loop to  return every
    other value in an array, type:

        for ($i = 0; $i -le ($a.length - 1); $i += 2) {$a[$i]}

    You can use a While loop to display the elements in an array until a 
    defined condition is no longer true. For example, to display the elements
    in the $a array while the array index is less than 4, type:

        $i=0
        while($i -lt 4) {$a[$i]; $i++}



 GET THE MEMBERS OF AN ARRAY

    To get the properties and methods of an array, such as the Length 
    property and the SetValue method, use the InputObject parameter of the
    Get-Member cmdlet. 

    When you pipe an array to Get-Member, Windows PowerShell sends the items 
    one at a time and Get-Member returns the type of each item
    in the array (ignoring duplicates). 

    When you use the InputObject parameter, Get-Member returns the
    members of the array. 

    For example, the following command gets the members of the array in the
    $a variable.

        Get-Member -InputObject $a

    You can also get the members of an array by typing a comma (,) before
    the value that is piped to the Get-Member cmdlet. The comma makes the 
    array the second item in an array of arrays. Windows PowerShell pipes
    the arrays one at a time and Get-Member returns the members of the array. 

        ,$a | Get-Member

        ,(1,2,3) | Get-Member


 MANIPULATING AN ARRAY
    You can change the elements in an array, add an element to an array, and
    combine the values from two arrays into a third array.

    To change the value of a particular element in an array, specify the
    array name and the index of the element that you want to change, and then
    use the assignment operator (=) to specify a new value for the element. For
    example, to change the value of the second item in the $a array (index
    position 1) to 10, type:

        $a[1] = 10

    You can also use the SetValue method of an array to change a value. The
    following example changes the second value (index position 1) of the $a
    array to 500:

        $a.SetValue(500,1)

    You can use the += operator to add an element to an array. When you use
    it, Windows PowerShell actually creates a new array with the values of the
    original array and the added value. For example, to add an element with a 
    value of 200 to the array in the $a variable, type:

        $a += 200

    It is not easy to delete elements from an array, but you can create a new
    array that contains only selected elements of an existing array. For
    example, to create the $t array with all the elements in the $a array 
    except for the value at index position 2, type:

        $t = $a[0,1 + 3..($a.length - 1)]

    To combine two arrays into a single array, use the plus operator (+). The
    following example creates two arrays, combines them, and then displays
    the resulting combined array.

        $x = 1,3
        $y = 5,9
        $z = $x + $y

    As a result, the $z array contains 1, 3, 5, and 9.


    To delete an array, assign a value of $null to the array. The following
    command deletes the array in the $a variable. 

        $a = $null

    You can also use the Remove-Item cmdlet, but assigning a value of $null
    is faster, especially for large arrays.



 ARRAYS OF ZERO OR ONE
    Beginning in Windows PowerShell 3.0, a collection of zero or one object 
    has the Count and Length property. Also, you can index into an array of
    one object. This feature helps you to avoid scripting errors that occur 
    when a command that expects a collection gets fewer than two items.

    The following examples demonstrate this feature.    
    
    #Zero objects
        $a = $null
        $a.Count
        0
        $a.Length
        0

    #One object
        $a = 4
        $a.Count
        1
        $a.Length
        1
        $a[0]
        4
        $a[-1]
        4


SEE ALSO
    about_Assignment_Operators
    about_Hash_Tables
    about_Operators
    about_For
    about_Foreach
    about_While












reference

In [ ]:

</div>

1908-powershell-alias-grep

1908-powershell-alias-grep

overview

notebook

nbviewer.jupyter.org

log

$PSVersionTable

get-alias | out-string -stream | select-string "new-item"

get-alias | out-string -stream | select-string "Out"

get-alias | out-string -stream | select-string "get-alias"

gal | out-string -stream | sls 'sls'

gal | oss | sls 'dir'

1908-powershell-specialfolder-getfolderpath

1908-powershell-specialfolder-getfolderpath

nbviewer

nbviewer.jupyter.org

code

[Enum]::GetNames('System.Environment+SpecialFolder')

$mydocfolder = [Environment]::GetFolderPath('MyDocuments')

$mydocfolder

$mydocfolder.GetType().FullName

[Environment]::GetFolderPath('ApplicationData')

[Environment]::GetFolderPath('Startup')