Finding and changing Google file owners - javascript

I want to be able to check a given folder that I've shared, for files that someone else put into the folder, and then take ownership of those files. I've tried this:
function changeUser() {
var folderID = "<folder ID here>"
var newUser = "<my email address>"
var folder = DriveApp.getFolderById(folderID);
var files = folder.getFiles();
while (files.hasNext()) {
var file = files.next();
if(file.getOwner() <> "DriveUser") {
file.setOwner(newUser);
}
}
}
I'm using "DriveUser" because that's the user it says it is, when I run Logger.log(file.getOwner()); But I'm certainly not sure that's right.
When I try to run this, it tells me that there's an unexpected token '>' in the IF statement line. Hey - I'm new to this. In any case, any suggestions as to how I could make this work?

I believe there are two issues with your code:
Javascript uses != for 'not equals' rather than the <> used in some other languages.
The DriveUser you are seeing logged is not a string value, but rather an instance of the User class, documented here. To get a meaningful identifier of the user, you need to call this class's method .getEmail(). You can then compare that to your own email address.
So the updated code looks like this:
var folderID = "..."
var newUser = "(an email address)"
var folder = DriveApp.getFolderById(folderID);
var files = folder.getFiles();
console.log(folder.getOwner())
while (files.hasNext()) {
var file = files.next();
if(file.getOwner().getEmail() != newUser) {
file.setOwner(newUser);
}
}
But there's a third issue you'll encounter: This will only work if you are transferring ownership from you to another user (i.e. you own the files and newUser is not your email address). Apps Script runs scripts on your behalf, which means it will not execute an action that you wouldn't have permission to do manually--only the owner of a file can transfer that ownership to another user. If you run the script on files you don't own, you'll get a vaguely worded error Action not allowed.

Related

Error of duplication in root drive with google script while copying a file from one folder to another

So, I'm trying to copy a file which is updated automatically in my computer in a folder.
Thing is that every time the script runs, it copies the file in the selected folder but also creates a duplication in the root folder despite root isn't referred in the whole script
function moveFiles() {
var olderfiles = DriveApp.getFolderById("idfromdestinyfolder").getFiles();
while (olderfiles.hasNext()) {
var olderfile = olderfiles.next();
var pull = DriveApp.getFolderById("idfromdestinyfolder");
pull.removeFile(olderfile)
}
var files = DriveApp.getFolderById("idfromstartingfolder").getFiles();
while (files.hasNext()) {
var file = files.next();
var destination = DriveApp.getFolderById("idfromdestinyfolder");
file.makeCopy("nameofthefile",destination);
}
}
The first part olderfiles checks if a file exist in the destiny, and if exists, it removes it.
The second part copies the file from the starting folder to destination.
Thing is, every time it runs, it creates a copy in root which should not happen.
Is the first time I'm using google script
From the question
... it copies the file in the selected folder but also creates a duplication in the root folder despite root isn't referred in the whole script
The problem might be caused by the use of Class Folder.removeFile(child). Pleaser bear in mind that it's a deprecated method, the docs instructs to use Folder.moveTo(destination) instead.
If you are looking to send the file to the trash, then use Class File.setTrashed(true)
Related
Permanently delete file from google drive
Delete or Trash specific file in Drive
Try this makeCopy()
function makeCopy() {
var folderid = "folderid";
var fileid = "fileid";
var folder = Drive.Files.get(folderid, { "supportsAllDrives": true });
var newFile = { "fileId": fileid, "parents": [folder] };
var args = { "resource": { "parents": [folder], "title": "new Title" }, "supportsAllDrives": true };
Drive.Files.copy(newFile, fileid, args);
}

How can I get an input folder and its files using Javacript for Automator?

