Google sheet - Value is not being set correctly - google-apps-script

I have setup a google sheet with a script attached to it that runs a function to pull chromebook device information, works great apart from two fields im interested in, "cpuStatusReports" and "diskVolumeReports" the script logger does show the correct info but my sheet cell values is set to for example
{cpuUtilizationPercentageInfo=[Ljava.lang.Object;#d151552,
cpuTemperatureInfo=[Ljava.lang.Object;#f57094c,
reportTime=2019-03-29T18:15:56.049Z}
my function is :-
function chromebookdetails2() { var domain, chromebooks, page, ss,
sheet, pageToken, i var sheetData4 =
onSheet.getSheetByName("chromebook") //sheetData4.clear(); domain =
"mydomainnamehere" chromebooks= new Array() do{ page =
AdminDirectory.Chromeosdevices.list("my_customer", {domain: domain,
maxResults: 1000, pageToken: pageToken }) for (i in
page.chromeosdevices){ chromebooks.push(page.chromeosdevices[i]) }
pageToken = page.nextPageToken }while(pageToken){ var row = 3
//starting row position for (var i = 0; i < chromebooks.length; i++) {
var sheetData4 = onSheet.getSheetByName("chromebook")
/////////////////////Header////////////////////////////////////////
var date = Utilities.formatDate(new Date(), "GMT+1", "dd/MM/yyyy")
sheetData4.getRange(1,1).setValue("Date Ran - "+date); //(2,1 means
2nd row, 1st column) sheetData4.getRange(2,1).setValue("orgUnitPath");
//(2,1 means 2nd row, 1st column)
sheetData4.getRange(2,2).setValue("annotatedUser");
sheetData4.getRange(2,3).setValue("annotatedLocation");
sheetData4.getRange(2,4).setValue("annotatedAssetId");
sheetData4.getRange(2,5).setValue("serialNumber");
sheetData4.getRange(2,6).setValue("lastEnrollmentTime");
sheetData4.getRange(2,7).setValue("deviceId");
sheetData4.getRange(2,8).setValue("bootMode");
sheetData4.getRange(2,9).setValue("recentUsers");
sheetData4.getRange(2,10).setValue("macAddress");
sheetData4.getRange(2,11).setValue("lastSync");
sheetData4.getRange(2,12).setValue("osVersion");
sheetData4.getRange(2,13).setValue("platformVersion");
sheetData4.getRange(2,14).setValue("activeTimeRanges");
sheetData4.getRange(2,15).setValue("model");
sheetData4.getRange(2,16).setValue("etag");
sheetData4.getRange(2,17).setValue("firmwareVersion");
sheetData4.getRange(2,18).setValue("status");
sheetData4.getRange(2,19).setValue("ethernetMacAddress");
sheetData4.getRange(2,20).setValue("notes");
sheetData4.getRange(2,21).setValue("systemRamTotal");
sheetData4.getRange(2,22).setValue("CPU");
if(chromebooks[i].length == 0){
// array is empty Logger.log('empty'); } else { //array not empty >Logger.log('not empty');
Logger.log(chromebooks[i].cpuStatusReports);
/////////////////////Array Data///////////////////////////////////
sheetData4.getRange(row,1).setValue(chromebooks[i].orgUnitPath);
sheetData4.getRange(row,2).setValue(chromebooks[i].annotatedUser);
sheetData4.getRange(row,3).setValue(chromebooks[i].annotatedLocation);
sheetData4.getRange(row,4).setValue(chromebooks[i].annotatedAssetId);
sheetData4.getRange(row,5).setValue(chromebooks[i].serialNumber);
sheetData4.getRange(row,6).setValue(chromebooks[i].lastEnrollmentTime);
sheetData4.getRange(row,7).setValue(chromebooks[i].deviceId);
sheetData4.getRange(row,8).setValue(chromebooks[i].bootMode);
sheetData4.getRange(row,9).setValue(chromebooks[i].recentUsers);
sheetData4.getRange(row,10).setValue(chromebooks[i].macAddress);
sheetData4.getRange(row,11).setValue(chromebooks[i].lastSync);
sheetData4.getRange(row,12).setValue(chromebooks[i].osVersion);
sheetData4.getRange(row,13).setValue(chromebooks[i].platformVersion);
sheetData4.getRange(row,14).setValue(chromebooks[i].activeTimeRanges);
sheetData4.getRange(row,15).setValue(chromebooks[i].model);
sheetData4.getRange(row,16).setValue(chromebooks[i].etag);
sheetData4.getRange(row,17).setValue(chromebooks[i].firmwareVersion);
sheetData4.getRange(row,18).setValue(chromebooks[i].status);
sheetData4.getRange(row,19).setValue(chromebooks[i].ethernetMacAddress);
sheetData4.getRange(row,20).setValue(chromebooks[i].notes);
sheetData4.getRange(row,21).setValue(chromebooks[i].systemRamTotal /
(1024*1024) /1024); // "/ (1024*1024)" converts bytes to Mb "/1024"
then converts back to Gb
sheetData4.getRange(row,22).setValue(chromebooks[i].cpuStatusReports);
}
row++ Logger.log(row) } } }
The results in the log file....
[{cpuUtilizationPercentageInfo=[63],
cpuTemperatureInfo=[{temperature=24, label=soc_dts0 },
{temperature=24, label=soc_dts1 }],
reportTime=2019-03-10T18:11:49.480Z}]
How do i reference cpuUtilizationPercentageInfo, cpuTemperatureInfo from cpuStatusReports?
Thankyou

