Permission denied when trying to delete file via vbscript - vbscript

We have a logon script that sets up default shortcuts on users desktop deployed via Group Policy. This script was used in our previous Windows XP environment. The problem is, the person who set this up copied the shortcuts to %ALLUSERSPROFILE$\Desktop. Now that we're in Windows 7, I'm trying to move the shortcuts to %USERPROFILE%\Desktop and I'm getting permission denied when I try to delete the shortcuts via vbscript. I can delete the shortcuts manually, the UAC prompt comes up, but it works.
Three questions come out of this:
1) In what user context does the script run when run from GPO?
2) In what user context does the script run when run when I run it from the command line and have run the command prompt as administrator?
3) Is there a way to delete these via vbscript in my situation?
Thanks in advance for any help.
I tried using the following script deployed through GP as a startup script to no avail.
'Startup Script
' Force explicit variable declaration.
Option Explicit
On Error Resume Next
Const sPhoneLnk = "Phone_List.lnk"
Const sDesktop = "\Desktop\"
Dim g_oShell, g_oFSO, sAllUsrPrf, sPhoneLink
Set g_oShell = CreateObject("Wscript.Shell")
Set g_oFSO = CreateObject("Scripting.FileSystemObject")
sAllUsrPrf = g_oShell.ExpandEnvironmentStrings("%ALLUSERSPROFILE%")
sPhoneLink = sAllUsrPrf & sDesktop & sPhoneLnk
If g_oFSO.FileExists (sPhoneLink) Then
' wscript.echo sPhoneLnk & " Found."
g_oFSO.DeleteFile (sPhoneLink)
' wscript.echo sPhoneLnk & " Deleted."
Else
' wscript.echo sPhoneLnk & " Not found."
End if
I also tried running the above script from a command prompt as Administrator with UAC turned off and received Access denied.

