Powershell Get-Content + Array - arrays

how's it going?
I'm new on Powershell and I'm trying to simplify my code in order that I need to perform the same action in two files, the only thing that changes is the File Name and ReadCount size (15000 for the first file and 50000 for the second one).
When I run it the error shows:
Get-Content : An object at the specified path
C:\Folder\08_configuration_items 11_CI-Contract-new[0].csv does not
exist, or has been filtered by the -Include or -Exclude parameter. At
line:2 char:7
+ $i=0; Get-Content "C:\Folder\$fileArray[$len].csv" -ReadCount $sizeA ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : ObjectNotFound: (System.String[]:String[]) [Get-Content], Exception
+ FullyQualifiedErrorId : ItemNotFound,Microsoft.PowerShell.Commands.GetContentCommand
Get-Content : An object at the specified path
C:\Folder\08_configuration_items 11_CI-Contract-new[0]_1.csv does not
exist, or has been filtered by the -Include or -Exclude parameter. At
line:3 char:20
+ ... bookContent = Get-Content "C:\Folder\$fileArray[$len]_1.csv" | Selec ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : ObjectNotFound: (System.String[]:String[]) [Get-Content], Exception
+ FullyQualifiedErrorId : ItemNotFound,Microsoft.PowerShell.Commands.GetContentCommand
That's the code, not sure if I'm accessing the Array using the right way on Powershell.
$sizeArray = #(15000,50000)
$fileArray = #("08_configuration_items", "11_CI-Contract-new")
for($len=0; $len -le 1; $len++) {
$i=0; Get-Content "C:\Folder\$fileArray[$len].csv" -ReadCount $sizeArray[$len] | %{$i++; $_ | Out-File "C:\Folder\$fileArray[$len]_$i.csv" -Encoding "UTF8"}
$WorkbookContent = Get-Content "C:\Folder\$fileArray[$len]_1.csv" | Select -Index 0
for($j=2; $j -le $i; $j++) {
$CurrentFileContent = Get-Content "C:\Folder\$fileArray[$len]_$j.csv"
#($WorkbookContent, $CurrentFileContent) | Set-Content "C:\Folder\$fileArray[$len]_$j.csv"
}
}
Any ideias?
Thanks a lot

The problem here is with string interpolation. A variable name within a string will expand up until it reaches a special character in that name. Then it will append the remainder of the string and any interpolated strings afterwards. This commonly happens with the . character when accessing a property of an object within a string. A simple solution is to use the subexpression operator ($()).
Get-Content "C:\Folder\$($fileArray[$len]).csv"
An alternative is to build the path string another way and then pass it into the command. The method below uses the format operator (-f).
$Path = "C:\Folder\{0}.csv" -f $fileArray[$len]
Get-Content $Path
Your code with the subexpression operator added will look like the following:
$sizeArray = #(15000,50000)
$fileArray = #("08_configuration_items", "11_CI-Contract-new")
for($len=0; $len -le 1; $len++) {
$i=0; Get-Content "C:\Folder\$($fileArray[$len]).csv" -ReadCount $sizeArray[$len] | %{$i++; $_ | Out-File "C:\Folder\$($fileArray[$len])_$i.csv" -Encoding "UTF8"}
$WorkbookContent = Get-Content "C:\Folder\$($fileArray[$len])_1.csv" | Select -Index 0
for($j=2; $j -le $i; $j++) {
$CurrentFileContent = Get-Content "C:\Folder\$($fileArray[$len])_$j.csv"
#($WorkbookContent, $CurrentFileContent) | Set-Content "C:\Folder\$($fileArray[$len])_$j.csv"
}
}
You can see this behavior on a simpler scale using your $fileArray variable.
$filearray
08_configuration_items
11_CI-Contract-new
# Notice how the [0] gets appended to the string-cast $fileArray
"$filearray[0]"
08_configuration_items 11_CI-Contract-new[0]
$filearray[0]
08_configuration_items
"$($filearray[0])"
08_configuration_items
Since $fileArray is an array of strings, you have another unintended effect. With "$fileArray[0]", $fileArray will be interpolated and converted to a string output rather than an array. PowerShell by default will join array elements by a single space when casting as a string. So the resulting output format is arrayItem1 arrayItem2 arrayItem3[0]. [0] is not included as part of the variable evaluation.

Related

