Start OneDrive Under Full Admin Rights - excel

Summary
I necessarily run Excel with Admin privileges and I have UAC set to Never Notify. Excel VBA opens Word. Word has a macro button that restarts OneDrive. The error message is that "OneDrive can't be run using full admin rights." How can I restart OneDrive without the error massage?
Note: There is a sister post at How to Restart OneDrive via VBA When Running Excel Elevated, but that post poses an entirely different question.
Workflow
Excel VBA opens Word:
Sub m_Test_Finish_WordDoc()
Const strpath = "C:\Users\ssttr\OneDrive\Documents\Investing\Automation\Static Inputs\Restart_OneDrive.docm"
Dim Wd As Object
Dim InstrDoc As Object
Dim f As Boolean
On Error Resume Next
Set InstrDoc = GetObject(strpath)
With InstrDoc.Parent
.Visible = True
.Activate
End With
End Sub
Word macro restarts OneDrive:
Private Sub CommandButton1_Click()
Application.Run "Restart_OneDrive"
End Sub
Sub Restart_OneDrive()
'Restarts OneDrive
Dim shell
Set shell = CreateObject("wscript.shell")
shell.Run """C:\Users\ssttr\OneDrive\Documents\Investing\Automation\Static Inputs\OneDrive Restart - Copy.bat""" 'bat.zzz
End Sub
Contents of OneDrive Restart - Copy.bat
REM Restarts OneDrive from the command line.
REM From https://stackoverflow.com/questions/29872973/syncing-onedrive-skydrive-with-batch-file-via-cmd.
REM If the /background switch is omitted then Explorer is opened to the OneDrive folder in your user profile but OneDrive does not start.
REM If restarting OneDrive from a batch file then add the START command or the batch file won't end.
REM start %LOCALAPPDATA%\Microsoft\OneDrive\OneDrive.exe /background <-- the original '~error-producing' command
RunWithRestrictedRights %LOCALAPPDATA%\Microsoft\OneDrive\OneDrive.exe -w -v
One Possible Path to a Solution
I downloaded the RunWithRestrictedRights.exe standalone executable from https://www.coretechnologies.com/products/RunWithRestrictedRights/ into the C:\Windows\System32 directory and the implementation (shown above) in VBA was replacing the
start %LOCALAPPDATA%\Microsoft\OneDrive\OneDrive.exe /background
line in my batch file (which BTW is from Syncing OneDrive (SkyDrive) with Batch File (via cmd))
with
RunWithRestrictedRights %LOCALAPPDATA%\Microsoft\OneDrive\OneDrive.exe.
Note that, as required at the very bottom of https://www.coretechnologies.com/products/RunWithRestrictedRights/, I added the Administrator to the security policy settings for "Replace a process level token" and for "Adjust memory quotas." See below Notes > SecPol.msc §.
The hang-up is when that the batch file, when called in the above process (Important: remember Excel is Run As Admin), runs (i.e. cmd window flashes) but it does not open OneDrive.
Is my problem, as I suspect, in my batch file, or somewhere else? If somewhere else, then you may wish to see my sister post (it is the same underlying issue but pursing a very different question) at How to Restart OneDrive via VBA When Running Excel Elevated.
Notes:
Things that didn't work for me:
There was some stuff about UAC being required relative to an elevated launch of OneDrive, but that's a non-starter for me because if a user needs to attend to a UAC prompt, then my code's purpose of full automation is negated. Also, for my purposes, I have UAC set to Never Notify.
From https://superuser.com/questions/171917/force-a-program-to-run-without-administrator-privileges-or-uac/450503#450503 -- The MS RunAsInvoker Application Compatibility Toolkit shim does not apply bc I have UAC turned off by default.
FWIW, I did try setting UAC to Always Notify but it did not remove the error. I also tried RunAs /trustlevel:0x20000 %LOCALAPPDATA%\Microsoft\OneDrive\OneDrive.exe, and it did not seem to work, which is because per https://www.coretechnologies.com/products/RunWithRestrictedRights/ I have UAC disabled.
Origins of the solution I am pursuing:
From https://www.coretechnologies.com/blog/alwaysup/onedrive-hates-admin-rights/ -- "UAC enables an administrator to run OneDrive normally" section -- this is a really informative and provided the final solution
SecPol.msc
From https://learn.microsoft.com/en-us/windows/security/threat-protection/security-policy-settings/replace-a-process-level-token -- "This policy setting determines which parent processes can replace the access token (editor's note - describes the security context of a process or thread) that is associated with a child process." That's the lynch pin setting.
I set that per https://learn.microsoft.com/en-us/windows/security/threat-protection/security-policy-settings/user-rights-assignment and https://learn.microsoft.com/en-us/windows/security/threat-protection/security-policy-settings/how-to-configure-security-policy-settings.
I also had to set Adjust memory quotas for a process per https://learn.microsoft.com/en-us/windows/security/threat-protection/security-policy-settings/adjust-memory-quotas-for-a-process and https://learn.microsoft.com/en-us/windows/security/threat-protection/security-policy-settings/how-to-configure-security-policy-settings.
Per https://learn.microsoft.com/en-us/windows/security/threat-protection/security-policy-settings/how-to-configure-security-policy-settings, "any change to the user rights assignment for an account becomes effective the next time the owner of the account logs on." so I restarted (after I tested and confirmed it did not work without a restart).
Update 2022-01-07-18.7
I've moved from a *.bat because I was passing multiple commands, to attempting to directly implement the command by way of:
Sub Restart_OneDrive()
Dim RWRR As Variant
RWRR = shell("RunWithRestrictedRights.exe ""C:\Users\ssttr\AppData\Local\Microsoft\OneDrive\OneDrive.exe"" -w -p -v", vbNormalFocus)
End Sub
but I get Run-time error '53': File not found.
The error still occurs if I change to
RWRR = shell("C:/Windows/System32/RunWithRestrictedRights.exe ""C:\Users\ssttr\AppData\Local\Microsoft\OneDrive\OneDrive.exe"" -w -p -v", vbNormalFocus)
or to
Call shell("RunWithRestrictedRights ""C:\Users\ssttr\AppData\Local\Microsoft\OneDrive\OneDrive.exe""", vbNormalFocus)
I have the required security policy set per https://www.coretechnologies.com/products/RunWithRestrictedRights/ :
which states:
Does RunWithRestrictedRights.exe work on Windows XP and Windows Server
2003, where there is no UAC?
Yes, it works well on Windows XP and Windows Server 2003. The Windows
Integrity Level can't be set (that feature is only available in
Windows Vista and later) but the application is run without admin
rights as intended.
One note though: If you receive an error stating that "a required
privilege is not held by the client", please ensure that your account
has these two rights: Adjust memory quotas for a process; Replace a
process level token.
If I run directly from a non-elevated command line
RunWithRestrictedRights.exe "C:\Users\ssttr\AppData\Local\Microsoft\OneDrive\OneDrive.exe" -w -p -v
or
C:/Windows/System32/RunWithRestrictedRights.exe "C:\Users\ssttr\AppData\Local\Microsoft\OneDrive\OneDrive.exe"```` or ````RunWithRestrictedRights "C:\Users\ssttr\AppData\Local\Microsoft\OneDrive\OneDrive.exe" -w -p -v
it works, resulting in:
I have tried all these syntax commands inside the shell, with what I think are the appropriate syntax changes, e.g. as shown the above VBA above, but still get the run time error 53.
FWIW here's the help for RunWithRestrictedRights.exe:
which says:
RunWithRestrictedRights
Synopsis: Runs a given application in a "restricted" mode - at Medium
(or Low) Integrity and without rights granted by being a member
of the Administrators group.
Usage: RunWithRestrictedRights.exe [-w] [-l] [-p]
[-v]
[-d ]
Options:
The full path to the application to be started. Please be
sure to enclose the path in quotes if it contains at least
one space.
-w Instead of returning immediately after launching the
application, wait until the application ends. Optional.
-l Instead of running the application with Medium Integrity,
start it with Low Integrity. Optional.
-p Also strip away rights granted from being a member of the
"Power Users" group. Optional.
-d Also deny rights to the given SID.
-v Produce verbose output. Optional.
Exit code: The non-zero process identifier (PID) if the
application
was successfully started.
-1 if there was an error starting the application.
Version: 3.0.1.16 (Feb 18 2020)
Example: > RunWithRestrictedRights.exe "C:\MyApp\MyApp.exe"
- Starts MyApp.exe with retricted rights.
This free utility is Copyright 2020, Core Technologies Consulting,
LLC. Find out about this and our other products at our web site:
https://www.CoreTechnologies.com/