In the loop add
var status = chromebooks[i].cpuStatusReports;
var cpuUtilizationPercentageInfo = status[0].cpuUtilizationPercentageInfo[0];
var cpuTemperatureInfo = status[0].cpuTemperatureInfo[0].temperature;
var label = status[0].cpuTemperatureInfo[0].label;
Check logger.log() to see if you get the desired results.

did you tried:
.setValue(chromebooks[i].cpuStatusReports.toString());
just turn every thing into string and you should have no problem on setValue() I guess.

Related

User Drive's usage without shared files

I'd like to create a report of storage usage for all my users. To do so I use AdminReports app, like so (found in google example, somewhere. Just had to adapt the "parameters" and the "row" arrays) :
function generateUserUsageReport() {
var today = new Date();
var oneWeekAgo = new Date(today.getTime() - 7 * 24 * 60 * 60 * 1000);
var timezone = Session.getScriptTimeZone();
var date = Utilities.formatDate(oneWeekAgo, timezone, 'yyyy-MM-dd');
var parameters = [
'accounts:gmail_used_quota_in_mb',
'accounts:drive_used_quota_in_mb',
'accounts:total_quota_in_mb ',
'accounts:used_quota_in_percentage'
];
var rows = [];
var pageToken;
var page;
do {
page = AdminReports.UserUsageReport.get('all', date, {
parameters: parameters.join(','),
maxResults: 500,
pageToken: pageToken
});
if (page.warnings) {
for (var i = 0; i < page.warnings.length; i++) {
var warning = page.warnings[i];
Logger.log(warning.message);
}
}
var reports = page.usageReports;
if (reports) {
for (var i = 0; i < reports.length; i++) {
var report = reports[i];
var parameterValues = getParameterValues(report.parameters);
var row = [
report.date,
report.entity.userEmail,
parseInt(parameterValues['accounts:drive_used_quota_in_mb']),
parseInt(parameterValues['accounts:gmail_used_quota_in_mb']),
parseInt(parameterValues['accounts:total_quota_in_mb']),
((parseInt(parameterValues['accounts:gmail_used_quota_in_mb'])+parseInt(parameterValues['accounts:drive_used_quota_in_mb']))/parseInt(parameterValues['accounts:total_quota_in_mb']))*100
];
rows.push(row);
}
}
pageToken = page.nextPageToken;
} while (pageToken);
if (rows.length > 0) {
var spreadsheet = SpreadsheetApp.getActive();
var sheet = spreadsheet.getActiveSheet();
// Append the headers.
var headers = [['Date', 'User mail', 'Drive use','Gmail use', 'Total available',
'Total(%)']];
sheet.getRange(1, 1, 1, 6).setValues(headers);
// Append the results.
sheet.getRange(2, 1, rows.length, 6).setValues(rows);
Logger.log('Report spreadsheet created: %s', spreadsheet.getUrl());
} else {
Logger.log('No results returned.');
}
}
/**
* Gets a map of parameter names to values from an array of parameter objects.
* #param {Array} parameters An array of parameter objects.
* #return {Object} A map from parameter names to their values.
*/
function getParameterValues(parameters) {
return parameters.reduce(function(result, parameter) {
var name = parameter.name;
var value;
if (parameter.intValue !== undefined) {
value = parameter.intValue;
} else if (parameter.stringValue !== undefined) {
value = parameter.stringValue;
} else if (parameter.datetimeValue !== undefined) {
value = new Date(parameter.datetimeValue);
} else if (parameter.boolValue !== undefined) {
value = parameter.boolValue;
}
result[name] = value;
return result;
}, {});
}
The issue I have is that the parameters "accounts:drive_used_quota_in_mb" gives you the drive usage WITH the shared files (which is irrelevant to calculate the storage used by a user ( to determine whether he needs more space or not)).
I even tried to use 'accounts:used_quota_in_percentage' which seemed to be exactly what I need, but it calculate the percentage the same way i do : ((drive + mail)/total space)*100, and no way to ignore shared files to do so.
I'm working on the possibility to check every files of the drive, but you know the next problem : slowness.. (just for 1User with few docs, it take 1-2minutes)
Is there a way to do so by script, with another class, or something that is done for it in google that I didn't see ?
Thanks for your reading, forgive my english.
Ok, there is no issue, I just freaked out because a user was at 30Go consumption although he has his account for only 2month.
But after discussing with him, he did upload heavy files one week ago, and since, he deleted it.
And executing the script for only 2days ago gives the correct result, since he deleted these files between these two dates.
The reason of my mistake is that my script was providing stats that was 1 Week old (without me being conscious of that), and I was checking the veracity of theses stats on the web interface, that incidates nowadays stats.