Powershell build array with each item a new line [duplicate]

This question already has an answer here:
Powershell: Piping output of pracl command to array
(1 answer)
Closed 1 year ago.
Using Get-ChildItem I have pulled a list of files that meet a criteria, then split a part of the Basename and want to build an array with that part of the name. I can do that successfully, except the array returns on long string. I'd like each part of the array to return on a new line.
Script:
$files = GCI "\\Paths" -Recurse | Where-Object {$_.LastWriteTime -ge (Get-Date).Adddays(-22)}
$name = ""
foreach($file in $files){
$file = $file.basename.Split(".")[0]
$array += $file
}
I also tried the following with no luck:
$files = GCI "\\Paths" -Recurse | Where-Object {$_.LastWriteTime -ge (Get-Date).Adddays(-22)}
$name = ""
foreach($file in $files){
$file = $file.basename.Split(".")[0]
$array+= $file -split "`n"
}
Current outcome when calling $array:
file01file02file03file04
Desired outcome when calling $array:
file01
file02
file03
file04
The string is returned because $array is not an array. It is typed at assignment and its first assignment is a string. Therefore it keeps appending new values to that string.
You may do the following instead:
$array = foreach($file in $files){
$file.basename.Split(".")[0]
}
When iterated values are output within a foreach statement, that statement output can be captured into a variable. Each value will be an element of an array.
As an aside, the += syntax to add elements to an array is inefficient because a new array is created each time after retrieving all the contents of the current array.
You're already returning an array, so just narrow it down to what you're assigning to your variable.
$files = GCI "\\Paths" -Recurse |
Where-Object {$_.LastWriteTime -ge (Get-Date).Adddays(-22)} |
ForEach-Object -Process {
$_.basename.Split(".")[0]
}
Or, just assign a variable to your foreach loop removing the output to an array.:
$arr = foreach (...)

Powershell for loop throwing "the array index evaluated to null"