Related

Why isn't my script able to locate my excel file when given correct filepath?

I have a .vbs script that opens two excel files and copies the contents of a sheet from the first file into the second file. It's supposed to run daily via task scheduler.
The script ran normally until the excel files in question were recently modified and slightly renamed - I went through the script and edited the filenames accordingly after the changes were made, triple checking that the names and filepaths matched up.
Everything ran fine for a few weeks after the changes but now the script fails immediately after starting, giving me an error claiming that the file can't be located even though the file is located at the given path. The error code is 800A03EC.
This is the first chunk of code in the script, including line 7 which seems to be throwing the error:
Dim objApp ' as excel object
Dim x, y ' as workbook
Set objApp = CreateObject("Excel.Application")
objApp.DisplayAlerts = False
objApp.Visible = False
Set x = objApp.Workbooks.Open("S:\Work (Public)\PORT MGMT & TRADING\PORT MGMT FORMS\ORION_FPFOCUS.xlsm")
Set y = objApp.Workbooks.Open("S:\Work (Public)\PORT MGMT & TRADING\PORT MGMT FORMS\FPFocusPasteSpecialValues.xlsb")
Dim WSx, WSy ' as excel worksheet
Set WSx = x.Worksheets("FPSUP")
Set WSy = y.Worksheets("FPFOCUS-COPY")
WSy.Range("B1").value = FormatDateTime(Now)
objApp.Application.Run "ORION_FPFOCUS.xlsm!Auto_Open"
The excel files in question are both located in the same directory:
S:\Work (Public)\PORT MGMT & TRADING\PORT MGMT FORMS\ORION_FPFOCUS.xlsm
S:\Work (Public)\PORT MGMT & TRADING\PORT MGMT FORMS\FPFocusPasteSpecialValues.xlsb
And the script is located here:
C:\Users\bserv\Documents\CopyFPFocus.vbs
The S drive isn't a physical drive, it's a virtual drive hosted by a service called Workplace. I can navigate through it and open the excel files manually just fine.
I initially thought it was a user privilege issue with task scheduler, but I've selected the 'run with highest privileges' option and the script is still failing. I also went through the privacy/trust settings in Excel to make sure the script wasn't being denied access, but I don't see any settings that would disable the script from working, and I also know that all these settings haven't changed since the script was working, so I don't see how they could be potential causes.
When I try running the code manually via cscript in the command line, it returns this error:
C:\Users\bserv\Documents\CopyFPFocus.vbs(25, 4) (null): The remote procedure call failed.
This is line 25 of the script for reference:
objApp.Run "RefreshAllStaticData"
When I try again by running command prompt as an admin, I get the same error I got initially. Sorry, is it possible the file was moved renamed or deleted.
The part that really confuses me is that the script ran fine for some time after the changes - so I'm really unsure about what actually changed to cause this issue to randomly pop up.
One other thing I've noticed is that upon opening the excel files I get a popup saying they're in use and locked for editing by me. I can't remember if this popup was showing up before the issue started. The other users on the network have been accessing these files regularly long before the script started failing, so I don't see how that could be the issue. The error code/message also doesn't seem to correspond with this being the problem.
I'd appreciate any help or insight into this issue. Thank you!

