How to add a new line after every integer - powershell

I am trying to figure out a way to make a new variable from another to output to a GUI. When I try to just display the variable through a lable it loses its line breaks.
I managed to figure out a solution when working with text but when it comes to numbers it does not work.
Here is what I have tried:
$ActiveUnits = #(Get-MsolAccountSku | Select-Object -ExpandProperty ActiveUnits)
$ActiveUnitsFix = "`n"
foreach ($Unit in $ActiveUnits) {
$ActiveUnitsFix += #($Unit + "`n")
}
The output that I am getting is this:
31425220100002521100001000000100000002137328420
When it should be something like this:
3
14
25
220
10000
25
21
10000
1000000
10000000
213
7
3
28
4
20

You could use the -join parameter for adding the new line if you receive an int array from (Get-MsolAccountSku).ActiveUnits.
[System.Int32[]]$ActiveUnits = (Get-MsolAccountSku).ActiveUnits
[System.String]$ActiveUnitsFix = $ActiveUnits -join [System.Environment]::NewLine
$ActiveUnitsFix

Related

PowerShell one counter behaves differently at some part of a script

I am running a PS script to create an excel file with some text and the corresponding pictures to the text. Till now everything works as expected but when i want to choose the right column for the pictures with a counter something weird happens.
Before the if statement the counter behaves like it should, but as soon i let it output the counter inside the if statement the counter does something weird what i cannot explain.
Part of the Script
pictures is an list of file names
rows_sorted is an list of camera names
foreach ($picture in $pictures) {
foreach ($row in $rows_sorted) {
$xlcounter += 1
Write $xlcounter -> counter looks fine
if ($picture -match $row ) {
$live_picture = "C:\Snapshots\pictures\$picture"
$image = [System.Drawing.Image]::FromFile($live_picture)
$sheet | Add-ExcelImage -Image $image -Row $xlcounter -Column 4 -ResizeCell
$image.Dispose()
Write $xlcounter -> Weird things happen
}
}
}
Example output of counter outside the if statement:
2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
Example output of counter inside the if statement:
2 205 408 611 814 1017 1220 1423 1626 1829 2032 2235 2438 2641 2844 3047 3251 3454 3657 3860 4063
I tried to rename the counter because the same name was used in a few lines before, but that did not help either.

Converting Output to CSV and Out-Grid

I have a file as below.
I want it to convert it to CSV and want to have the out grid view of it for items Drives,Drive Type,Total Space, Current allocation and Remaining space only.
PS C:\> echo $fileSys
Storage system address: 127.0.0.1
Storage system port: 443
HTTPS connection
1: Name = Extreme Performance
Drives = 46 x 3.8T SAS Flash 4
Drive type = SAS Flash
RAID level = 5
Stripe length = 13
Total space = 149464056594432 (135.9T)
Current allocation = 108824270733312 (98.9T)
Remaining space = 40639785861120 (36.9T)
I am new to Powershell but I have tried below code for two of things but it's not even getting me desired output.
$filesys | ForEach-Object {
if ($_ -match '^.+?(?<Total space>[0-9A-F]{4}\.[0-9A-F]{4}\.[0-9A-F]{4}).+?(?<Current allocation>\d+)$') {
[PsCustomObject]#{
'Total space' = $matches['Total space']
'Current allocation' = $matches['Current allocation']
}
}
}
First and foremost, the named capture groups cannot contain spaces.
From the documentation
Named Matched Subexpressions
where name is a valid group name, and subexpression is any valid
regular expression pattern. name must not contain any punctuation
characters and cannot begin with a number.
Assuming this is a single string since your pattern attempts to grab info from multiple lines, you can forego the loop. However, even with that corrected, your pattern does not appear to match the data. It's not clear to me what you are trying to match or your desired output. Hopefully this will get you on the right track.
$filesys = #'
Storage system address: 127.0.0.1
Storage system port: 443
HTTPS connection
1: Name = Extreme Performance
Drives = 46 x 3.8T SAS Flash 4
Drive type = SAS Flash
RAID level = 5
Stripe length = 13
Total space = 149464056594432 (135.9T)
Current allocation = 108824270733312 (98.9T)
Remaining space = 40639785861120 (36.9T)
'#
if($filesys -match '(?s).+total space\s+=\s(?<totalspace>.+?)(?=\r?\n).+allocation\s+=\s(?<currentallocation>.+?)(?=\r?\n)')
{
[PsCustomObject]#{
'Total space' = $matches['totalspace']
'Current allocation' = $matches['currentallocation']
}
}
Total space Current allocation
----------- ------------------
149464056594432 (135.9T) 108824270733312 (98.9T)
Edit
If you just want the values in the parenthesis, modifying to this will achieve it.
if($filesys -match '(?s).+total space.+\((?<totalspace>.+?)(?=\)).+allocation.+\((?<currentallocation>.+?)(?=\))')
{
[PsCustomObject]#{
'Total space' = $matches['totalspace']
'Current allocation' = $matches['currentallocation']
}
}
Total space Current allocation
----------- ------------------
135.9T 36.9T
$unity=[Regex]::Matches($filesys, "\(([^)]*)\)") -replace '[(\)]','' -replace "T",""
$UnityCapacity = [pscustomobject][ordered] #{
Name = "$Display"
"Total" =$unity[0]
"Used" = $unity[1]
"Free" = $unity[2]
'Used %' = [math]::Round(($unity[1] / $unity[0])*100,2)
}``