Pushing a simple Log string from a Google Ad Script to a Google Sheet

I am trying to set up a script which can push data from an App Script into a Google Sheet.
I have the script successfully logging what I want, which goes in the following format Account budget is 12344, but now I want to push this into a Google Sheet. I have set up a variable containing the URL and another variable containing the sheet name, and also a clear method to delete anything already there.
Find the code I have below:
// - The link to the URL
var SPREADSHEET_URL = 'abcdefghijkl'
// - The name of the sheet to write the data
var SHEET_NAME = 'Google';
// No to be changed
function main() {
var spreadsheet = SpreadsheetApp.openByUrl(SPREADSHEET_URL);
var sheet = spreadsheet.getSheetByName(SHEET_NAME);
sheet.clearContents();
}
function getActiveBudgetOrder() {
// There will only be one active budget order at any given time.
var budgetOrderIterator = AdsApp.budgetOrders()
.withCondition('status="ACTIVE"')
.get();
while (budgetOrderIterator.hasNext()) {
var budgetOrder = budgetOrderIterator.next();
Logger.log("Budget Order Amount " + budgetOrder.getSpendingLimit());
}
}
Assuming you want to clear the entire Sheet every time you extract the data this should work for you. You will need to set the url and shtName variables.
function getActiveBudgetOrder() {
var url = 'https://docs.google.com/spreadsheets/d/xxxxxxxxxxxxxxxxxxxxxxx/';
var shtName = 'Sheet1';
var arr = [];
var sht = SpreadsheetApp.openByUrl(url).getSheetByName(shtName);
// There will only be one active budget order at any given time.
var budgetOrderIterator = AdsApp.budgetOrders()
.withCondition('status="ACTIVE"')
.get();
while (budgetOrderIterator.hasNext()) {
var budgetOrder = budgetOrderIterator.next();
arr.push(["Budget Order Amount " + budgetOrder.getSpendingLimit()]);
}
sht.clearContents();
sht.getRange(1, 1, arr.length, arr[0].length).setValues(arr);
}

