I've found myriad methods to retrieve data FROM a string with substrings, but what I want to do is create a new string that contains substrings. The reason for this is that I want to pass that string to a CSV through the Export-CSV cmdlet. This is in a PowerShell Forms created app.
So the plan would be to
1). Read the contents of each text box:
(e.g. $endusername.text $endusernumber.text $locationname.text)
2). Store those into a new string with substrings
($formoutput.endusername $formoutput.endusernumber $formoutput.locationname)
3). Output the string to a .CSV
Export-CSV -InputObject $formoutput "c:\output\formoutput.csv"
Basically, if I take any existing cmdlet (say, Get-Mailbox), store its output as a string, and then pass that string through the Export-CSV in the way explained above, it performs exactly the way I like - creating a .CSV with each of the substrings as a column, and the contents of that substring in the appropriately headed column. I just want to be able to do that with a string containing substrings that I define.
I think you are confusing nomenclature a little bit. It sounds like what you want is a custom object not a string. Here is some pseudo-code to get you going in the right direction:
$formOutput = New-Object PsCustomObject -Property #{'EndUserName' = $endUserName.Text;
'EndUserNumber' = $endUserNumber.Text;
'LocationName' = $locatioName.Text}
$formOutput | Export-CSV .\FileName.csv -NoTypeHeader
Related
I'm currently trying to filter a value from a long string I got by using a GET request with the cURL command. The output looks like this:
{"errors":null,"result":{"host_id":"1632","display_name":"notshownhere","hostname":"notshownhere","dnsname":"","ip":"1.1.1.1","host_type_id":"1","checks":[{"check_id":"12851","preset_id":"1","checktype_id":"1","checktype_short_name":"ping","status":"3","status_condition":"ok","status_color":"green","status_change_time":"1589066121","result_short":"1.1.1.1 is alive","result_time":"1591683892"}
My aim is to filter out the host_id from this output. This means, I want to find a way how I can only output the host_id with the number 1632.
I tried out Select-String, but it didn't work because the string is too long.
This looks like JSON and it would be best to use ConvertFrom-Json command on a proper JSON. That results in a PowerShell object where you could use object.'host_id' to retrieve the value.
Parsing the string, you can do the following.
# Assuming $j contains your string
($j | Select-String -Pattern '(?<="host_id":")\d+(?=")').Matches.Value
Since -pattern by default take a regex string, (?<=) contains a positive lookbehind from the current position. (?=) is a positive lookahead. \d+ is one or more digits. Since the command returns a MatchInfo object, you need to access the Value to return the digits.
I have a string in excel that I need to extract a substring from
This is an example of the string:
<\Text Name="Text5"><TextValue>Hostname: hostnamehere</TextValue>
I'm new to regex and powershell, but I'm trying to find a way to extract the "hostname here" portion of the string. It's variable length, so indexing won't be reliable.
since you changed the sample, the comment code i posted won't work. [grin] this will, tho ...
$InStuff = '<\Text Name="Text5"><TextValue>Hostname: hostnamehere</TextValue>'
$InStuff.Split(':')[-1].Split('<')[0].Trim()
output = hostnamehere
if you have a set of sample strings, then you likely otta post them so the code can be arranged to handle the needed variants.
If that were xml, it would be straightforward
[xml]$xml = '<Text Name="Text5"><TextValue>Hostname: hostnamehere</TextValue></Text>'
(-split $xml.text.textvalue)[1]
hostnamehere
I need a PS function that would take input string and generate output collection as per below:
Input:
$someString = "abcd{efg|hijk|lmn|o}pqrs"
Desired output:
$someCollection = #("abcdefgpqrs","abcdhijkpqrs","abcdlmnpqrs","abcdopqrs")
Note: there is going to be at most 1 {...|...|...} expression within the input string; the number of pipes is dynamic and can be anything from 1 to 20 ish.
As I drive the input data, the format of the string to explode does not have to follow exactly the example above; it can be anything else; I am looking for simplicity rather than sophistication.
My question is, is there any RegExp based solution that I could use straight away or should I write my function from the scratch, analysing intput string, detecting all the {s, |s and }s and so on?
Platform: Windows 7 / Windows Server 2012, PowerShell 5.x
You could do this using PowerShell 5 using regex pretty easily:
# define a regex pattern with named groups for all three parts of your string
$pattern = '^(?<pre>[^\{]*)\{(?<exp>.*)\}(?<post>[^\}]*)$'
if($someString -match $pattern){
# grab the first and last parts
$prefix = $Matches['pre']
$postfix = $Matches['post']
# explode the middle part
foreach($part in $Matches['exp'] -split '\|'){
# create a new string for each of the exploded middle parts
"$prefix$part$postfix"
}
}
I got data like this:
3LLO24MACT01 24MOB_6012010051700000020100510105010 123456
It contains different values for different columns when I import it.
Every column is fixed width:
Col#1 is the ID and just 1 long. Meaning it is "3" here.
Col#2 is 3 in length and here "LLO".
Col#3 is 9 in length and "24MACT01 " (notice that the missing ones gets filled up by blanks).
This goes on for 15 columns or so...
Is there a method to quickly cut it into different elements based on sequence length? I couldn't find any.
This can be done with RegEx matching, and creating an array of custom objects. Something like this:
$AllRecords = Get-Content C:\Path\To\File.txt | Where{$_ -match "^(.)(.{3})(.{9})"} | ForEach{
[PSCustomObject]#{
'Col1' = $Matches[1]
'Col2' = $Matches[2]
'Col3' = $Matches[3]
}
}
That will take each line, match by how many characters are specified, and then create an object based off those matches. It collects all objects in an array and could be exported to CSV or whatever. The 'Col1', 'Col2' etc are just generic column headers I suggested due to a lack of better information, and could be anything you wanted.
Edit: Thank you iCodez for showing me, perhaps inadvertantly, that you can specify a language for your code samples!
[Regex]::Matches will do this rather easily. All you need to do is specify a Regex pattern that has . followed by the number of characters you want in curly braces. For example, to match a column of three characters, you would write .{3}. You then do this for all 15 columns.
To demonstrate, I will use a string that contains the first three columns of your example data (since I know their sizes):
PS > $data = '3LLO24MACT01 '
PS > $pattern = '(.{1})(.{3})(.{9})'
PS > ([Regex]::Matches($data, $pattern).Groups).Value
3LLO24MACT01
3
LLO
24MACT01
PS >
Note that the first value outputted will be the text matched be all of the capture groups. If you do not need this, you can remove it with slicing:
$columns = ([Regex]::Matches($data, $pattern).Groups).Value
$columns = $columns[1..$columns.Length]
New-PSObjectFromMatches is a helper function for creating PS Objects from regex matches.
The -Debug option can help with the process of writing the regex.
I need to find a way so that I can read values from an excel file and then replace all the corresponding values in another file accordingly. Basically, I found some discrepancy in one of the automated task we run and I need to convert some values within the file before I send it to the automated task. I have an excel file that list the "wrong" values and their corresponding "correct" values and I need to how Power shell can help me in this.
$docID = $args[0] $docid #Read Z ticker file
$Zfile = 'I:\IS\Rishabh\Z tickers Active.xls' # Find the .rps file imported automatically from schwab trust
$RPSFile= 'L:\Trading\Schwab Trust\Import\CS<%dmmdd-01yy>.RPS'
While (Get-Content $ZFile)
{
$_-cmatch 'A$','B$'| Set-Variable X-ticker # End Loop
}
(Get-Content $RPSfile) | ForEach-Object { $_-replace '%, ' ,'X-ticker' #End Loop }
Set-Content $RPSFile
You don't need to use Powershell. Excel itself has built in mechanisms for doing what you want. For example you could use the LOOKUP function in Excel.