Cannot add the msExchArchiveGUID in Powershell

I cannot add the GUID value for msExchArchiveGUID in powershell. Error reports of "constraint violation" or "A value for the attribute was not in the acceptable range of values" depending on which powershell cmdlet is used. From what I can tell the value that needs to be input needs to be up to 16 characters. Anything more and it errors. For example, the GUID value I need to write is 5C669E441173CF4394995E43EC8ED9ED. When pasted using ADSIEdit the output looks like: 5C 66 9E 44 11 73 CF 43 94 99 5E 43 EC 8E D9 ED. If I add the same value using Powershell it errors. How can I write the value in Powershell to give the same result like adding using ADSIEdit?
E.g
Set-aduser -identity "someone" -add #{msExchArchiveGUID="A format the works!
"}
The solution is a bit convoluted (and probably obvious to all but me!) which I will show below.. I'm sure a more concise answer is out there..
I get the GUID value using quest (rather that get-remotemailbox)
Get-QADUser -Service domain -Identity someone -IncludeAllProperties|select msExchArchiveGUID
This presents the archive GUID as 5C669E441173CF4394995E43EC8ED9ED
So.....
$oct = "5C669E441173CF4394995E43EC8ED9ED"
$oct1 = $oct.substring(0,2)
$oct2 = $oct.substring(2,2)
$oct3 = $oct.substring(4,2)
$oct4 = $oct.substring(6,2)
$oct5 = $oct.substring(8,2)
$oct6 = $oct.substring(10,2)
$oct7 = $oct.substring(12,2)
$oct8 = $oct.substring(14,2)
$oct9 = $oct.substring(16,4)
$oct10 = $oct.substring(20,12)
$strOut = "$oct4" + "$oct3" + "$oct2" + "$oct1" + "-" + "$oct6" + "$oct5" + "-" + "$oct8" + "$oct7" + "-" + "$oct9" + "-" + "$oct10"
Output is "449E665C-7311-43CF-9499-5E43EC8ED9ED"
$Id = [GUID]("449e665c-7311-43cf-9499-5e43ec8ed9ed")
Set-ADUser -Identity $IPGUser -Clear msexcharchiveGUID
Set-ADUser User -Add #{msexchArchiveGUId=$id}

Re-Use of a line fails as "`r" doesn't move the 'line-pointer' ("`b" fails as well)

As C# does not has the options of powershell's write-progress I start to try to 're-use' the same line:
function ReUseFails {
$x=0
$nDec = 10
while ($true) {
$x++
$a = $x.ToString().PadLeft($nDec)
$z = $x.ToString().PadLeft($nDec)
Write-Host "`r$a $z" -noNewLine
Start-Sleep -s 1
}
}
ReUseFails
I expected because of `r (carriage return) to see in the same line (the next line overrides the prev.):
1 1 # and after 1 Second in that line:
2 2 # after the 2nd second
3 3 # (and so on)
but what I get is
1 1 2 2 3 3 4 4 ...
So the carriage return r has no effect?<br>
Is there a way to 'enable' thisr??
Even when I try to use `b I see additional spots but not a back-space.
Can it be that the DOS-console can do that (to show a spinning wheel) but bot the PS-console?
Regards

How to sum values in a column grouped by values in the other

I have a large file consisting data in 2 columns
100 5
100 10
100 10
101 2
101 4
102 10
102 2
I want to sum the values in 2nd column with matching values in column 1. For this example, the output I'm expecting is
100 25
101 6
102 12
I'm trying to work on this using bash script preferably. Can someone explain me how can I do this
Using awk:
awk '{a[$1]+=$2}END{for(i in a){print i, a[i]}}' inputfile
For your input, it'd produce:
100 25
101 6
102 12
In a perl oneliner
perl -lane "$s{$F[0]} += $F[1]; END { print qq{$_ $s{$_}} for keys %s}" file.txt
You can use an associative array. The first column is the index and the second becomes what you add to it.
#!/bin/bash
declare -A columns=()
while read -r -a line ; do
columns[${line[0]}]=$((${columns[${line[0]}]} + ${line[1]}))
done < "${1}"
for idx in ${!columns[#]} ; do
echo "${idx} ${columns[${idx}]}"
done
Using awk and maintain the order:
awk '!($1 in a){a[$1]=$2; b[++i]=$1;next} {a[$1]+=$2} END{for (k=1; k<=i; k++) print b[k], a[b[k]]}' file
100 25
101 6
102 12
Python is my choice:
d = {}
for line in f.readlines():
key,value = line.split()
if d[key] == None:
d[key] = 0
d[key] += value
print d
Why would you want a bash script?