VBscript Can't Find Excel File

I am attempting to use VBscript to open an excel file. However, when I run the script, it says the file cannot be located. I am pretty certain I have the file path correct. Is it possible that something else is causing my code to fail?
Set objExcel = CreateObject("Excel.Application")
objExcel.Visible = True
Set objWorkbook =
objExcel.Workbooks.Open("C:\Users\Guest\Documents\Projects\1A.xlsx")
Set objExcel = Nothing
Set objWorkbook = Nothing
As mentioned in the comments
In 9 out of 10 cases, this is permission related
The likeihood is (if you have already confirmed the file path is correct) that the VBScript does not have the permission required to access the file path, but due to the way elevation works along with UAC on most Windows Operating Systems means that VBScript doesn't know about the path, so it isn't reported as a access permission error.
As the path in question refers to a User Profile path the chances of it being permissions related increases.
To fix the problem the host process running the VBScript (wscript.exe or cscript.exe) needs to be run using elevated privileges. You can do this by opening an elevated command prompt (Run as Administrator context menu option) and specifying the host process followed by the script path.
Something like;
cscript.exe "yourscript.vbs"
From a windows command prompt type
c:\ dir C:\Users\Guest\Documents\Projects\1A.xlsx
The file could have been saved with a different file extension, or if explorer is hiding extensions and a user has provided the extension on save it might be called 1A.xlsx.xslx
Windows explorer might be hiding data. If you can see it in explorer, right click the file > properties > details.
The Name attribute should tell you exactly what the file is named on disk and the Folder path should give you the path.
You can combine the two to give the full path to the file on disk

