powershell:qnd:powershell

Differences

This shows you the differences between two versions of the page.

Link to this comparison view

Both sides previous revision Previous revision
Next revision
Previous revision
powershell:qnd:powershell [2023/01/27 23:22] – [Loops/Iteration] mguptonpowershell:qnd:powershell [2024/10/24 14:24] (current) – [Select Objects] mgupton
Line 35: Line 35:
 </code> </code>
  
-===== Data Types =====+====== Data Types ======
   * Use ''$var.GetType()'' to get data type of variable   * Use ''$var.GetType()'' to get data type of variable
   * [[https://docs.microsoft.com/en-us/powershell/scripting/learn/deep-dives/everything-about-hashtable|hashtables]]   * [[https://docs.microsoft.com/en-us/powershell/scripting/learn/deep-dives/everything-about-hashtable|hashtables]]
Line 50: Line 50:
 </code> </code>
  
 +<code powershell>
 +$foo = @(
 +       "alpha"
 +       "beta"
 +       "gamma"
 +       )
 +</code>
 ==== hash table ==== ==== hash table ====
 <code powershell> <code powershell>
Line 63: Line 70:
   * If a variable name contains spaces it needs to be wrapped in quotes (e.g. ''$obj."First Name"'' or ''{}''. This might happen with imported CSV data, for example.   * If a variable name contains spaces it needs to be wrapped in quotes (e.g. ''$obj."First Name"'' or ''{}''. This might happen with imported CSV data, for example.
  
-===== Control Structures ===== +====== Control Structures ====== 
-===== Loops/Iteration =====+====== Loops/Iteration ======
 ==== For Loop ==== ==== For Loop ====
- 
 <code powershell> <code powershell>
 $fruit = @('apple','pear','banana','lemon','lime','mango') $fruit = @('apple','pear','banana','lemon','lime','mango')
Line 91: Line 97:
  
 ==== Hash Table ==== ==== Hash Table ====
-  * To loop over the items in a hash table you have to call ''GetEnumerator()'' on the hash table.+  * To loop over the items in a hash table one option is to call ''GetEnumerator()'' on the hash table. 
 + 
 +<code powershell> 
 +$t1 = @{firstname = "Michael"; lastname = "Muse"
 + 
 +foreach ($i in $t1.GetEnumerator()) { 
 +    $i.value 
 +
 +</code> 
 + 
 +=== Alternatively use the keys === 
 + 
 +<code powershell> 
 +$t1 = @{firstname = "Michael"; lastname = "Muse"
 + 
 +foreach ($i in $t1.keys) { 
 +    $t1[$i] 
 +
 +</code>
  
 ====== Select-String ====== ====== Select-String ======
Line 107: Line 131:
 Example of getting just the first item of the listed output Example of getting just the first item of the listed output
 <code powershell> <code powershell>
-ls | select first 1+ls | select -first 1
 </code> </code>
  
  • powershell/qnd/powershell.1674861757.txt.gz
  • Last modified: 2023/01/27 23:22
  • by mgupton