1) In what user context does the script run when run from GPO?
The logon script activates with the security of the user logging on.
2) In what user context does the script run when run when I run it from the command line and have run the command prompt as administrator?
The script runs as administrator on the local machine.
3) Is there a way to delete these via vbscript in my situation?
Yes. But you should consider, how long do you need this script to be installed? Is it temporary or permanent. If it's temporary, you should write a simple computer startup script which remotes the shortcut links under the all users directory on boot. That way it is not tied to the User Accounts.
If you absolutely want to bypass security for all user accounts and perform actions on user logon no matter what. You can use a domain logon based vbscript:
' ======================================================================
'| name : DSMoveAs.vbs
'| author: Remco Simons [nl] 2007
'|
'| ( http://www.petri.co.il/forums/showthread.php?t=18003 )
' ======================================================================
'
' this script accepts Credentials from command-line
' Usage with GPO:
' Scripts / LogonScript / scriptName -> scriptname.vbs
' Scripts / LogonScript / ScriptParameters -> /u:"domain\user" /p:"password"
'(this user does not nessecarily have to be a member of the Domain Admins group, you can just delegate control over the OU's to it.
'
' this script can move computer objects in active directory
' you have to copy 'dsmove.exe' to a central share
Set objSysInfo = CreateObject("ADSystemInfo")
strComputerDN = objSysInfo.ComputerName
strComputerRDN = split(strComputerDN,",")(0)
strCurrentOU = Replace(strComputerDN, strComputerRDN & ",","")
strCurrentSite = UCase(objSysInfo.SiteName)
'tool
pathDSMOVE = "\\domain.local\sysvol\domain.local\scripts\Dsmove.exe"
'Alternate Credentials
Set Named = WScript.Arguments.Named 'Read script parameters
strUser = Empty
strSecret = Empty
If Named.Exists("u") Then
strUser = Named.Item("u")
If Named.Exists("p") Then _
strSecret = Named.Item("p")
End If
altCredentials = " -u """ & strUser & """ -p """ & strSecret & """"
'variables
strSiteName1 = UCase("New-York")
strSiteName2 = UCase("washington")
'conditional run
If (strCurrentSite = strSiteName1) Then
strNewOU = "CN=computers,DC=domain,dc=Local"
If Not UCase(strCurrentOU) = Ucase(strNewOU) Then
call MoveObject(pathDSMOVE, strComputerDN, strNewOU, altCredentials)
End If
ElseIf (strCurrentSite = strSiteName2) Then
strNewOU = "ou=workstations,DC=domain,dc=Local"
If Not UCase(strCurrentOU) = Ucase(strNewOU) Then
call MoveObject(pathDSMOVE, strComputerDN, strNewOU, altCredentials)
End If
End If
Sub MoveObject(pathDsmove, strComputerDN, targetOU, credentials)
With Wscript.CreateObject("WScript.Shell")
strCommand = pathDsmove & " """ & strComputerDN & """ " _
& "-newparent """ & targetOU & """ " _
& credentials
.Run "%comspec% /c #call " & strCommand,0,True
End With
End Sub

I'd recommend using Group Policy Preferences for modifying desktop shortcuts. Logon scripts are always running in the context of the user logging in. That user may or may not have sufficient privileges for deleting shortcuts from the All Users desktop.

Related

VBScript Error "Permission Denied" But Works Anyway

I have a VBScript setup as a logon script in my GPO. I'm having an issue where every time it runs at logon, I get Permission Denied on the line:
set lf = fso.opentextfile(lfp, 2, true)
Points of interest:
Despite the error, the script completes successfully.
The script executes without error if I run it manually.
The lfp variable points to c:\folder\folder\file.log. The file is created (when necessary) and populated appropriately (overwritten, as expected when it does exist).
If the file is created, the fso is closed before trying to opentextfile.
The user logging in does have modify permission to the path and to the file being replaced when it exists via inherited Authenticated Users permission (from c:\folder1 - see below).
If I throw in a wscript.sleep 30000 just before that line, it just waits 30 seconds to throw permissions denied.
If user is a member of local administrators group on PC, I get no errors. Again, when user is not local admin, it errors, but completes successfully.
I see the same behavior under both Windows 7 and 10.
I'm at a loss here. Here's the pertinent section of code (please excuse any poor coding practice):
'notify robocopy log file location
function seelog(log)
lf.writeline "[" & now & "] " & "See log file for details: " & log
end function
'process robocopy exit codes and write log
function writeerrors(items)
docs = items(0)
retcode = items(1)
logfile = items(2)
if docs = "c" then
name = "some stuff"
else
name = "some other stuff"
end if
If retcode = 0 Then
lf.writeline "[" & now & "] " & name & " folder was already up to date."
elseif retcode = 1 then
lf.writeline "[" & now & "] " & name & " folder was updated."
seelog(logfile)
else
lf.writeline "[" & now & "] " & name & " folder update exited with robocopy error code: " & retcode
seelog(logfile)
End If
end function
'get logged in user
un = CreateObject("WScript.Network").UserName
'check for logfile, and if not exist, create
'folder1 always exists, no need to check or create
lfp = "c:\folder1\folder2\folder3\logfile1.log"
ld1 = "c:\folder1\folder2"
ld2 = "c:\folder1\folder2\folder3"
set fso = createobject("scripting.filesystemobject")
if not fso.fileexists(lfp) then
if not fso.folderexists(ld1) then
fso.createfolder(ld1)
end if
if not fso.folderexists(ld2) then
fso.createfolder(ld2)
end if
set cf = fso.createtextfile(lfp)
cf.close
end if
'open logfile (lfp variable)
'for writing (2)
'overwrite if already exists (true)
wscript.sleep 30000
'************permission denied happens on next line on lfp var*************
Set lf = fso.OpenTextFile(lfp, 2, True)
lf.writeline "[" & now & "] " & "Script started."
lf.writeline "[" & now & "] " & "Logged in user: " & un
lf.writeline "[" & now & "] " & "========================================================="
more code writing to log file and executing robocopy....
I suppose suppressing all errors is an option, but 1) I'd rather not, and 2) I'm not clear on how to accomplish that in VBScript.
ETA:
On Error Resume Next
Set lf = fso.OpenTextFile(lfp, 2, True)
On Error Goto 0
I tested this and it does break the script. lf is not set due to the error so the following lines error out with 'object required "lf"' code 800a01a8 as expected.
I don't like doing this, but my work around was to launch the .vbs from a .bat (personal preference - I like to keep everything from one job in one script so in the future I don't have to go chasing files around).
I placed a logon.bat file in my GPO as the logon script.
#echo off
echo Launching update script...
cscript c:\folder1\script.vbs
This seems to work around the (apparently false) permissions issue I was having. I'm still curious if anyone can tell me exactly why I was seeing the behavior I saw. Does the script engine write to a temp location maybe, when calling OpenTextFile (when launching directly from the GPO) that only admin users would have access to?
On Error Resume Next will ignore the error then On Error Goto 0 will turn normal error handling back on

Creating a script that creates a shortcut and then restarts the computer

I need help with my code. I am trying to make a script that does 2 things: First, it creates shortcut icon on the users desktop. Second, when the user double clicks the icon a box appears asking if they want to restart their computer giving them the option to click OK to restart to CANCEL to cancel the command. When entering the script into the command prompt it just executes the restart computer option. Any help would be greatly appreciated. Here is my script:
Dim answer
' ********* Main processing section **********
' Verify that the user wants to open the Turn Off Computer dialog
Set wshObject = WScript.CreateObject("WScript.Shell")
desktopFolder = wshObject.SpecialFolders("Desktop")
Set myShortcut = wshObject.CreateShortcut(desktopFolder & "\\Shortcut.lnk")
myShortcut.TargetPath = "%windir%\Shortcut.exe"
myShortcut.Save()
answer = MsgBox("The Turn Off Computer dialog will be opened.", 1, "Turn off Computer Script!")
If answer = 1 then ' User clicked on OK
Initiate_Logoff()
End if
' *********** Procedures go here *************
' Open the Windows Turn Off Computer dialog
Function Initiate_Logoff()
shellApp.ShutdownWindows
End Function
How about this:
Option Explicit
'create a desktop shortcut
Dim shl : Set shl = CreateObject("WScript.Shell")
Dim scut : Set scut = shl.CreateShortcut(shl.ExpandEnvironmentStrings("%USERPROFILE%") & "\Desktop\Shortcut.lnk")
scut.TargetPath = "%windir%\shortcut.exe"
scut.Save
Dim cmd : cmd = "shutdown.exe /r /t 1" 'this command restarts the machine
'if the script is being run by cscript (command line)
If InStr(WScript.FullName, "cscript") > 0 Then
shl.Exec cmd
Else
'else ask the user
If MsgBox("Restart Now?", vbQuestion + vbOKCancel, "Title") = vbOK Then
shl.Exec cmd
End If
End If
WScript.Quit

Run script in background

I want to run following script as scheduled task on Windows 7 in background. Now, script displays cmd window and, can I run script without visible cmd window?
Option Explicit
Dim WshShell, oExec
Dim RegexParse
Dim hasError : hasError = 0
Set WshShell = WScript.CreateObject("WScript.Shell")
Set RegexParse = New RegExp
Set oExec = WshShell.Exec("%comspec% /c echo list volume | diskpart.exe")
RegexParse.Pattern = "\s\s(Volume\s\d)\s+([A-Z])\s+(.*)\s\s(NTFS|FAT)\s+(Mirror|RAID-5)\s+(\d+)\s+(..)\s\s([A-Za-z]*\s?[A-Za-z]*)(\s\s)*.*"
While Not oExec.StdOut.AtEndOfStream
Dim regexMatches
Dim Volume, Drive, Description, Redundancy, RaidStatus
Dim CurrentLine : CurrentLine = oExec.StdOut.ReadLine
Set regexMatches = RegexParse.Execute(CurrentLine)
If (regexMatches.Count > 0) Then
Dim match
Set match = regexMatches(0)
If match.SubMatches.Count >= 8 Then
Volume = match.SubMatches(0)
Drive = match.SubMatches(1)
Description = Trim(match.SubMatches(2))
Redundancy = match.SubMatches(4)
RaidStatus = Trim(match.SubMatches(7))
End If
If RaidStatus <> "Healthy" Then
hasError = 1
'WScript.StdOut.Write "WARNING "
MsgBox "Status of " & Redundancy & " " & Drive & ": (" & Description & ") is """ & RaidStatus & """", 16, "RAID error"
End If
End If
Wend
WScript.Quit(hasError)
Thanks a lot
Option 1 - If the task is running under your user credentials (if not, msgbox will not be visible)
There are two possible sources for the cmd window.
a) The script itself. If the task is executing cscript, the console window will be visible, avoid it calling wscript instead
b) The Shell.exec call. The only way to hide this window is to start the calling script hidden. On start of your script test for the presence of certain argument. If not present, make the script call itself with the argument, using Run method of the WshShell object, and indicating to run the script with hidden window. Second instance of the script will start with the special parameter, so it will run, but this time windows will be hidden.
Option 2 - Running the task under system credentials.
In this case, no window will be visible. All will be running in a separate session. BUT msgbox will not be seen. Change MsgBox call with a call to msg.exe and send a message to current console user.

Locking computer remotely

Is there any way that one can lock a desktop computer remotely? For example, if one accidently leaves a computer logged on, would there be a way to lock that computer using Remote Connection (VPN)?
Use PsExec to invoke:
rundll32.exe user32.dll, LockWorkStation
on your remote PC.
If you are currently on PC_A and want to lock PC_B, type this on your command line (on PC_A):
psexec \\\PC_B -u user -p pass "rundll32.exe user32.dll, LockWorkStation"
This way rundll32.exe user32.dll, LockWorkStation will be invoked on PC_B.
You can create a file with an arbitrary name and the suffix bat use this code in bat file
rundll32.exe user32.dll, LockWorkStation
save and run
You can use SysInternal tools, mainly the PsShutdown tool. You would get an instance of cmd on the PC and execute the lock command.
Example:
psshutdown \\computername -l
Option Explicit
Dim objWMIService, objProcess
Dim strShell, objProgram, strComputer, strExe, strInput
strExe = "rundll32.exe user32.dll,LockWorkStation"
' Input Box to get name of machine to run the process
Do
strComputer = (InputBox(" ComputerName to Run Script",_
"Computer Name"))
If strComputer <> "" Then
strInput = True
End if
Loop until strInput = True
' Connect to WMI
set objWMIService = getobject("winmgmts://"_
& strComputer & "/root/cimv2")
' Obtain the Win32_Process class of object.
Set objProcess = objWMIService.Get("Win32_Process")
Set objProgram = objProcess.Methods_( _
"Create").InParameters.SpawnInstance_
objProgram.CommandLine = strExe
'Execute the program now at the command line.
Set strShell = objWMIService.ExecMethod( _
"Win32_Process", "Create", objProgram)
'WScript.echo "Created: " & strExe & " on " & strComputer
WSCript.Quit
' End of Example of a Process VBScript

How to run an exe by client remotely on server using vb6

I'm using code below to execute my commands in cmd. Which is actually made for running an exe on my server.
Private Sub Command1_Click()
Dim FN As Integer
FN = FreeFile
'DOS COMMANDS
ServerName = "\\mydbserv"
ExePath = """d:\myfolder\my.exe"""
UserName = "myserver\myuser"
Password = "mypass"
MyCommand = "psexec " & ServerName & " -u " & UserName & " -p " & Password & " -i " & ExePath
'Open Bat file
Open "C:\Mybatc.bat" For Output As #FN
Print #FN, "cd c:\Users\myuser"
Print #FN, MyCommand
Print #FN, "Exit"
Close #FN
'Activate
result = Shell("C:\Mybatc.bat", vbHide)
End
End Sub
everything was fine until i seen that cmd is not getting closed when process is done.
and the worse is the exe i was trying to run remotely also not stops. When i check the cpu usage it always shows "00" doesnt even starts.. It shows like working for ever but never works actually.
So my question is :
Why i cant run this exe file remotely? (or why it just shows like running)
How can i remotely run and close when finished this exe file on server?
How can i close the window and process when finished on my pc as well?
How about this?
install Windbg on the server.
config the windbg auto attach to your exe, when your exe is ready to running.
http://ask.brothersoft.com/image-file-execution-options-debugger-83827.html
running your script
after your exe is started, the windbg will attach to it.
input 'g' in the windbg command, let your exe to running.
wait until you think it should finished
ctrl-break to let the process hang on
input '~*kb' to windbg command, to see what's going on in every thread,
to find out why they are waiting, and what they are waiting for?
PSExec will only initiate the start of the process in a computer (most of the time remote), after that it has no control on the exe that is being executed. Kindly try to run it as a process (within a ProcessInfo as in C#)(with shell execute false). Also something like the following can be used to confirm the state of the process in remote PC:
Option Explicit
Private Sub Form_Load()
Dim strComputer As String
Dim sReturn As String
Dim strNameOfUser As Variant
Dim colProcesses As Object
Dim objProcess As Object
strComputer = "." '"." local or "\\ComputerName"
Set colProcesses = GetObject("winmgmts:{impersonationLevel=impersonate}!\\" & strComputer & "\root\cimv2").ExecQuery("Select * from Win32_Process")
For Each objProcess In colProcesses
sReturn = objProcess.GetOwner(strNameOfUser)
If sReturn <> 0 Then
MsgBox "Could not get owner info for process " & objProcess.Name & vbNewLine & "Error = " & sReturn
Else
MsgBox "Process " & objProcess.Name & " is owned by " & "\" & strNameOfUser & "."
End If
Next
End Sub
link : http://www.vbforums.com/showthread.php?355203-RESOLVED-How-to-get-process-information
hope it helps

Resources