Why can my VB6 app not open the "Open" dialog on some systems

I have a VB6 application that, despite everything manages to work on lots of systems, including the numerous Windows 7 x64 systems.
On most of them, the windows dialogs accessed through COMDLG32.OCX work just fine. However, on one particular system, this doesn't work at all. Some forms, when attempting to show the "Open" (or "Save") dialog causes an exception:
Run-time error '32765'
The common dialog function failed during initalization. This error often occurs when insufficent memory is available
Although some other forms that use it simply never show the dialog box at all. Needless to say, memory is not an issue. Microsoft have a kb article on the error where they say:
You have a Microsoft Visual Basic 6.0 program that runs on a Terminal Server, the program uses the Common Dialog control to open a file, and the following conditions are true:
The user is using a roaming profile.
There is a policy to delete the roaming profile when the user logs off.
When these conditions are true, you may receive [the error quoted above]
The conditions mentioned are not true - this is all through the (only, local) user on the system. The suggested solution involves calling the relevant API calls directly.
Reluctant to implemenet the pile of code suggested in every form relevant, I found a class already built for the purpose - CDlgEx. While this works fine on all the computers where the OCX also works fine, on the system which has problems, whenver this line is reached:
RetValue = GetOpenFileName(OFN)
where
Private Declare Function GetOpenFileName Lib "comdlg32.dll" Alias "GetOpenFileNameA" (pOpenfilename As OPENFILENAME) As Long
and OFN is of the private type expected by the function, nothing happens. No dialog box appears, and the program simply moves on to the next line.
Further testing has shown that this only happens when running from the IDE. Running from a compliled executable, everything is fine.
Had the exact same problem. Grab the cCommonDialog class from the following link and add it to your project.
https://github.com/ziggythehamster/ignitionserver/blob/master/vbtracer/cCommonDialog.cls
You can then do something like this in your code
Private Sub Command1_Click()
Dim commonDialog As New GCommonDialog
Dim fileName As String
commonDialog.VBGetOpenFileName fileName
MsgBox fileName
End Sub

VB Macros for Office 2016 for Mac require Permissions every time they try to access a file! Is there any way to get around this behavior?

Any VB Macro in Office 2016 shows a dialog box to the user asking for permission, every time the Macro tries to access a file! Is there a way to avoid it.
Unlike VB Macros in Office for Mac 2011, VB Macros in Office 2016 for Mac do not have access to external files by default. The Office 2016 for Mac apps are sandboxed and hence they lack the required permissions to access external files. Existing macro file commands are changed to prompt the user for file access if the app doesn’t already have access to it. This means that macros that access external files cannot run unattended; they will require user interaction to approve file access the first time each file is referenced.
Developers should use the GrantAccessToMultipleFiles command (see following section) to avoid this experience. This command lets your app get permission for all the files at one time, thereby avoiding a difficult user experience.
GrantAccessToMultipleFiles
This lets you input an array of file paths and prompt the user for permission to access them.
Boolean GrantAccessToMultipleFiles(fileArray)
Parameters
fileArray -- An array of POSIX file paths.
Return Values
True - The user grants permission to the files.
False - The user denies permission to the files.
Note: Once granted, the permissions are stored with the app and user need not grant permission to the file anymore.
Example: 
 
Sub requestFileAccess() 
 
'Declare Variables 
    Dim fileAccessGranted As Boolean 
    Dim filePermissionCandidates
 
 'Create an array with file paths for which permissions are needed 
    filePermissionCandidates = Array("/Users/<user>/Desktop/test1.txt", "/Users/<user>/Desktop/test2.txt")
 
