Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
209 views
in Technique[技术] by (71.8m points)

windows - Batch programming a runas utility creater

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

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

1 Reply

0 votes
by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...