Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I'm attempting to write a batch file that makes it easier for me to make runas utility shortcuts on a computers desktop.

I have this mostly done, I have all the variables generated, I'm just having issues with the actual shortcut creation part of the script.

This is the code I am using to create the shortcut. With this code, I am using for variables: %shortcutName% as Internet Explorer, %computername% is my computers name, which doesn't include any special characters or spaces, %user% is a local user account which is an administrator (Again no special characters or spaces), and %UserInputpath% is equal to "C:Program FilesInternet Exploreriexplore.exe" (When you drag and drop a file into the command prompt window it generates this link, and wraps it in quotes if needed)

powershell "$s=(New-Object -COM WScript.Shell).CreateShortcut('%USERPROFILE%Desktop\%shortcutName%.lnk');$s.TargetPath='runas /user:%computername%\%user% /savecred %UserInputPath%';$s.Save()"

I think that my problem stems from the quotes as I said earlier, but I'm not really sure how to handle the issue.

This is the error that I get:

Value does not fall within the expected range.
At line:1 char:98
+ ... lorer.lnk');$s.TargetPath='runas /user:iamgrootadmin /savecred C ...
+                 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : OperationStopped: (:) [], ArgumentException
    + FullyQualifiedErrorId : System.ArgumentException

Unable to save shortcut "C:UsersuserDesktopInternet Explorer.lnk".
At line:1 char:203
+ ...  /savecred C:Program FilesInternet Exploreriexplore.exe';$s.Save()
+                                                                 ~~~~~~~~~
    + CategoryInfo          : OperationStopped: (:) [], DirectoryNotFoundException
    + FullyQualifiedErrorId : System.IO.DirectoryNotFoundException
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
208 views
Welcome To Ask or Share your Answers For Others

1 Answer

My suggestion is you wrap your script with this...

#Run as Adminstrator

If (-NOT ([Security.Principal.WindowsPrincipal][Security.Principal.WindowsIdentity]::GetCurrent()).IsInRole([Security.Principal.WindowsBuiltInRole] "Administrator"))

{   
$arguments = "& '" + $myinvocation.mycommand.definition + "'"
Start-Process powershell -Verb runAs -ArgumentList $arguments

%Your Coder HERE%

}

This little section of code resolved all my not administrator errors.

Let me know how it works out for you,

The UnderDog


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share

548k questions

547k answers

4 comments

86.3k users

...