'Request Access from User 
    fileAccessGranted = GrantAccessToMultipleFiles(filePermissionCandidates) 'returns true if access granted, false otherwise 
     
 
End Sub
I wanted to delete a file in Excel using VBA's Kill syntax and got the permission prompt when the VBA attempted to execute the command. My script is supposed to run once every 3 minutes day and night so responding to separate prompts wouldn't cut it.
To workaround the issue, I created a wrapper for VBA's Kill function called myKill. To implement it I:
Globally replaced all calls to Kill with myKill in my VBA code.
Added a new VBA subroutine called myKill (code below)
Created an AppleScript file to actually remove the file (code below)
Granted Excel Full Disk access in System Preferences/Security & Privacy/Privacy. Not sure this step was necessary but I mention it as it's my current configuration. It's worthless without the first three steps.
Here is the myKill subroutine:
Sub myKill(fname As String)
Dim s As String
If Left(Application.OperatingSystem, 3) = "Mac" Then
s = AppleScriptTask("Kill.applescript", "Kill", fname)
Else
Kill fname
End If
End Sub
Here is the Kill.applescript file contents:
on Kill(fileName)
# implementation of vba kill command on Mac. Mac sandboxes Microsoft's
# kill command
tell application "System Events" to delete alias fileName
end Kill
The Kill.applescript file must be stored in
/Users/your user name/Library/Application Scripts/com.microsoft.excel/Kill.applescript
The first time the Apple Script executes, Mac OS will ask for permission for Excel to manipulate files in the directory where the file to be deleted is located. Once given, future file deletes in the directory won't trigger the permission request. I tested that by exiting Excel, reentering and deleting another file.
RANT
How anyone thought making programmers jump through all these hoops or click "OK" each time a file had to be deleted was an acceptable implementation is beyond me. Because someone in Microsoft dropped the ball on abstracting simple file manipulations like Kill over 10,000 programmers have seen this web page trying to figure out what they have to do to delete a file in Microsoft Excel.
Yo Microsoft VBA Project Manager! I'm talking to you! Your job exists because Joel Spolsky convinced Bill Gates that a macro language for Excel was a good idea despite Gates' doubts. Your job is to ensure that Excel VBA abstracts os weirdness so programmers can get their job done and not have to hack in another language.

Task Breaking: Microsoft Windows 2012R2, Task Scheduler, Excel 2013 VBScript

I am trying to move some Excel automation Tasks (Task Scheduler) from an older (Win2003) server to a new Windows 2012 R2 server.
I can get it to work when I first create the task, but if I change anything it stops working and I can't figure out why, or how to stop it from changing. Any thoughts? (also see my second observation below)
Here's What Happens
I create the initial task as shown below and it works fine, but if I change the user that the script runs as, It fails with the error:
Cannot run the macro 'Build'. The macro may not be available in this workbook or all macros may be disabled.
Changing the task to run as the original (working) user does not fix it. I get the same error when I re-run the task and have to delete/re-create it to get it to run again.
File/Task Details
D:\ApplicationDir\run.wsf (simplified)
<job id="1">
<script language="VBScript">
On Error Resume Next
Dim excel
Dim SourceFile
Set excel = CreateObject("Excel.Application")
SourceFile = "D:\ApplicationDir\File.xlsm"
excel.Workbooks.Open SourceFile
excel.Run "Build"
excel.Workbooks.Close
If Err <> 0 Then
... write Err.Description to file ...
End If
Set excel = Nothing
</script>
</job>
Task (in Task Scheduler)
- Runs as a user Account
- Run whether user is logged on or not
- Run with highest privileges
- Configure For: Windows Server 2003, Windows XP or Windows 2000
Triggers:
- Daily At 6:15 AM every day
Actions:
- Start a Program:
- Program: C:\Windows\System32\cscript.exe
- Arguments: run.wsf
- Start In: D:\Application_Dir\
Another Observation
If I select any other "Configure for:" option, I lose the ability to select "Windows Server 2003, Windows XP or Windows 2000" altogether. The option just isn't there when I go back to edit the task properties. Any ideas why this is happening ?
Thanks in advance.

Resources