PowerShell to search for a negativ value and replace it - search

This is my data:
"Number";"Name";"Manufacturer";"Brand ID";"EAN";"Price";"Currency Code";"StockLevel"
"88212115";"Starter";"PowerMax";"4543";"5713852365634";"79,81";"EUR";"181"
"88212119";"Starter";"PowerMax";"4543";"5713852365672";"209,07";"EUR";"1"
"88212120";"Starter";"PowerMax";"4543";"5713852365689";"91,56";"EUR";"30"
"88212121";"Starter";"PowerMax";"4543";"5713852365696";"79,81";"EUR";"-6"
"88212125";"Starter";"PowerMax";"4543";"5713852365733";"84,51";"EUR";"39"
"88212128";"Starter";"PowerMax";"4543";"5713852365764";"108,59";"EUR";"23"
"88212130";"Starter";"PowerMax";"4543";"5713852365788";"133,86";"EUR";"1"
"88212135";"Starter";"PowerMax";"4543";"5713852365832";"58,66";"EUR";"-11"
"88212136";"Starter";"PowerMax";"4543";"5713852365849";"115,95";"EUR";"-23"
"88212138";"Starter";"PowerMax";"4543";"5713852365863";"99,49";"EUR";"8"
"88212140";"Starter";"PowerMax";"4543";"5713852365887";"66,59";"EUR";"6"
What I need is to have all negativ values i the StockLevel column (column 8) replaced with 0
In another question I had The Forth Bird provided me with this code that works fine
Get-Content "C:\Users\SvcBI\Documents\Autodoc\Autodoc_Temp.csv" | ForEach-Object {
if($_.Contains("MAHLE AM GmbH")) {
$_.Replace("4543", "287")
} else { $_ } } | Set-Content C:\Users\SvcBI\Documents\Autodoc\POWERMAX_DK_2.csv
So, I tried to rewrite it to this
Get-Content "O:\Lagertal_til_kunder\Autodoc\myTempFile.csv" | ForEach-Object {
if($_.Contains("-[0-9]*")) {
$_.Replace("-[0-9]*", "0")
}
else { $_ } } | Set-Content O:\Lagertal_til_kunder\Autodoc\POWERMAX_DK_2.csv
But it don't work.
All negativ values is still present in POWERMAX_DK_2.csv
Please help /Kim

Related

How to overwrite multiple line in rust

I'm trying to print status on ongoing process something like this:
|Label-1 |Label-2 |Label-3
|Data-1 |Data-2 |Data-3
|Data-1 |Data-2 |Data-3
|Data-1 |Data-2 |Data-3
With following code:
println!("|{0:<25} | {1:<1} | {2:<10}", "URL Path", "Status Code", "Version");
println!("{0:<25} | {1:<11} | {2:<10?}", resp.request_url, resp.status_code, resp.version);
unsafe {
if (FOUND.len() != 0) {
for elem in FOUND.iter() {
println!("\n\n{0:<25} | {1:<11} | {2:<10?}", elem.request_url, elem.status_code, elem.version);
}
}
if (resp.status_code == 200) {
FOUND.push(resp)
}
}
stdout().execute(cursor::MoveUp(3));
stdout().execute(terminal::Clear(terminal::ClearType::FromCursorDown));
The string of the rows have to be overwritten with new string. If it were one line, I could do print!("\r{} | {} | {}",data1,data2,data3) but since it's multiline the carriage return messes.
PS: Any example would be appreciated
I'm not sure exactly what your problem is, but holding a locked stdout worked for me:
use std::io::{stdout, Write};
use crossterm::{
cursor, terminal, Result, ExecutableCommand
};
fn main() -> Result<()> {
let mut stdout = stdout(); // lock stdout and use the same locked instance throughout
writeln!(stdout, "|{0:<25} | {1:<11} | {2:<10}", "URL Path", "Status Code", "Version")?;
writeln!(stdout, "|{0:<25} | {1:<11} | {2:<10}", "https://google.com", 200, 9)?;
writeln!(stdout, "|{0:<25} | {1:<11} | {2:<10}", "https://yahoo.com", 200, 15)?;
// wait 2 seconds before replacing lines
std::thread::sleep(std::time::Duration::from_secs(2));
stdout.execute(cursor::MoveUp(2))?;
stdout.execute(terminal::Clear(terminal::ClearType::FromCursorDown))?;
writeln!(stdout, "|{0:<25} | {1:<11} | {2:<10}", "https://bing.com", 200, 3)?;
writeln!(stdout, "|{0:<25} | {1:<11} | {2:<10}", "https://duckduckgo.com", 200, 1)?;
Ok(())
}

ARM Template: how to read output result in array format