Error in Google Sheets Script when parsing XML

I have this function running in a Google Sheets script that pulls HTML from subreddits and returns them to a spreadsheet. It works for me some/most of the time, but other times I get an error "Could not parse text. (line 13)" which is the line with var doc = Xml.parse(page, true);. Any idea why this is happening or is this just a bug with Google Scripts? Here's the code that works...sometimes.
function getRedditHTML() {
var entries_array = [];
var subreddit_array = ['https://www.reddit.com/r/news/','https://www.reddit.com/r/funny/','https://www.reddit.com/r/science/'];
for (var s = 0; s < subreddit_array.length; s++) {
var page = UrlFetchApp.fetch(subreddit_array[s]);
//this is Line 13 that is breaking
var doc = Xml.parse(page, true);
var bodyHtml = doc.html.body.toXmlString();
doc = XmlService.parse(bodyHtml);
var root = doc.getRootElement();
var entries = getElementsByClassName(root,'thing');
for (var i = 0; i < entries.length; i++) {
var title = getElementsByClassName(entries[i],'title');
title = XmlService.getRawFormat().format(title[1]).replace(/<[^>]*>/g, "");
var link = getElementsByClassName(entries[i],'comments');
link = link[0].getAttribute('href').getValue();
var rank = getElementsByClassName(entries[i],'rank');
rank = rank[0].getValue();
var likes = getElementsByClassName(entries[i],'likes');
likes = likes[0].getValue();
entries_array.push([rank, likes, title, link]);
}
}
return entries_array.sort(function (a, b) {
return b[1] - a[1];
});
}
Here is what I found upon playing with importXML (my usual way of doing this) - for some reason I cannot narrow down - it DOES appear to randomly stall out and return null for a few minutes - so I'm guessing the issue with your thing is not the code but that the site or google temporarily blocks/won't return the data -
however I found the JSON endpoint to the piece you want - and I noticed that when XML went down - the JSON didnt.
You can take that and fix it to push your own array of topics/urls - I just left it for one link for now to show you how the URL breaks down and where it should be modified:
The URL is 'https://www.reddit.com/r/news/hot.json?raw_json=1&subredditName=news&sort=top&t=day&feature=link_preview&sr_detail=true&app=mweb-client
News is mentioned in 2 places so just modify all your URLs to follow that method - you can easily load that javascript in a browser to see all the fields available
Also the portion hot.json is where you can change whether you want the ranked list (called hot), or new,top,promoted, etc. you just change that keyword.
Score is the same as the upvotes/likes
function getSubReddit() {
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet = ss.getActiveSheet(); //get Active sheet
var subject = 'news';
var url = 'https://www.reddit.com/r/' + subject + '/hot.json?raw_json=1&subredditName=' + subject + '&sort=top&t=day&feature=link_preview&sr_detail=true&app=mweb-client'; //json endpoint for data
var response = UrlFetchApp.fetch(url); // get api endpoint
var json = response.getContentText(); // get the response content as text
var redditData = JSON.parse(json); //parse text into json
Logger.log(redditData); //log data to logger to check
//create empty array to hold data points
var statsRows = [];
var date = new Date(); //create new date for timestamp
//The following lines push the parsed json into empty stats array
for (var j=0;j<25;j++){
for (var i =0;i<25;i++){
var stats=[];
stats.push(date);//timestamp
stats.push(i+1);
stats.push(redditData.data.children[i].data.score); //score
stats.push(redditData.data.children[i].data.title); //title
stats.push(redditData.data.children[i].data.url); //article url
// stats.push('http://www.reddit.com' + redditData.data.children[i].data.permalink); //reddit permalink
statsRows.push(stats)
}
//append the stats array to the active sheet
sheet.appendRow(statsRows[j])
}
}