I am writing an automator workflow to work with files and folders. I’m writing it in JavaScript as I’m more familiar with it.
I would like to receive a folder, and get the folder’s name as well as the files inside.
Here is roughly what I have tried:
Window receives current folders in Finder (I’m only interested in the first and only folder)
Get Folder Contents
JavaScript:
function run(input,parameters) {
var files = [];
for(let file of input) files.push(file.toString().replace(/.*\//,''));
// etc
}
This works, but I don’t have the folder name. Using this, I get the full path name of each file, which is why I run it through the replace() method.
If I omit step 2 above, I get the folder, but I don’t know how to access the contents of the folder.
I can fake the folder by getting the first file and stripping off the file name, but I wonder whether there is a more direct approach to getting both the folder and its contents.
I’ve got it working. In case anybody has a similar question:
// Window receives current folders in Finder
var app = Application.currentApplication()
app.includeStandardAdditions = true
function run(input, parameters) {
let directory = input.toString();
var directoryItems = app.listFolder(directory, { invisibles: false })
var files = [];
for(let file of directoryItems) files.push(file.toString().replace(/.*\//,'')) ;
// etc
}
I don’t include the Get Folder Contents step, but iterate through the folder using app.listFolder() instead. The replace() method is to trim off everything up to the last slash, giving the file’s base name.

Get spreadsheet id or url from the spreadsheets name

I have multiple named spreadsheets in a folder on google drive. How would I get their id or url by passing one of the names to a function?
I can get the file using DriveApp, but I dont know how to get the id from that.
function getFile(name)
{
var folder = DriveApp.getFolderById('id');
var file = folder.getFilesByName(name);
//get file id
}
Is there a way to get the id or url using DriveApp or SpreadsheetApp?
The command folder.getFilesByName(name);potentially retrieve more than one file (has it's name say it- getFiles) so it give you a file iterator that you need to parse with a while loop.
If you are absolutely sure that there is at least one file with that has the name, you can avoid the loop with a little dirty code like this:
var file = folder.getFilesByName(name).next();
and then retrieve the id with:
var id = file.getId()
-- EDIT:
If you are not sure to retrieve a file (You don't know if it exist or has the right name....) you'll need to check the result of the file iterator.
Instead of writing :
var file = folder.getFilesByName(name);
prefer to write:
var files = folder.getFilesByName(name); // you could have zero or more than one file
And then you can do a while loop if you believe there is more than one file with that name:
var out = [];
while(files.hasNext()) {
var file = files.next();
out.push(file.getId());
Logger.log(file.getId());
}
return out;
or if there is only one or zero file a simple if will do the job:
if (files.hasNext()) {
var file = files.next();
Logger.log(file.getId());
return file.getIt(); // eventually
}
else {
Logger.log("there is no file with that name");
return "no id"; // eventually
}

Google Spreadsheet script, file access in Drive, "You do not have permission to call ..."

I have a Sheet where I need to get the id of a file located in my Google-drive.
I have written the folowing script:
function get_id_pdf() {
var nom='INV432-altaïr-Famille XXX-XXX Marie-03-2016.pdf';
var files = DriveApp.getFilesByName("'"+nom+"'");
while (files.hasNext()) {
var file = files.next();
var name = file.getName();
var type = file.getMimeType();
var url = file.getUrl();
var id = file.getId();
// Logger.log(file.getId());
return file.getId();
}
}
If I execute it in the Script editor (with the run button), it is working well (I get the id the the Log).
But If I call the script from a cell (in the cell: =get_id_pdf()) of my Google-Sheet, I get the error:
"You do not have permission to call getFilesByName" (see image)
I have of course all the authorization to access to this file (it is in my own drive, and the file havs been created by me).
Does somebody have an idea ?
Regards.
You cannot make calls to services that require user authorization as an anonymous user, which is what custom functions execute as. You will need to put the behavior into a custom menu, or a sidebar so that it can be authorized by the user.
Authorization Documentation
Custom Function Documentation
If your custom function throws the error message "You do not have
permission to call X service.", the service requires user authorization
and thus cannot be used in a custom function.

Add Spreadsheet file in a folder

Anyone know how create a Spreadsheet file in a specific folder on Google Drive?
I have already tried the answer from this link.
EDIT - Tried this answer :-D :
//"Move" file to folder-------------------------------//
var fileID = '12123123213321'
var folderID = '21321312312'
var file = DriveApp.getFileById(fileID).getName()
var folder = DriveApp.getFolderById(folderID)
var newFile = file.makeCopy(file, folder)
//Remove file from root folder--------------------------------//
DriveApp.getFileById(fileID).setTrashed(true)
But the "correct answer" gives me the follow error "Uncaught TypeError: Cannot find function makeCopy in object Spreadsheet."
I saw other answers but none of them work. I have already tried enable "Drive API" from "Advanced Google Services", but it's kind of complicate to work with.
UPDATE!
Just to explain, my problem is that I was creating the Spreadsheet
var sheetId = SpreadsheetApp.create("filename").getId();
And then trying to makeCopy, or addFile in a folder. Something like that:
<someFolder>.addFile(sheet);
What I detect is that to work I have to get a File type, not a string like after. So I change to the code;
var sheetId = SpreadsheetApp.create("filename").getId();
var file = DriveApp.getFileById(sheet);
<someFolder>.addFile(file);
Instead of making a copy, why don't you just move it?
var file = DriveApp.getFileById(fileID),
folder = DriveApp.getFolderById(folderID),
parents = file.getParents();
folder.addFile(file);
while( parents.hasNext() )
parents.next().removeFile(file);

Categories

Resources