I posted some question on stackoverflow and would like to thanks those who take time to answer.
Although it exists documentation, i still face an issue related to output feature.
Basically I understand how to retrieve data when format is string.
Unfortunately when data is on array format it looks more difficult for me.
"outputs": {
"keyVaultName": {
"type": "string",
"value": "[variables('keyVaultName')]"
},
"websitesname": {
"type": "array",
"copy": {
"count": "[length(variables('webSitesName'))]",
"input": {
"name": "[variables('webSitesName')[copyIndex()].name]"
}
}
}
}
Then i do this:
$deploymentResult = New-AzResourceGroupDeployment -Name $deploymentName -ResourceGroupName
$ResourceGroupName-TemplateFile $TemplateFile
$vaultName = $deploymentResult.Outputs.keyVaultName.Value
$arrayWebsitesName = $deploymentResult.Outputs.websitesname.Value
I need to extract value from returned array. In powershell i expected to use something like
$arrayWebsitesName[0] to get AppService-Prod-CentralUS
$arrayWebsitesName[\1] to get AppService-Prod-EastUS
I believe there is something related to conversion and I tried convertto-json without success.
Your help is appreciated !
The variable type returned from the deployment for websitesname is a JArray.
PS> $deploymentResult.Outputs.websitesname.Value.GetType()
IsPublic IsSerial Name BaseType
-------- -------- ---- --------
True False JArray Newtonsoft.Json.Linq.JContainer
In order to get at the values, you would make the call like:
$arrayWebsitesName = $deploymentResult.Outputs.websitesname.Value
$ids = $arrayWebsitesName.ToString() | ConvertFrom-Json
$ids[0].name
$ids[1].name
Converting the JArray to a JSON string, and then converting the JSON string to a PowerShell array may not be most efficient but I don't typically deal with large arrays and performance is not a concern (gets the job done).

Passing JSON Parameters into the Azure DevOps Powershell Script

I'm trying to pass my variable into my JSON post parameters, however, the below code only works for hardcoding the values, but I need to pass the $var to the principal parameter:
$var="demo"
Write-Host $var
$postParams = #'
{ "scope": "DemoScope","principal": "$($var)" }
'#
So far I tried like $(var) and $($var) in the above script but nothing worked.
Because you use ' ' the variable can't be used, I like this way to create the json:
$postParams = #{
scope = "DemoScope"
principal = $var
} | ConvertTo-Json
# Result:
{
"principal": "demo",
"scope": "DemoScope"
}
Another way it to use " instaed of ':
$postParams = #"
{ "scope": "DemoScope","principal": "$var" }
"#

Convert name and Value to column and rows during Export to CSV in Powershell

