1909-powershell-get-command
1909-powershell-get-command¶
overview¶
- A Usage of get-command cmdlet
jupyter notebook¶
Usage¶
Get-Help¶
In [33]:
Get-Help Get-Command -online
In [1]:
Get-Help Get-Command | Out-String -Stream | Set -Name ary_str
In [2]:
$ary_str.Length
55
In [3]:
$ary_str[0..13]
NAME Get-Command SYNOPSIS Gets all commands. SYNTAX Get-Command [[-Name] <String[]>] [[-ArgumentList] <Object[]>] [-All] [-CommandType {Alias | Function | Filter | Cmdlet | ExternalScript | Application | Script | Workflow | Configuration | All}] [-FullyQualifiedModule <ModuleSpecification[]>] [-ListImported] [-Module <String[]>] [-ParameterName <String[]>] [-ParameterType <PSTypeName[]>] [-ShowCommandInfo] [-Syntax] [-TotalCount <Int32>] [<CommonParameters>]
In [4]:
get-help get-command | set -Name store
In [5]:
$store.GetType().Fullname
System.Management.Automation.PSCustomObject
In [6]:
$store | format-list *
examples : @{example=System.Management.Automation.PSObject[]} inputTypes : @{inputType=@{type=@{name=System.String}; description=System.Management.Automation.PSObject[]}} alertSet : @{alert=System.Management.Automation.PSObject[]} syntax : @{syntaxItem=System.Management.Automation.PSObject[]} parameters : @{parameter=System.Management.Automation.PSObject[]} details : @{description=System.Management.Automation.PSObject[]; verb=Get; noun=Command; name=Get-Command} description : {@{Text=The Get-Command cmdlet gets all commands that are installed on the computer, including cmdlets, aliases, functions, workflows, filters, scripts, and applications. Get-Command gets the commands from Windows PowerShell modules and snap-ins and commands that were imported from other sessions. To get only commands that have been imported into the current session, use the ListImported parameter. }, @{Text=Without parameters, a Get-Command command gets all of the cmdlets, functions, workflows and aliases installed on the computer. A `Get-Command *` command gets all types of commands, including all of the non-Windows PowerShell files in the Path environment variable ($env:path), which it lists in the Application command type. }, @{Text=A Get-Command command that uses the exact name of the command, without wildcard characters, automatically imports the module that contains the command so that you can use the command immediately. To enable, disable, and configure automatic importing of modules, use the $PSModuleAutoLoadingPreference preference variable. For more information, see about_Preference_Variables (http://go.microsoft.com/fwlink/?LinkID=113248) in the Microsoft TechNet library. Get-Command gets its data directly from the command code, unlike Get-Help, which gets its information from help topics. }, @{Text=In Windows PowerShell 2.0, Get-Command gets only commands in current session. It does not get commands from modules that are installed, but not imported. To limit Get-Command in Windows PowerShell 3.0 and later versions to commands in the current session, use the ListImported parameter. }...} relatedLinks : @{navigationLink=System.Management.Automation.PSObject[]} returnValues : @{returnValue=System.Management.Automation.PSObject[]} xmlns:maml : http://schemas.microsoft.com/maml/2004/10 xmlns:command : http://schemas.microsoft.com/maml/dev/command/2004/10 xmlns:dev : http://schemas.microsoft.com/maml/dev/2004/10 xmlns:MSHelp : http://msdn.microsoft.com/mshelp Name : Get-Command Category : Cmdlet Synopsis : Gets all commands. Component : Role : Functionality : PSSnapIn : Microsoft.PowerShell.Core ModuleName : Microsoft.PowerShell.Core
In [7]:
$store.description[0..10]
The Get-Command cmdlet gets all commands that are installed on the computer, including cmdlets, aliases, functions, workflows, filters, scripts, and applications. Get-Command gets the commands from Windows PowerShell modules and snap-ins and commands that were imported from other sessions. To get only commands that have been imported into the current session, use the ListImported parameter. Without parameters, a Get-Command command gets all of the cmdlets, functions, workflows and aliases installed on the computer. A `Get-Command *` command gets all types of commands, including all of the non-Windows PowerShell files in the Path environment variable ($env:path), which it lists in the Application command type. A Get-Command command that uses the exact name of the command, without wildcard characters, automatically imports the module that contains the command so that you can use the command immediately. To enable, disable, and configure automatic importing of modules, use the $PSModuleAutoLoadingPreference preference variable. For more information, see about_Preference_Variables (http://go.microsoft.com/fwlink/?LinkID=113248) in the Microsoft TechNet library. Get-Command gets its data directly from the command code, unlike Get-Help, which gets its information from help topics. In Windows PowerShell 2.0, Get-Command gets only commands in current session. It does not get commands from modules that are installed, but not imported. To limit Get-Command in Windows PowerShell 3.0 and later versions to commands in the current session, use the ListImported parameter. Starting in Windows PowerShell 5.0, results of the Get-Command cmdlet display a Version column by default. A new Version property has been added to the CommandInfo class.
In [8]:
$store.parameters
-All [<SwitchParameter>] Indicates that this cmdlet gets all commands, including commands of the same type that have the same name. By default, Get-Command gets only the commands that run when you type the command name. For more information about the method that Windows PowerShell uses to select the command to run when multiple commands have the same name, see about_Command_Precedence (http://go.microsoft.com/fwlink/?LinkID=113214) in the TechNet library. For information about module-qualified command names and running commands that do not run by default because of a name conflict, see about_Modules (http://go.microsoft.com/fwlink/?LinkID=144311). This parameter was introduced in Windows PowerShell 3.0. In Windows PowerShell 2.0, Get-Command gets all commands by default. Required? false Position? named Default value False Accept pipeline input? True (ByPropertyName) Accept wildcard characters? false -ArgumentList <Object[]> Specifies an array of arguments. This cmdlet gets information about a cmdlet or function when it is used with the specified parameters ("arguments"). The alias for ArgumentList is Args . To detect dynamic parameters that are available only when certain other parameters are used, set the value of ArgumentList to the parameters that trigger the dynamic parameters. To detect the dynamic parameters that a provider adds to a cmdlet, set the value of the ArgumentList parameter to a path in the provider drive, such as WSMan:, HKLM:, or Cert:. When the command is a Windows PowerShell provider cmdlet, enter only one path in each command. The provider cmdlets return only the dynamic parameters for the first path the value of ArgumentList . For information about the provider cmdlets, see about_Providers (http://go.microsoft.com/fwlink/?LinkID=113250) in the TechNet library. Required? false Position? 1 Default value None Accept pipeline input? False Accept wildcard characters? false -CommandType <CommandTypes> Specifies the types of commands that this cmdlet gets. Enter one or more command types. Use CommandType or its alias, Type . By default, Get-Command gets all cmdlets, functions, and workflows, and aliases. The acceptable values for this parameter are: - Alias. Gets the aliases of all Windows PowerShell commands. For more information, see about_Aliases. - All. Gets all command types. This parameter value is the equivalent of `Get-Command *`. - Application. Gets non-Windows-PowerShell files in paths listed in the Path environment variable ($env:path), including .txt, .exe, and .dll files. For more information about the Path environment variable, see about_Environment_Variables. - Cmdlet. Gets all cmdlets. - ExternalScript. Gets all .ps1 files in the paths listed in the Path environment variable ($env:path). - Filter and Function. Gets all Windows PowerShell advanced and simple functions and filters. - Script. Gets all script blocks. To get Windows PowerShell scripts (.ps1 files), use the ExternalScript value. - Workflow. Gets all workflows. For more information about workflows, see Introducing Windows PowerShell Workflow. Required? false Position? named Default value None Accept pipeline input? True (ByPropertyName) Accept wildcard characters? false -FullyQualifiedModule <ModuleSpecification[]> Specifies modules with names that are specified in the form of ModuleSpecification objects, described by the Remarks section of Module Specification Constructor (Hashtable)http://msdn.microsoft.com/library/windows/desktop/jj136290(v=vs.85).aspx on the Microsoft Developer Network (MSDN). For example, the FullyQualifiedModule parameter accepts a module name that is specified in the format @{ModuleName = "modulename"; ModuleVersion = "version_number"} or @{ModuleName = "modulename"; ModuleVersion = "version_number"; Guid = "GUID"}. ModuleName and ModuleVersion are required, but Guid is optional. You cannot specify the FullyQualifiedModule parameter in the same command as a Module parameter. The two parameters are mutually exclusive. Required? false Position? named Default value None Accept pipeline input? True (ByPropertyName) Accept wildcard characters? false -ListImported [<SwitchParameter>] Indicates that this cmdlet gets only commands in the current session. Starting in Windows PowerShell 3.0, by default, Get-Command gets all installed commands, including, but not limited to, the commands in the current session. In Windows PowerShell 2.0, it gets only commands in the current session. This parameter was introduced in Windows PowerShell 3.0. Required? false Position? named Default value False Accept pipeline input? True (ByPropertyName) Accept wildcard characters? false -Module <String[]> Specifies an array of modules. This cmdlet gets the commands that came from the specified modules or snap-ins. Enter the names of modules or snap-ins, or enter snap-in or module objects. This parameter takes string values, but the value of this parameter can also be a PSModuleInfo or PSSnapinInfo object, such as the objects that the Get-Module, Get-PSSnapin, and Import-PSSession cmdlets return. You can refer to this parameter by its name, Module , or by its alias, PSSnapin . The parameter name that you choose has no effect on the command output. Required? false Position? named Default value None Accept pipeline input? True (ByPropertyName) Accept wildcard characters? false -Name <String[]> Specifies an array of names. This cmdlet gets only commands that have the specified name. Enter a name or name pattern. Wildcard characters are permitted. To get commands that have the same name, use the All parameter. When two commands have the same name, by default, Get-Command gets the command that runs when you type the command name. Required? false Position? 0 Default value None Accept pipeline input? True (ByPropertyName, ByValue) Accept wildcard characters? false -Noun <String[]> Specifies an array of command nouns. This cmdlet gets commands, which include cmdlets, functions, workflows, and aliases, that have names that include the specified noun. Enter one or more nouns or noun patterns. Wildcard characters are permitted. Required? false Position? named Default value None Accept pipeline input? True (ByPropertyName) Accept wildcard characters? false -ParameterName <String[]> Specifies an array of parameter names. This cmdlet gets commands in the session that have the specified parameters. Enter parameter names or parameter aliases. Wildcard characters are supported. The ParameterName and ParameterType parameters search only commands in the current session. This parameter was introduced in Windows PowerShell 3.0. Required? false Position? named Default value None Accept pipeline input? False Accept wildcard characters? false -ParameterType <PSTypeName[]> Specifies an array of parameter names. This cmdlet gets commands in the session that have parameters of the specified type. Enter the full name or partial name of a parameter type. Wildcard characters are supported. The ParameterName and ParameterType parameters search only commands in the current session. This parameter was introduced in Windows PowerShell 3.0. Required? false Position? named Default value None Accept pipeline input? False Accept wildcard characters? false -ShowCommandInfo [<SwitchParameter>] Indicates that this cmdlet displays command information. For more information about the method that Windows PowerShell uses to select the command to run when multiple commands have the same name, see about_Command_Precedence. For information about module-qualified command names and running commands that do not run by default because of a name conflict, see about_Modules. This parameter was introduced in Windows PowerShell 3.0. In Windows PowerShell 2.0, Get-Command gets all commands by default. Required? false Position? named Default value False Accept pipeline input? False Accept wildcard characters? false -Syntax [<SwitchParameter>] Indicates that this cmdlet gets only the following specified data about the command: - Aliases. Gets the standard name. - Cmdlets. Gets the syntax. - Functions and filters. Gets the function definition. - Scripts and applications or files. Gets the path and filename. Required? false Position? named Default value False Accept pipeline input? True (ByPropertyName) Accept wildcard characters? false -TotalCount <Int32> Specifies the number of commands to get. You can use this parameter to limit the output of a command. Required? false Position? named Default value None Accept pipeline input? True (ByPropertyName) Accept wildcard characters? false -Verb <String[]> Specifies an array of command verbs. This cmdlet gets commands, which include cmdlets, functions, workflows, and aliases, that have names that include the specified verb. Enter one or more verbs or verb patterns. Wildcard characters are permitted. Required? false Position? named Default value None Accept pipeline input? True (ByPropertyName) Accept wildcard characters? false <CommonParameters> This cmdlet supports the common parameters: Verbose, Debug, ErrorAction, ErrorVariable, WarningAction, WarningVariable, OutBuffer, PipelineVariable, and OutVariable. For more information, see about_CommonParameters (https:/go.microsoft.com/fwlink/?LinkID=113216).
Show-Commnad¶
In [9]:
Show-Command Get-Command
Get-Command¶
In [41]:
Get-Command -Noun Item | select Name | format-wide
Clear-Item Copy-Item Get-Item Invoke-Item Move-Item New-Item Remove-Item Rename-Item Set-Item
Get-Alias¶
In [10]:
get-alias | Out-String -stream | select-string 'command'
CommandType Name Version Source Alias gcm -> Get-Command Alias icm -> Invoke-Command Alias shcm -> Show-Command Alias trcm -> Trace-Command
System.Management.Automation.CmdletInfo¶
In [11]:
(gcm get-item).GetType().Fullname
System.Management.Automation.CmdletInfo
In [12]:
gcm get-item | format-list *
gcm get-item | format-list * HelpUri : https://go.microsoft.com/fwlink/?LinkID=113319 DLL : C:\WINDOWS\Microsoft.Net\assembly\GAC_MSIL\Microsoft.PowerShell.Commands.Management\v4.0_3.0.0.0_ _31bf3856ad364e35\Microsoft.PowerShell.Commands.Management.dll Verb : Get Noun : Item HelpFile : Microsoft.PowerShell.Commands.Management.dll-Help.xml PSSnapIn : Version : 3.1.0.0 ImplementingType : Microsoft.PowerShell.Commands.GetItemCommand Definition : Get-Item [-Path] <string[]> [-Filter <string>] [-Include <string[]>] [-Exclude <string[]>] [-Force] [-Credential <pscredential>] [-UseTransaction] [-Stream <string[]>] [<CommonParameters>] Get-Item -LiteralPath <string[]> [-Filter <string>] [-Include <string[]>] [-Exclude <string[]>] [-Force] [-Credential <pscredential>] [-UseTransaction] [-Stream <string[]>] [<CommonParameters>] DefaultParameterSet : Path OutputType : {System.IO.FileInfo, System.Boolean, System.String, System.IO.FileInfo...} Options : ReadOnly Name : Get-Item CommandType : Cmdlet Source : Microsoft.PowerShell.Management Visibility : Public ModuleName : Microsoft.PowerShell.Management Module : Microsoft.PowerShell.Management RemotingCapability : PowerShell Parameters : {[Path, System.Management.Automation.ParameterMetadata], [LiteralPath, System.Management.Automation.ParameterMetadata], [Filter, System.Management.Automation.ParameterMetadata], [Include, System.Management.Automation.ParameterMetadata]...} ParameterSets : {[-Path] <string[]> [-Filter <string>] [-Include <string[]>] [-Exclude <string[]>] [-Force] [-Credential <pscredential>] [-UseTransaction] [-Stream <string[]>] [<CommonParameters>], -LiteralPath <string[]> [-Filter <string>] [-Include <string[]>] [-Exclude <string[]>] [-Force] [-Credential <pscredential>] [-UseTransaction] [-Stream <string[]>] [<CommonParameters>]}
Get-Verb¶
In [13]:
get-verb | set -Name ary_verb
get-verb | set -Name ary_verb
In [14]:
$ary_verb | where {$_.Group -eq 'Common'}
Verb Group ---- ----- Add Common Clear Common Close Common Copy Common Enter Common Exit Common Find Common Format Common Get Common Hide Common Join Common Lock Common Move Common New Common Open Common Optimize Common Pop Common Push Common Redo Common Remove Common Rename Common Reset Common Resize Common Search Common Select Common Set Common Show Common Skip Common Split Common Step Common Switch Common Undo Common Unlock Common Watch Common
In [15]:
$ary_verb | where {$_.Group -eq 'Data'} | select Verb | format-wide
Backup Checkpoint Compare Compress Convert ConvertFrom ConvertTo Dismount Edit Expand Export Group Import Initialize Limit Merge Mount Out Publish Restore Save Sync Unpublish Update
In [16]:
$ary_verb | where {$_.Group -eq 'LifeCycle'} | fw verb
Approve Assert Complete Confirm Deny Disable Enable Install Invoke Register Request Restart Resume Start Stop Submit Suspend Uninstall Unregister Wait
In [17]:
$ary_verb | where {$_.Group -eq 'Diagnostic'} | fw verb
Debug Measure Ping Repair Resolve Test Trace
In [18]:
$ary_verb | where {$_.Group -eq 'Communications'} | fw verb
Connect Disconnect Read Receive Send Write
In [19]:
$ary_verb | where {$_.Group -in @('security','other')} | fw verb
Block Grant Protect Revoke Unblock Unprotect Use
Nouns¶
In [36]:
Get-Command | set -Name ary_cmd
Get-Verb | select Verb | foreach {$_.Verb}|set -Name ary_verb
$nouns = @(
"Acl","Alias","Certificate","ChildItem","Clipboard",
"Clixml","Command","Computer","ComputerInfo","Console",
"Content","ControlPanelItem","Counter","Credential",
"Csv","Culture","Custom","Date","Debug","Debugger",
"DedupProperties","Default","Error","Event","EventLog",
"ExecutionPolicy","Expression","File","FormatData","GridView",
"Guid","Help","Hex","History","Host","HotFix","Html","Information",
"InstalledModule","InstalledScript","IseSnippet","Item",
"ItemProperty","ItemPropertyValue","Job","JobTrigger","Json",
"List","LocalizedData","Location","MailMessage","Member",
"Mock","Module","ModuleManifest","ModuleMember","Null","Object",
"ObjectEvent","OdbcDriver","OdbcDsn","OdbcPerfCounter","Output",
"PSBreakpoint","PSCallStack","PSDebug","PSDrive","PSSnapin",
"Package","PackageProvider","PackageSource","Path","Pester","
PesterOption","Process","Progress","Random","RecycleBin",
"RestMethod","Script","ScriptFileInfo","SecureString",
"Service","Sleep","String","StringData","Table","TemporaryFile",
"TimeSpan","TimeZone","Trace","TraceSource","Transaction",
"Transcript","TroubleshootingPack","Type","TypeData",
"UICulture","Unique","Variable","Verb","Verbose","Warning",
"WebRequest","WebServiceProxy","Wide","WinEvent",
"WinHomeLocation","WindowsEdition","WmiEvent","WmiInstance",
"WmiMethod","WmiObject","Xml"
)
Get-Command | set -Name ary_cmd Get-Verb | select Verb | foreach {$_.Verb}|set -Name ary_verb $nouns = @( >> "Acl","Alias","Certificate","ChildItem","Clipboard", >> "Clixml","Command","Computer","ComputerInfo","Console", >> "Content","ControlPanelItem","Counter","Credential", >> "Csv","Culture","Custom","Date","Debug","Debugger", >> "DedupProperties","Default","Error","Event","EventLog", >> "ExecutionPolicy","Expression","File","FormatData","GridView", >> "Guid","Help","Hex","History","Host","HotFix","Html","Information", >> "InstalledModule","InstalledScript","IseSnippet","Item", >> "ItemProperty","ItemPropertyValue","Job","JobTrigger","Json", >> "List","LocalizedData","Location","MailMessage","Member", >> "Mock","Module","ModuleManifest","ModuleMember","Null","Object", >> "ObjectEvent","OdbcDriver","OdbcDsn","OdbcPerfCounter","Output", >> "PSBreakpoint","PSCallStack","PSDebug","PSDrive","PSSnapin", >> "Package","PackageProvider","PackageSource","Path","Pester"," >> PesterOption","Process","Progress","Random","RecycleBin", >> "RestMethod","Script","ScriptFileInfo","SecureString", >> "Service","Sleep","String","StringData","Table","TemporaryFile", >> "TimeSpan","TimeZone","Trace","TraceSource","Transaction", >> "Transcript","TroubleshootingPack","Type","TypeData", >> "UICulture","Unique","Variable","Verb","Verbose","Warning", >> "WebRequest","WebServiceProxy","Wide","WinEvent", >> "WinHomeLocation","WindowsEdition","WmiEvent","WmiInstance", >> "WmiMethod","WmiObject","Xml" >> ) >>
In [37]:
$ary = @()
$dic = @{}
$arylist = New-Object System.Collections.ArrayList
$arylist.Clear()
foreach($ar in $ary_cmd)
{
$buf = $ar -split '-'
if($buf[0] -in $ary_verb)
{
$null = $arylist.Add(@($buf[0], $buf[1]))
# $buf[0] + ' : ' + $buf[1]
}
}
Get-Command | set -Name ary_cmd
In [22]:
$i = 0
foreach($a in $arylist)
{
if($a[1] -in $nouns){
if($a[1] -in $dic.Keys)
{
$dic[$a[1]] += $a[0]
}else{
$dic[$a[1]] = @()
$dic[$a[1]] += $a[0]
}
$i++
# if($i -gt 100){break}
}
}
$i = 0 foreach($a in $arylist)
In [23]:
$dic.GetEnumerator() |
Sort-Object { $_.key } |
select key, value | set -Name ordered
>> { >> if($a[1] -in $nouns){ >> if($a[1] -in $dic.Keys) >> { >> $dic[$a[1]] += $a[0] >> }else{ >> $dic[$a[1]] = @() >> $dic[$a[1]] += $a[0] >> } >> $i++ >> # if($i -gt 100){break} >> } >> } >> $dic.GetEnumerator() | >> Sort-Object { $_.key } | >> select key, value | set -Name ordered >>
In [24]:
$ordered[0..26]
Key Value --- ----- Acl {Get, Set} Alias {Export, Get, Import, New...} Certificate {Export, Get, Import, Switch...} ChildItem {Get} Clipboard {Get, Set} Clixml {Export, Import} Command {Find, Get, Invoke, Measure...} Computer {Add, Checkpoint, Remove, Rename...} ComputerInfo {Get} Console {Export} Content {Add, Clear, Get, Set} ControlPanelItem {Get, Show} Counter {Export, Get, Import} Credential {Get} Csv {ConvertFrom, ConvertTo, Export, Import} Culture {Get, Set} Custom {Format} Date {Get, Set} Debug {Write} Debugger {Wait} DedupProperties {Get} Default {Out} Error {Write} Event {Get, New, Remove, Unregister...} EventLog {Clear, Get, Limit, New...} ExecutionPolicy {Get, Set} Expression {Invoke}
In [25]:
$ordered[27..77]
Key Value --- ----- File {Out, Unblock} FormatData {Export, Get, Update} GridView {Out} Guid {New} Help {Get, Save, Update} Hex {Format} History {Add, Clear, Get, Invoke} Host {Clear, Get, Out, Read...} HotFix {Get} Html {ConvertTo} Information {Write} InstalledModule {Get} InstalledScript {Get} IseSnippet {Get, Import, New} Item {Clear, Copy, Get, Invoke...} ItemProperty {Clear, Copy, Get, Move...} ItemPropertyValue {Get} Job {Debug, Get, Receive, Remove...} JobTrigger {Add, Disable, Enable, Get...} Json {ConvertFrom, ConvertTo} List {Format, Update} LocalizedData {Import} Location {Get, Pop, Push, Set} MailMessage {Send} Member {Add, Get} Mock {Invoke} Module {Find, Install, Publish, Save...} ModuleManifest {Update, New, Test} ModuleMember {Export} Null {Out} Object {Compare, Group, Measure, New...} ObjectEvent {Register} OdbcDriver {Get, Set} OdbcDsn {Add, Get, Remove, Set} OdbcPerfCounter {Disable, Enable, Get} Output {Write} Package {Find, Get, Install, Save...} PackageProvider {Find, Get, Import, Install} PackageSource {Get, Register, Set, Unregister} Path {Convert, Join, Resolve, Split...} Pester {Invoke} Process {Debug, Get, Start, Stop...} Progress {Write} PSBreakpoint {Disable, Enable, Get, Remove...} PSCallStack {Get} PSDebug {Set} PSDrive {Get, New, Remove} PSSnapin {Add, Get, Remove} Random {Get} RecycleBin {Clear} RestMethod {Invoke}
In [26]:
$ordered[78..$ordered.Length]
Key Value --- ----- Script {Find, Install, Publish, Save...} ScriptFileInfo {New, Test, Update} SecureString {ConvertFrom, ConvertTo} Service {Get, New, Restart, Resume...} Sleep {Start} String {ConvertFrom, Convert, Out, Select} StringData {ConvertFrom} Table {Format} TemporaryFile {New} TimeSpan {New} TimeZone {Get, Set} Trace {Start, Stop, Export} TraceSource {Get, Set} Transaction {Complete, Get, Start, Undo...} Transcript {Start, Stop} TroubleshootingPack {Get, Invoke} Type {Add} TypeData {Get, Remove, Update} UICulture {Get} Unique {Get} Variable {Clear, Get, New, Remove...} Verb {Get} Verbose {Write} Warning {Write} WebRequest {Invoke} WebServiceProxy {New} Wide {Format} WindowsEdition {Get, Set} WinEvent {Get, New} WinHomeLocation {Get, Set} WmiEvent {Register} WmiInstance {Set} WmiMethod {Invoke} WmiObject {Get, Remove} Xml {ConvertTo, Select}
Get-Command and modules¶
In [27]:
get-module | ft Name, ModuleType, ExportedCommands
Name ModuleType ExportedCommands ---- ---------- ---------------- Microsoft.PowerShell.Management Manifest {[Add-Computer, Add-Computer], [Add-Content, Add-Content], [Checkpoint-Co... Microsoft.PowerShell.Utility Manifest {[Add-Member, Add-Member], [Add-Type, Add-Type], [Clear-Variable, Clear-V... PSReadline Script {[Get-PSReadlineKeyHandler, Get-PSReadlineKeyHandler], [Get-PSReadlineOpt...
In [28]:
get-command -Module *.powershell.management | fw Name
Add-Computer Add-Content Checkpoint-Computer Clear-Content Clear-EventLog Clear-Item Clear-ItemProperty Clear-RecycleBin Complete-Transaction Convert-Path Copy-Item Copy-ItemProperty Debug-Process Disable-ComputerRestore Enable-ComputerRestore Get-ChildItem Get-Clipboard Get-ComputerInfo Get-ComputerRestorePoint Get-Content Get-ControlPanelItem Get-EventLog Get-HotFix Get-Item Get-ItemProperty Get-ItemPropertyValue Get-Location Get-Process Get-PSDrive Get-PSProvider Get-Service Get-TimeZone Get-Transaction Get-WmiObject Invoke-Item Invoke-WmiMethod Join-Path Limit-EventLog Move-Item Move-ItemProperty New-EventLog New-Item New-ItemProperty New-PSDrive New-Service New-WebServiceProxy Pop-Location Push-Location Register-WmiEvent Remove-Computer Remove-EventLog Remove-Item Remove-ItemProperty Remove-PSDrive Remove-WmiObject Rename-Computer Rename-Item Rename-ItemProperty Reset-ComputerMachinePassword Resolve-Path Restart-Computer Restart-Service Restore-Computer Resume-Service Set-Clipboard Set-Content Set-Item Set-ItemProperty Set-Location Set-Service Set-TimeZone Set-WmiInstance Show-ControlPanelItem Show-EventLog Split-Path Start-Process Start-Service Start-Transaction Stop-Computer Stop-Process Stop-Service Suspend-Service Test-ComputerSecureChannel Test-Connection Test-Path Undo-Transaction Use-Transaction Wait-Process Write-EventLog
In [29]:
Get-Command -module Microsoft.PowerShell.Utility -CommandTYpe cmdlet | fw Name
Add-Member Add-Type Clear-Variable Compare-Object ConvertFrom-Csv ConvertFrom-Json ConvertFrom-String ConvertFrom-StringData Convert-String ConvertTo-Csv ConvertTo-Html ConvertTo-Json ConvertTo-Xml Debug-Runspace Disable-PSBreakpoint Disable-RunspaceDebug Enable-PSBreakpoint Enable-RunspaceDebug Export-Alias Export-Clixml Export-Csv Export-FormatData Export-PSSession Format-Custom Format-List Format-Table Format-Wide Get-Alias Get-Culture Get-Date Get-Event Get-EventSubscriber Get-FormatData Get-Host Get-Member Get-PSBreakpoint Get-PSCallStack Get-Random Get-Runspace Get-RunspaceDebug Get-TraceSource Get-TypeData Get-UICulture Get-Unique Get-Variable Group-Object Import-Alias Import-Clixml Import-Csv Import-LocalizedData Import-PSSession Invoke-Expression Invoke-RestMethod Invoke-WebRequest Measure-Command Measure-Object New-Alias New-Event New-Object New-TimeSpan New-Variable Out-File Out-GridView Out-Printer Out-String Read-Host Register-EngineEvent Register-ObjectEvent Remove-Event Remove-PSBreakpoint Remove-TypeData Remove-Variable Select-Object Select-String Select-Xml Send-MailMessage Set-Alias Set-Date Set-PSBreakpoint Set-TraceSource Set-Variable Show-Command Sort-Object Start-Sleep Tee-Object Trace-Command Unblock-File Unregister-Event Update-FormatData Update-List Update-TypeData Wait-Debugger Wait-Event Write-Debug Write-Error Write-Host Write-Information Write-Output Write-Progress Write-Verbose Write-Warning
In [30]:
Get-Command -verb out | ft Name, Source
Get-Command -verb out | ft Name, Source Name Source ---- ------ Out-Default Microsoft.PowerShell.Core Out-File Microsoft.PowerShell.Utility Out-GridView Microsoft.PowerShell.Utility Out-Host Microsoft.PowerShell.Core Out-Null Microsoft.PowerShell.Core Out-Printer Microsoft.PowerShell.Utility Out-String Microsoft.PowerShell.Utility
In [31]:
Get-Command -verb write | ft Name, Source
Name Source ---- ------ Write-FileSystemCache Storage Write-DtcTransactionsTraceSession MsDtc Write-PrinterNfcTag PrintManagement Write-VolumeCache Storage Write-Debug Microsoft.PowerShell.Utility Write-Error Microsoft.PowerShell.Utility Write-EventLog Microsoft.PowerShell.Management Write-Host Microsoft.PowerShell.Utility Write-Information Microsoft.PowerShell.Utility Write-Output Microsoft.PowerShell.Utility Write-Progress Microsoft.PowerShell.Utility Write-Verbose Microsoft.PowerShell.Utility Write-Warning Microsoft.PowerShell.Utility
Appendix¶
In [32]:
Get-Help Get-Command
NAME Get-Command SYNOPSIS Gets all commands. SYNTAX Get-Command [[-Name] <String[]>] [[-ArgumentList] <Object[]>] [-All] [-CommandType {Alias | Function | Filter | Cmdlet | ExternalScript | Application | Script | Workflow | Configuration | All}] [-FullyQualifiedModule <ModuleSpecification[]>] [-ListImported] [-Module <String[]>] [-ParameterName <String[]>] [-ParameterType <PSTypeName[]>] [-ShowCommandInfo] [-Syntax] [-TotalCount <Int32>] [<CommonParameters>] Get-Command [[-ArgumentList] <Object[]>] [-All] [-FullyQualifiedModule <ModuleSpecification[]>] [-ListImported] [-Module <String[]>] [-Noun <String[]>] [-ParameterName <String[]>] [-ParameterType <PSTypeName[]>] [-ShowCommandInfo] [-Syntax] [-TotalCount <Int32>] [-Verb <String[]>] [<CommonParameters>] DESCRIPTION The Get-Command cmdlet gets all commands that are installed on the computer, including cmdlets, aliases, functions, workflows, filters, scripts, and applications. Get-Command gets the commands from Windows PowerShell modules and snap-ins and commands that were imported from other sessions. To get only commands that have been imported into the current session, use the ListImported parameter. Without parameters, a Get-Command command gets all of the cmdlets, functions, workflows and aliases installed on the computer. A `Get-Command *` command gets all types of commands, including all of the non-Windows PowerShell files in the Path environment variable ($env:path), which it lists in the Application command type. A Get-Command command that uses the exact name of the command, without wildcard characters, automatically imports the module that contains the command so that you can use the command immediately. To enable, disable, and configure automatic importing of modules, use the $PSModuleAutoLoadingPreference preference variable. For more information, see about_Preference_Variables (http://go.microsoft.com/fwlink/?LinkID=113248) in the Microsoft TechNet library. Get-Command gets its data directly from the command code, unlike Get-Help, which gets its information from help topics. In Windows PowerShell 2.0, Get-Command gets only commands in current session. It does not get commands from modules that are installed, but not imported. To limit Get-Command in Windows PowerShell 3.0 and later versions to commands in the current session, use the ListImported parameter. Starting in Windows PowerShell 5.0, results of the Get-Command cmdlet display a Version column by default. A new Version property has been added to the CommandInfo class. RELATED LINKS Online Version: http://go.microsoft.com/fwlink/?LinkId=821482 Get-Help REMARKS To see the examples, type: "get-help Get-Command -examples". For more information, type: "get-help Get-Command -detailed". For technical information, type: "get-help Get-Command -full". For online help, type: "get-help Get-Command -online"
</div>
1909-powershell-datetime
1909-powershell-datetime¶
overview¶
- datetime object on powershell
jupyter notebook¶
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]:
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>
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]:
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]:
reference¶
- 【PowerShell】TimeSpanオブジェクトを作成する
- Use PowerShell and Conditional Formatting to Format Time Spans
- PowerShellのGet-Date -Formatで出力される標準の書式指定結果一覧
</div>
1909-powershell-alias
1909-powershell-alias¶
overview¶
- overview of alias on powershell
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
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
Definition Name HelpUri ---------- ---- ------- Add-Content ac https://go.microsoft.com/fwlink/?LinkID=113278 Clear-Content clc https://go.microsoft.com/fwlink/?LinkID=113282 Get-Content type https://go.microsoft.com/fwlink/?LinkID=113310 Get-Content gc https://go.microsoft.com/fwlink/?LinkID=113310 Get-Content cat https://go.microsoft.com/fwlink/?LinkID=113310 Set-Content sc https://go.microsoft.com/fwlink/?LinkID=113392
In [41]:
Get-Alias | Where-Object {$_.Definition -match 'Item$'} | Sort-Object Definition | Format-Table Definition, Name, HelpUri
Definition Name HelpUri ---------- ---- ------- Clear-Item cli https://go.microsoft.com/fwlink/?LinkID=113283 Copy-Item cpi https://go.microsoft.com/fwlink/?LinkID=113292 Copy-Item cp https://go.microsoft.com/fwlink/?LinkID=113292 Copy-Item copy https://go.microsoft.com/fwlink/?LinkID=113292 Get-ChildItem gci https://go.microsoft.com/fwlink/?LinkID=113308 Get-ChildItem ls https://go.microsoft.com/fwlink/?LinkID=113308 Get-ChildItem dir https://go.microsoft.com/fwlink/?LinkID=113308 Get-Item gi https://go.microsoft.com/fwlink/?LinkID=113319 Invoke-Item ii https://go.microsoft.com/fwlink/?LinkID=113345 Move-Item mi https://go.microsoft.com/fwlink/?LinkID=113350 Move-Item move https://go.microsoft.com/fwlink/?LinkID=113350 Move-Item mv https://go.microsoft.com/fwlink/?LinkID=113350 New-Item ni https://go.microsoft.com/fwlink/?LinkID=113353 Remove-Item ri https://go.microsoft.com/fwlink/?LinkID=113373 Remove-Item rmdir https://go.microsoft.com/fwlink/?LinkID=113373 Remove-Item rm https://go.microsoft.com/fwlink/?LinkID=113373 Remove-Item del https://go.microsoft.com/fwlink/?LinkID=113373 Remove-Item rd https://go.microsoft.com/fwlink/?LinkID=113373 Remove-Item erase https://go.microsoft.com/fwlink/?LinkID=113373 Rename-Item rni https://go.microsoft.com/fwlink/?LinkID=113382 Rename-Item ren https://go.microsoft.com/fwlink/?LinkID=113382 Set-Item si https://go.microsoft.com/fwlink/?LinkID=113395
In [86]:
Get-Alias -Definition '*Location' | Sort-Object Definition | Format-Table Definition, Name, HelpUri
Definition Name HelpUri ---------- ---- ------- Get-Location pwd https://go.microsoft.com/fwlink/?LinkID=113321 Get-Location gl https://go.microsoft.com/fwlink/?LinkID=113321 Pop-Location popd https://go.microsoft.com/fwlink/?LinkID=113369 Push-Location pushd https://go.microsoft.com/fwlink/?LinkID=113370 Set-Location sl https://go.microsoft.com/fwlink/?LinkID=113397 Set-Location chdir https://go.microsoft.com/fwlink/?LinkID=113397 Set-Location cd https://go.microsoft.com/fwlink/?LinkID=113397
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
Definition Name HelpUri ---------- ---- ------- Compare-Object diff https://go.microsoft.com/fwlink/?LinkID=113286 Compare-Object compare https://go.microsoft.com/fwlink/?LinkID=113286 ForEach-Object foreach https://go.microsoft.com/fwlink/?LinkID=113300 ForEach-Object % https://go.microsoft.com/fwlink/?LinkID=113300 Get-WmiObject gwmi https://go.microsoft.com/fwlink/?LinkID=113337 Group-Object group https://go.microsoft.com/fwlink/?LinkID=113338 Measure-Object measure https://go.microsoft.com/fwlink/?LinkID=113349 Remove-WMIObject rwmi https://go.microsoft.com/fwlink/?LinkID=113381 Select-Object select https://go.microsoft.com/fwlink/?LinkID=113387 Sort-Object sort https://go.microsoft.com/fwlink/?LinkID=113403 Tee-Object tee https://go.microsoft.com/fwlink/?LinkID=113417 Where-Object where https://go.microsoft.com/fwlink/?LinkID=113423 Where-Object ? https://go.microsoft.com/fwlink/?LinkID=113423
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
Definition Name HelpUri ---------- ---- ------- ForEach-Object foreach https://go.microsoft.com/fwlink/?LinkID=113300 ForEach-Object % https://go.microsoft.com/fwlink/?LinkID=113300 Group-Object group https://go.microsoft.com/fwlink/?LinkID=113338 Measure-Object measure https://go.microsoft.com/fwlink/?LinkID=113349 Select-Object select https://go.microsoft.com/fwlink/?LinkID=113387 Sort-Object sort https://go.microsoft.com/fwlink/?LinkID=113403 Tee-Object tee https://go.microsoft.com/fwlink/?LinkID=113417 Where-Object where https://go.microsoft.com/fwlink/?LinkID=113423 Where-Object ? https://go.microsoft.com/fwlink/?LinkID=113423
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
Definition Name HelpUri ---------- ---- ------- Clear-Host clear http://technet.microsoft.com/library/hh852689(v=wps.630).aspx Copy-Item cp https://go.microsoft.com/fwlink/?LinkID=113292 Copy-Item copy https://go.microsoft.com/fwlink/?LinkID=113292 Get-ChildItem dir https://go.microsoft.com/fwlink/?LinkID=113308 Get-ChildItem ls https://go.microsoft.com/fwlink/?LinkID=113308 Get-Content type https://go.microsoft.com/fwlink/?LinkID=113310 Get-Content cat https://go.microsoft.com/fwlink/?LinkID=113310 Get-Location pwd https://go.microsoft.com/fwlink/?LinkID=113321 help man https://go.microsoft.com/fwlink/?LinkID=113316 Move-Item move https://go.microsoft.com/fwlink/?LinkID=113350 Move-Item mv https://go.microsoft.com/fwlink/?LinkID=113350 Remove-Item rm https://go.microsoft.com/fwlink/?LinkID=113373 Remove-Item rmdir https://go.microsoft.com/fwlink/?LinkID=113373 Remove-Item del https://go.microsoft.com/fwlink/?LinkID=113373 Rename-Item ren https://go.microsoft.com/fwlink/?LinkID=113382 Set-Location cd https://go.microsoft.com/fwlink/?LinkID=113397 Set-Location chdir https://go.microsoft.com/fwlink/?LinkID=113397 Set-Variable set https://go.microsoft.com/fwlink/?LinkID=113401 Write-Output write https://go.microsoft.com/fwlink/?LinkID=113427 Write-Output echo https://go.microsoft.com/fwlink/?LinkID=113427
In [75]:
Definition Name HelpUri ---------- ---- ------- Get-History history https://go.microsoft.com/fwlink/?LinkID=113317 Get-Process ps https://go.microsoft.com/fwlink/?LinkID=113324 Invoke-WebRequest wget https://go.microsoft.com/fwlink/?LinkID=217035 Invoke-WebRequest curl https://go.microsoft.com/fwlink/?LinkID=217035 powershell_ise.exe ise Start-Sleep sleep https://go.microsoft.com/fwlink/?LinkID=113407 Stop-Process kill https://go.microsoft.com/fwlink/?LinkID=113412
In [77]:
$ary_other_rare = @(
'sls', 'fl', 'ft','gm','gal'
)
Get-Alias | Where {$_.Name -in $ary_other_rare} | Sort Definition | Select Definition, Name, HelpUri
Definition Name HelpUri ---------- ---- ------- Format-List fl https://go.microsoft.com/fwlink/?LinkID=113302 Format-Table ft https://go.microsoft.com/fwlink/?LinkID=113303 Get-Alias gal https://go.microsoft.com/fwlink/?LinkID=113306 Get-Member gm https://go.microsoft.com/fwlink/?LinkID=113322 Select-String sls https://go.microsoft.com/fwlink/?LinkID=113388
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¶
- hashtable object on powershell
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
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
dic_for_conv Json = { "one": 1, "three": 3, "two": 2 }
hash -> psobj¶
In [56]:
$jsn = $dic_for_conv | Convertto-Json -Compress
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 [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"
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¶
- How do I convert an array object to a string in PowerShell?
In [ ]:
</div>
1908-powershell-alias-grep
1908-powershell-alias-grep
overview
- powershellのAliasを、grepする
notebook
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
code
[Enum]::GetNames('System.Environment+SpecialFolder') $mydocfolder = [Environment]::GetFolderPath('MyDocuments') $mydocfolder $mydocfolder.GetType().FullName [Environment]::GetFolderPath('ApplicationData') [Environment]::GetFolderPath('Startup')
Quote saved.
Login to quote this blog
Failed to save quote. Please try again later.
You cannot quote because this article is private.