How to Iterate to output data to Google Sheets with App-Script

Using Google App Script, when I used Logger.log() the for loop iterates properly and I get results for each value. When I try to output this to a google sheet only the last value for each variable is output over and over again for the number of goals.length.
Any help is very much appreciated!
function listGoals() {
var sheet = SpreadsheetApp.getActiveSheet();
var filterList = Analytics.Management.Goals.list(accountId, webPropertyId, profileId)
var goals = filterList.items;
for (var i = 0, goal; goal = goals[i]; i++) {
var accountId = goal.accountId;
var propertyId = goal.webPropertyId;
var goalNumber = goal.id;
var goalName = goal.name;
Logger.log('accountId: ' + accountId);
Logger.log('profileId: ' + propertyId);
Logger.log('goal number: ' + goalNumber);
Logger.log('goal name: ' + goalName);
//Logger.log prints for each result
sheet.getRange(1,1,goals.length).setValue(goalNumber);
sheet.getRange(1,2,goals.length).setValue(goalName);
//this only prints out the last value of goalNumber and goalName to the sheet
}
}
It doesn't only print the last results, it just keeps overwriting the old result with the new one.
goals.length only helps if you then supply an array of arrays containing the values looking as such:
[[1, "Goal 1"],
[2, "Goal 2"]]
If you want to print out a list of goalNumber and goalName you need to offset the cell to write in every time.
something like
sheet.getRange(1+i,1).setValue(goalNumber);
sheet.getRange(1+i,2).setValue(goalName);
To speed up the process a bit and not do two calls for every goal you can store the id name pairs as arrays within an array and do one final setValues call after the loop finishes executing.
function listGoals() {
var sheet = SpreadsheetApp.getActiveSheet();
var filterList = Analytics.Management.Goals.list(accountId, webPropertyId, profileId)
var goals = filterList.items;
var goalsToWrite = [];
for (var i = 0, goal; goal = goals[i]; i++) {
goalsToWrite.push([goal.id, goal.name]);
}
sheet.getRange(1, 1, goals.length, 2).setValues(goalsToWrite);
}

Google Apps Script: Display single column based on user email