I am trying to convert name and values returned from my API call into column and rows during export but so far I have no luck.
$searchResponse = Invoke-RestMethod -Method POST -Uri $searchUri -ContentType application/json -Header $requestHeader -Body $searchResultsRequest
$lists = $searchResponse.businessO.fields | Select name, value
The $list returns:
name value
---- ----
Name YY
Address ABC street
City Seattle
Zip 01256
Name XYZ
Address XYZ street
City XYZ
Zip 45456
Name Mike
Address 1256 Street
City New York
Zip 78965
I want to output this result as following in CSV:
Name Address City Zip
YY ABC street Seattle 01256
.
.
.
I tried looping through list and applied condition to check name and populate value based on it, but i end up getting either duplicates or all my output data are out of sysnc meaning Mike gets Address of YY and so on....
If($lists.count -ge 0){
ForEach($list in $lists){
if($list.name -eq "Name") {$name= $list.value }
}
I would really appreciate any help on this one. Thank You.
$searchResponse results
$searchResponse |ConvertTo-Json
{
"businessObjects": [
{
"busObId": "xxxxxxxxxxxxxx",
"busObPublicId": "abc345",
"busObRecId": "xxxxxxxxxxxxxxxxxxx",
"fields": " ",
"links": "",
"errorCode": null,
"errorMessage": null,
"hasError": false
},
{
"busObId": "xxxxxxxxxxxxx",
"busObPublicId": "rty567",
"busObRecId": "xxxxxxxxxxxxxxxx",
"fields": " ",
"links": "",
"errorCode": null,
"errorMessage": null,
"hasError": false
}
],
"hasPrompts": false,
"links": [
],
"prompts": [
],
"searchResultsFields": [
],
"totalRows": 2500
}
Fields has the name and value which I want to output.
$searchResponse.businessObjects.fields |ConvertTo-Json
[
{
"dirty": false,
"displayName": "Name",
"fieldId": "xxxxxxxxxxx",
"html": null,
"name": "Name",
"value": "Mike"
},
{
"dirty": false,
"displayName": "Address",
"fieldId": "456451212113132",
"html": null,
"name": "Address",
"value": "Seattle"
},
and so on.
This answer as a teaching exercise with the expectation, one will walk through the code in the VSCode or ISE debugger and learn more about the objects, members, and more.
There are a few ways to solve this. In this answer, I try to break down the steps in a way newer PowerShell user may learn more about the language.
# mock your data
$list1 = #(
[pscustomobject]#{Name='YY'},
[pscustomobject]#{Address='ABC street'},
[pscustomobject]#{City='Seattle'},
[pscustomobject]#{Zip='01256'},
[pscustomobject]#{Name='XYZ'},
[pscustomobject]#{Address='XYZ street'},
[pscustomobject]#{City='XYZ'},
[pscustomobject]#{Zip='45456'},
[pscustomobject]#{Name='Mike'},
[pscustomobject]#{Address='1256 Street'},
[pscustomobject]#{City='New York'},
[pscustomobject]#{Zip='78965'}
)
# mock your data
$list2 = #(
#{Name='YY'},
#{Address='ABC street'},
#{City='Seattle'},
#{Zip='01256'},
#{Name='XYZ'},
#{Address='XYZ street'},
#{City='XYZ'},
#{Zip='45456'},
#{Name='Mike'},
#{Address='1256 Street'},
#{City='New York'},
#{Zip='78965'}
)
# debuggng...
#$list1
#$list1.GetType()
#$list1[0].GetType()
#$list2
#$list2.GetType()
#$list2[0].GetType()
# seems your data looks like list1
$data = #()
$entry = [ordered]#{}
# transform the data into separate objects based on the field you want
foreach ($item in $list)
{
if ($item.Name) {$entry.Name = $item.Name}
elseif ($item.Address) {$entry.Address = $item.Address}
elseif ($item.City) {$entry.City = $item.City}
elseif ($item.Zip) {$entry.Zip = $item.Zip; $data += $entry; $entry = [ordered]#{}}
}
# data transformed now into an array of hashtables
# there are a few says to save as csv, one is to just roll your own rather
# than GetEnumerator(), etc.
$out = #()
$out += $data[0].Keys -join ', '
$out += $data | % {
#$_['Name']+','+$_['Address']+','+$_['City']+','+$_['Zip']
# or
#$_.Name+','+$_.Address+','+$_.City+','+$_.Zip
# or
$_.Name,$_.Address,$_.City,$_.Zip -join ', '
}
$out
# save $out to a file, uncomment to use after editing path
#$out | Out-File -FilePath 'c:\mycsvfile.csv'

PowerShell: Remove Trailing "..."

I'm trying to create a powershell script that will get the list of scheduled tasks. I've got far enough to get a complete list of tasks, however I need to remove the trailing "..."
How do you do that?
$tasks | Select-String -pattern "Disabled" | ft #{Expression
={$_.Line};Label="Line";width=44}
Output:
Line
----
AD RMS Rights Policy Template Management ...
AD RMS Rights Policy Template Management ...
Proxy ...
UserTask ...
UserTask-Roam ...
Consolidator ...
KernelCeipTask ...
UsbCeip ...
ScheduledDefrag ...
Scheduled ...
Microsoft-Windows-DiskDiagnosticDataColl ...
Microsoft-Windows-DiskDiagnosticResolver ...
Notifications ...
WinSAT ...
ActivateWindowsSearch ...
ConfigureInternetTimeService ...
DispatchRecoveryTasks ...
ehDRMInit ...
InstallPlayReady ...
mcupdate ...
MediaCenterRecoveryTask ...
ObjectStoreRecoveryTask ...
OCURActivate ...
OCURDiscovery ...
PBDADiscovery ...
PBDADiscoveryW1 ...
PBDADiscoveryW2 ...
PeriodicScanRetry ...
PvrRecoveryTask ...
PvrScheduleTask ...
RecordingRestart ...
RegisterSearch ...
ReindexSearchRoot ...
SqlLiteRecoveryTask ...
UpdateRecordPath ...
CorruptionDetector ...
DecompressionFailureDetector ...
HotStart ...
LPRemove ...
SystemSoundsService ...
GatherNetworkInfo ...
Background Synchronization ...
Logon Synchronization ...
AnalyzeSystem ...
RacTask ...
RegIdleBackup ...
WindowsParentalControls ...
WindowsParentalControlsMigration ...
AutoWake ...
GadgetManager ...
SessionAgent ...
SystemDataProviders ...
SR ...
Interactive ...
IpAddressConflict1 ...
IpAddressConflict2 ...
MsCtfMonitor ...
SynchronizeTime ...
ResolutionHost ...
QueueReporting ...
BfeOnServiceStartTypeChange ...
UpdateLibrary ...
ConfigNotification ...
Calibration Loader ...
Don't use Format-Table (ft) since it will attempt to fit the data within the number of columns available in the console and you've limited the space for the "line" column to 44 chars. Try this instead:
$tasks | Select-String -pattern "Disabled" | Foreach {$_.Line}
$tasks | Select-String -pattern "Disabled" | ForEach-Object
{ $_ -replace "Disabled", ""} | ForEach-Object { $_ -replace "Could not start",
""} | ForEach-Object { $_.Trim() }
Does exactly as I wanted.
I'm not sure what $tasks has in it so I wrote this based off get-service but it should work in your case:
$tasks | Select-String -pattern "Disabled" | ft #{Expression=
{$intLength = 44; if($_.Line.length -lt $intLength) {$intLength=$_.Line.length} $_.Line.substring(0,$intLength)};Label="Line"}

Resources