For starters, I'm on Fedora 30 using PSCore version 6.2.1. I've encountered this issue in GNOME Terminal and the vscode snap.
I'm on the first challenge of the PSKoans module and I'm stuck when trying to use a for loop. I am given an array of strings, each of which is a collection of strings separated by commas.
$StockData = #(
"Date,Open,High,Low,Close,Volume,Adj Close"
"2012-03-30,32.40,32.41,32.04,32.26,31749400,32.26"
"2012-03-29,32.06,32.19,31.81,32.12,37038500,32.12"
) # The array is much longer than that, but shortened for simplicity's sake
So, my idea is to build a hashtable out of each subsequent string line in the array by using the first string in the array as keys and each following line as a set of values. I'm using -split to split the values apart from within the strings. I want to use a for loop to iterate through the array and pull values, building a hastable in a file to be read later like so:
# Build the array of keys
[array]$keys = $StockData[0] -split ','
# Begin for loop, using $i as int
for ($i = 1, $StockData[$i], $i++) {
# Create a text file for each hastable
New-Item -Name "ht$i.txt" -ItemType File
# Split current string into values
$values = $StockData[$i] -split ','
# Set value int
$valuesInt = 0
foreach ($key in $keys) {
Add-Content -Path "./ht$i.txt" -Value "$key = $values[$valuesInt]"
$valuesInt++
}
}
As I run that, I get the following error:
Index operation failed; the array index evaluated to null.
At /home/user/PSKoans/Foundations/SolutionStockChallenge.ps1:28 char:6
+ for ($i = 1, $stockData[$i], $i++) {
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidOperation: (:) [], RuntimeException
+ FullyQualifiedErrorId : NullArrayIndex
I've looked it up and I find all kinds of scenarios in which people get this error message. I didn't really find a solid explanation for the error message the might lead me to an answer.
Reading the error message, it doesn't make sense to me. the array index evaluated to null...but the array index in the first case is $StockData[1] which is a valid index and should return $true and continue with the loop. Am I missing something?
The syntax of your for loop is wrong. The for loop uses semi-colons as separators.
for ($i = 1, $StockData[$i], $i++) {
should be
for ($i = 1; $StockData[$i]; $i++) {
ConvertFrom-Json in PowerShell Core has the coolest switch - AsHashTable. Try this:
$StockData | convertfrom-csv | convertto-json | ConvertFrom-Json -AsHashtable

Convert txt to array in powershell

I have a powershell script and a txt database with different number of elements per line.
My txt file is list.txt:
"10345","doomsday","life","hope","run","stone"
"10346","ride","latest","metal"
My powershell script search.ps1:
#Get file path
$path = Split-Path $script:MyInvocation.MyCommand.Path
$search = #()
Get-Content -LiteralPath "$path\list.txt" | ForEach-Object {
$search += $_
}
So, how to convert each line as a element of array? As this:
$search = #(("10345","doomsday","life","hope","run","stone"),("10346","ride","latest","metal"))
To operate as:
echo $search[0][0]
Here's a concise PSv4+ solution:
$search = (Get-Content -LiteralPath $path\list.txt).ForEach({ , ($_ -split ',') })
The .ForEach() method operates on each line read from the input file by Get-Content.
$_ -split ',' splits each line into an array of strings by separator ,
, (...) wraps this array in an aux. single-item array to ensure that the array is effectively output as a whole, resulting in an array of arrays as the overall output.
Note: Strictly speaking, the .ForEach() method outputs a [System.Collections.ObjectModel.Collection[psobject]] collection rather than a regular PowerShell array ([object[]]), but for all practical purposes the two types act the same.
Note: The .ForEach() method was chosen as a faster alternative to a pipeline with the ForEach-Object (%) cmdlet.
Note that the .ForEach() method requires storing the input collection in memory as a whole first.
A faster and more memory-efficient, though perhaps slightly obscure alternative is to use a switch statement with the -file option:
$search = switch -file $path\list.txt { default { , ($_ -split ',') } }
switch -file processes each line of the specified file.
Since each line should be processed, only a default branch is used, in which the desired splitting is performed.
Use -split. A code snippet you can debug in ISE or VSCode below.
$x1 = #'
"10345","doomsday","life","hope","run","stone"
"10346","ride","latest","metal"
'#
$data = $x1 -split "`r`n"
$data.Count
$data[0] -split ","
$arr = #()
foreach ($row in $data)
{
$arr += ,($row -split ",")
}
"arr"
$arr
"0,3"
$arr[0][3]
"1,3"
$arr[1][3]
So you can split each line in your file returned from Get-Content and add it to your new array which lets you reference how you wanted...
There are other ways you can use your data depending on your needs.
Assuming you do not want each item quoted, you might consider to not using the -Split operator but just evaluating each line with the Invoke-Expression cmdlet or using a more secure [ScriptBlock] for this:
$Search = Get-Content ".\list.txt" | ForEach-Object {,#(&([ScriptBlock]::Create($_)))}

PowerShell: Sort Drive Encryption Status for Custom Output

I'm trying to get the encryption status of all drives on a Windows system and sort that list in a custom formatted output. I need this because the output is going to a Nagios server; it messes up the formatting of the standard output for Get-BitLockerVolume and is too long.
Here's what I have so far. I'm trying to sort the output in such a manner that the system drive is listed first and gives the mount point (drive letter) along with the percentage.
[array]$DriveTypes = Get-BitLockerVolume | Sort-Object VolumeType | Select-Object VolumeType
[array]$DriveMounts = Get-BitLockerVolume | Sort-Object VolumeType | Select-Object MountPoint
[array]$WDEPercent = Get-BitLockerVolume | Sort-Object VolumeType | Select-Object EncryptionPercentage
for ($i = 0; $i -lt $DriveTypes.Count; $i++) {
if ($DriveIndex -eq $DriveTypes.Count) {
$TextDriveListing = $TextDriveListing + $DriveMounts.MountPoint+" ("+$DriveTypes.VolumeType+") at "+$WDEPercent.EncryptionPercentage+"%."
}
else {
$TextDriveListing = $TextDriveListing + $DriveMounts.MountPoint+" ("+$DriveTypes.VolumeType+") at "+$WDEPercent.EncryptionPercentage+"%, "
}
if ($WDEPercent.EncryptionPercentage -lt $ReqValue) {
$NoEncryptFlag = 1
}
}
My desired output, for example, is this:
C: (OperatingSystem) at 100%, D: (Data) at 0%.
What I actually end up with is this:
C: D: (OperatingSystem Data) at 100 0%, C: D: (OperatingSystem Data) at 100 0%,
I did try something deriving from an answer to "How to sort a Multi Dimensional Array in Powershell" to test it out, commenting out my aforementioned for block and putting in:
$ListDrives | ForEach-Object {
Get-BitLockerVolume #{
MountPoint = $_[0]
EncryptionPercentage = $_[1]
}
} | Sort-Object VolumeType
Write-Host $ListDrives
That spit out this error:
Cannot index into a null array.
At C:****************.ps1:142 char:3
Get-BitLockerVolume #{
~~~~~~~~~~~~~~~~~~~~~~
CategoryInfo : InvalidOperation: (:) [], RuntimeException
FullyQualifiedErrorId : NullArray
What am I doing wrong? Any suggestions?
Thanks so much in advance!
Try this:
for ($i = 0; $i -lt $DriveTypes.Count; $i++) {
if ($i -eq ($DriveTypes.Count - 1)) {
$TextDriveListing = $TextDriveListing + $DriveMounts[$i].MountPoint+" ("+$DriveTypes[$i].VolumeType+") at "+$WDEPercent[$i].EncryptionPercentage+"%."
}
else {
$TextDriveListing = $TextDriveListing + $DriveMounts[$i].MountPoint+" ("+$DriveTypes[$i].VolumeType+") at "+$WDEPercent[$i].EncryptionPercentage+"%, "
}
if ($WDEPercent[$i].EncryptionPercentage -lt $ReqValue) {
$NoEncryptFlag = 1
}
}
You weren't using the $i from your For Loop to access specific indexes in your collections (i've added [$i] to each of your collection variables to do so). You were also using a variable called $DriveIndex that was never populated and I think this needed to be comparing to $i also, however the logic was also one that would never be true because the For loop would end before it was so (so i've changed the logic to ($i -eq ($DriveTypes.Count - 1)).
Here's a tidier version that I think also gets you the same result:
$TextDriveListing = ''
$Drives = Get-BitLockerVolume | Sort-Object VolumeType | Select VolumeType,MountPoint,EncryptionPercentage
$Drives | ForEach-Object {
$TextDriveListing += "$($_.MountPoint) ($($_.VolumeType)) at $($_.EncryptionPercentage)%,"
If ($_.EncryptionPercentage -lt $ReqValue) { $NoEncryptFlag = 1 }
} -End { $TextDriveListing -Replace ',$','.' }
Uses a single variable for the three properties you wanted to access, rather than putting them in to separate variables which was unnecessary.
Uses a ForEach-Object loop to access each item (and their properties) in that collection via the special token $_.
Uses a single double quoted string for output, with the object/properties accessed via the subexpression operator $().
Puts a comma on the end of each line, but then at the End of the ForEach, uses regex to replace the comma at the end of the line (regex: $ token) with a full stop.
Both sets of code are untested, so may need tweaking.

How do I get an array of strings from a powershell pipeline?

I have a list of directory names that I want to convert to absolute paths, and strip out any invalid ones. My initial attempt at doing this was the pipeline
$dirs = 'dir1', 'dir2', 'dir3'
$paths = $dirs | % { Resolve-Path -ea 0 $_ } | Select -ExpandProperty Path
However, what I get back has type [Object[]] rather than [String[]]. I tried ensuring that the paths existed (by adding a ? { Test-Path $_ } step to the pipeline, but that didn't help.
What am I doing wrong? How do I get the directories as a list of strings? I need this so that I can concatenate the array to another array of strings, specifically
$newpath = (($env:PATH -split ';'), $paths) -join ';'
object[] is simply the default array in PowerShell, and it doesn't matter in this (and most) situations. You problem is that you're trying to join to arrays using (arr1, arr2). What this acutally does is create an array with two array objects, because , is an array construction operator. Try to join the arrays using +, like this:
$dirs = 'dir1', 'dir2', 'dir3'
$paths = $dirs | % { Resolve-Path -ea 0 $_ } | Select -ExpandProperty Path
$newpath = (($env:PATH -split ';') + $paths) -join ';'
and you could even skip the splitting, and just do
$dirs = 'dir1', 'dir2', 'dir3'
$paths = $dirs | % { Resolve-Path -ea 0 $_ } | Select -ExpandProperty Path
$newpath = "$env:PATH;$($paths -join ';')"
This seems to work:
$newpath = (#($env:PATH) + $paths) -join ';'
You don't really need to explicitly cast it as [string[]]. Powershell will figure that out from the command context and coerce the data to the proper type.

Resources