I am trying to develop a gradebook with Google Spreadhseets, but I only want to display individual grades based on user email. Is there a Google Apps Script function that looks at a logged in user's email, searches the spreadhseet for it (it would be at the top of a column) and then displays that column back to the user?
I think the best solution would probably be to create a small webapp Ui that shows only the relevant column in a html table. Depending on your programming skills it can be quite easy to setup. I could have suggested an example but you gave too few information about the type of data that are in the spreadsheet... User's data are in a single column but I suppose there is also some kind of headers or row identifiers that must be shown to understand what is shown ?
Users will have to authorize the webapp in order to let you identify them when they are logged in.
Edit : here is a simple example of a possible solution that you can start from.
I assumed mails are in row 1, descriptions in column A.
var ss = SpreadsheetApp.openByUrl('https://docs.google.com/spreadsheet/ccc?key=0AnqSFd3iikE3dGdQOXZpRmJnT0xjQklkdEZING5YREE#gid=0');
var sh1 = ss.getSheetByName('sheet1');
var logsheet = ss.getSheetByName('logsheet');
var data = sh1.getDataRange().getValues();
var user = Session.getEffectiveUser()
function doGet() {
var app = UiApp.createApplication();
if(!getcol(user)){
var warn = app.createTextBox().setWidth('500').setValue("Your results are not available or you don't have permission to view these data");// if user is not in the list, warning + return
app.add(warn)
return app
}
var grid = app.createGrid(data.length, 2).setBorderWidth(1).setCellPadding(2);
var text = app.createTextBox().setName('text').setId('text').setValue(user+' | idx'+getcol(user) ).setWidth('300px');
var btn = app.createButton('press here to confirm you have view these results');
var handler = app.createServerHandler('log').addCallbackElement(grid);
btn.addClickHandler(handler);
var col = getcol(user)
grid.setWidget(0,1,text).setText(0, 0, 'Results for');
grid.setStyleAttribute('textAlign','center')
for(n=1;n<data.length;++n){
grid.setText(n, 0, data[n][0])
grid.setText(n, 1, data[n][col])
}
app.add(grid).add(btn)
return app
}
function log(e){
var text = e.parameter.text
var app = UiApp.getActiveApplication();
// add user name to the log sheet + timestamp + eventually send a mail etc...
return app
}
function getcol(mail){
if(data[0].toString().indexOf(mail.toString())!=-1){
for(zz=1;zz<data[0].length;++zz){
if(data[0][zz] == mail){var colindex=zz;break}
}
return colindex
}
return false
}
EDIT2 :
To print numbers with the desired number of decimals you can use the recently implemented printf function like this :
grid.setText(n, 1, Utilities.formatString('%.2f',data[n][col]));// 2 decimals, no leading 0
to show dates like you want use formatDate()
Utilities.formatDate(date, Session.getTimeZone(), "MM-dd")
EDIT3 :
here is a version that handles the different types of data :
var ss = SpreadsheetApp.openByUrl('https://docs.google.com/spreadsheet/ccc?key=0AnqSFd3iikE3dGdQOXZpRmJnT0xjQklkdEZING5YREE#gid=0');
var sh1 = ss.getSheetByName('sheet1');
var logsheet = ss.getSheetByName('logsheet');
var data = sh1.getDataRange().getValues();
var user = Session.getEffectiveUser()
Logger.log(user)
function doGet() {
var app = UiApp.createApplication();
if(!getcol(user)){
var warn = app.createTextBox().setWidth('500').setValue("Your results are not available or you don't have permission to view these data");// if user is not in the list, warning + return
app.add(warn)
return app
}
var grid = app.createGrid(data.length, 2).setBorderWidth(1).setCellPadding(2).setStyleAttribute('background','#ffeeaa').setId('grid');
var text = app.createTextBox().setName('text').setId('text').setValue(user+' | idx'+getcol(user) ).setWidth('300px');
var btn = app.createButton('press here to confirm you have view these results');
var handler = app.createServerHandler('log').addCallbackElement(grid);
btn.addClickHandler(handler);
var col = getcol(user)
grid.setWidget(0,1,text).setText(0, 0, 'Results for');
grid.setStyleAttribute('textAlign','center')
for(n=1;n<data.length;++n){
grid.setText(n, 0, string(data[n][0]));
grid.setText(n, 1, string(data[n][col]));
}
grid.setStyleAttributes(n-1, 0, {'fontWeight':'bold','background':'#ffff99'})
grid.setStyleAttributes(n-1, 1, {'fontWeight':'bold','background':'#ffff99'})
app.add(grid).add(btn)
return app
}
function log(e){
var text = e.parameter.text
var app = UiApp.getActiveApplication();
app.getElementById('grid').setStyleAttribute('background','#bbffbb')
// add user name to the log sheet + timestamp + eventually send a mail etc...
return app
}
function string(value){
Logger.log(typeof(value))
if (typeof(value)=='string'){return value};// if string then don't do anything
if (typeof(value)=='number'){return Utilities.formatString('%.1f / 20',value)};// if number ther format with 1 decimal
if (typeof(value)=='object'){return Utilities.formatDate(value, Session.getTimeZone(), "MM-dd")};//object >> date in this case, format month/day
return 'error'
}
function getcol(mail){
if(data[0].toString().indexOf(mail.toString())!=-1){
for(zz=1;zz<data[0].length;++zz){
if(data[0][zz] == mail){var colindex=zz;break}
}
return colindex
}
return false
}