Batch programming a runas utility creater - windows

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 Files\Internet Explorer\iexplore.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:iamgroot\admin /savecred C ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : OperationStopped: (:) [], ArgumentException
+ FullyQualifiedErrorId : System.ArgumentException
Unable to save shortcut "C:\Users\user\Desktop\Internet Explorer.lnk".
At line:1 char:203
+ ... /savecred C:\Program Files\Internet Explorer\iexplore.exe';$s.Save()
+ ~~~~~~~~~
+ CategoryInfo : OperationStopped: (:) [], DirectoryNotFoundException
+ FullyQualifiedErrorId : System.IO.DirectoryNotFoundException

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

Related

Setting Affinity of an Application on cmd

I have this problem when I'm using Voicemeeter and Discord together, my voice is just crackling and cutting out. I found out the solution to this problem. It's by going to the task manager, heading to details, right clicking audiodg.exe, and then setting it's affinity to only one processer. The problem is I don't want to do this all by hand everytime I start my computer. Is there any way I can write a line of code into the cmd that changes this? This way I can save this lane as a bat file and then put it into the shell:startup and everytime I turn my computer on it will do it automatically for me.
Thank you so much in advance.
Edit:
I'm sorry I wasn't aware of that. This is the error I get:
C:\Users\borah>C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe
"$Process = Get-Process audiodg.exe; $Process.ProcessorAffinity=1"
Get-Process : Cannot find a process with the name "audiodg.exe".
Verify the process name and call the cmdlet again. At line:1 char:12
$Process = Get-Process audiodg.exe; $Process.ProcessorAffinity=1
~~~~~~~~~~~~~~~~~~~~~~~
CategoryInfo : ObjectNotFound: (audiodg.exe:String) [Get-Process], ProcessCommandException
FullyQualifiedErrorId : NoProcessFoundForGivenName,Microsoft.PowerShell.Commands.GetProcessCommand
The property 'ProcessorAffinity' cannot be found on this object.
Verify that the property exists and can be set. At line:1 char:37
$Process = Get-Process audiodg.exe; $Process.ProcessorAffinity=1
~~~~~~~~~~~~~~~~~~~~~~~~~~~~
CategoryInfo : InvalidOperation: (:) [], RuntimeException
FullyQualifiedErrorId : PropertyNotFound
You can set affinity by typing a command, like following,
Start /affinity 2 notepad
This will start notepad while setting an affinity to second core of CPU.
You can save the command above in a file ending with .cmd and run it by double clicking like any other application. Or you can use task scheduler to launch it with windows startup every time, or you can run it as a startup application.
Edit
If you meant changing affinity of an already running process. Check Mofi's comment as solution.
C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe "$Process = Get-Process audiodg; $Process.ProcessorAffinity=1"

Launching multiple RDP sessions via powershell script

Here is the script:
$compnames = import-csv "$env:userprofile\Documents\list.csv"
$User = "username"
$Password = "password"
foreach ($computer in $compnames) {
cmdkey /generic:TERMSRV/$($computer.compname) /user:$User /pass:$Password
mstsc /v:$($computer.compname)
}
When I run the script, I get the following error:
cmdkey : The term 'cmdkey' is not recognized as the name of a cmdlet, function, script file, or operable program. Check the spelling of the name, or if a path was included, verify that the path is correct and try again. At C:\Program Files\WindowsPowerShell\Modules\rdpsession\1.0.2\RdpSession.psm1:92 char:1
+ cmdkey /generic:Termsrv/$computer /user:$Username /pass:$rdp > $null
+ ~~~~~~
+ CategoryInfo : ObjectNotFound: (cmdkey:String) [], CommandNotFoundException
+ FullyQualifiedErrorId : CommandNotFoundException
mstsc : The term 'mstsc' is not recognized as the name of a cmdlet, function, script file, or operable program. Check the spelling of the name, or if a path was included, verify that the path is correct and try again. At C:\Program Files\WindowsPowerShell\Modules\rdpsession\1.0.2\RdpSession.psm1:94 char:1
+ mstsc /v:$computer
+ ~~~~~
+ CategoryInfo : ObjectNotFound: (mstsc:String) [], CommandNotFoundException
+ FullyQualifiedErrorId : CommandNotFoundException
It seems like powershell doesn't recognize cmdkey and mstsc. I've tried googling for hours with no solution. Hoping some one knows what the issue is here preventing the script from running.
Thanks!
Make sure that the actual executables are in your path.
e.g.
dir "$($env:systemroot)\system32\cmdkey.exe"
dir "$($env:systemroot)\system32\mstsc.exe"
The errors are specif.
cmdkey : The term 'cmdkey' is not recognized as the name of a cmdlet
mstsc : The term 'mstsc' is not recognized as the name of a cmdlet
Those two items are external executables of the Windows and ran via cmd.exe, not PowerShell. Running executables/external commands in PowerShell is a well-documented thing, directly from Microsoft.
PowerShell only runs, '.ps' files. Executables are executed via cmd.exe, even from a PowerShell script, which will call cmd.exe under the covers to run them.
If you want to see your call stack of your command, that is why the Trace-Command cmdlet exists.
# Get specifics for a module, cmdlet, or function
(Get-Command -Name Trace-Command).Parameters
(Get-Command -Name Trace-Command).Parameters.Keys
Get-help -Name Trace-Command -Examples
Get-help -Name Trace-Command -Full
Get-help -Name Trace-Command -Online
PowerShell: Running Executables
https://social.technet.microsoft.com/wiki/contents/articles/7703.powershell-running-executables.aspx
As is PowerShell command precedence.
about_Command_Precedence
https://learn.microsoft.com/en-us/powershell/module/microsoft.powershell.core/about/about_command_precedence?view=powershell-7
1 - Alias
2 - Function
3 - Cmdlet
4 - External executable files (programs and non-PowerShell scripts)
With your use case, the call operator is most prudent.
The Call Operator &
Why: Used to treat a string as a SINGLE command. Useful for dealing with spaces.
In PowerShell V2.0, if you are running 7z.exe (7-Zip.exe) or another command that starts with a number, you have to use the command invocation operator &.
The PowerShell V3.0 parser does it now smarter, in this case, you don’t need the & anymore. >
Details: Runs a command, script, or script block. The call operator, also known as the "invocation operator," lets you run commands that are stored in variables and represented by strings. Because the call operator does not parse the command, it cannot interpret command parameters
Example:
& 'C:\Program Files\Windows Media Player\wmplayer.exe' "c:\videos\my home video.avi" /fullscreen
Things can get tricky when an external command has a lot of parameters or there are spaces in the arguments or paths!
With spaces, you have to nest Quotation marks and the result is not always clear!
In this case it is better to separate everything like so:
$CMD = 'SuperApp.exe'
$arg1 = 'filename1'
$arg2 = '-someswitch'
$arg3 = 'C:\documents and settings\user\desktop\some other file.txt'
$arg4 = '-yetanotherswitch'
& $CMD $arg1 $arg2 $arg3 $arg4
or same like that:
$AllArgs = #('filename1', '-someswitch', 'C:\documents and settings\user\desktop\some other file.txt', '-yetanotherswitch')
& 'SuperApp.exe' $AllArgs
If the executable is not in your System path, or $env:PSModulePath, then you must provide the full path to the executable, as noted by the answer provided by 'Dan'.

The term 'Win32' is not recognized as the name of a cmdlet - pass a pipe symbol as part of an argument

I'm trying to make script for automate build's.
Stacked on "release|Win32" command
Command:
PS C:\Users\Builder> powershell.exe "& 'C:\Program Files\Microsoft Visual Studio 11.0\Common7\IDE\devenv.com'" C:\Build\
VS2012Build\3.2.7X\ClientServer\SHClientServer\SHCApplicationsVS2012.sln /Clean Release|Win32 No Local
Error:
The term 'Win32' is not recognized as the name of a cmdlet, function, script file, or operable program. Check the spell
ing of the name, or if a path was included, verify that the path is correct and try again.
At line:1 char:193
+ powershell.exe "& 'C:\Program Files\Microsoft Visual Studio 11.0\Common7\IDE\devenv.com'" C:\Build\VS2012Build\3.2.7X
\ClientServer\SHClientServer\SHCApplicationsVS2012.sln /Clean Release|Win32 <<<< No Local
+ CategoryInfo : ObjectNotFound: (Win32:String) [], CommandNotFoundException
+ FullyQualifiedErrorId : CommandNotFoundException
Since | is a metacharacter (a character with syntactic meaning) in PowerShell, you must quote it if you want to use it as part of an argument - either individually with ` or, more typically, by (single- or double-)quoting the entire argument:
powershell.exe "& 'C:\Program Files\Microsoft Visual Studio 11.0\Common7\IDE\devenv.com' C:\Build\VS2012Build\3.2.7X\ClientServer\SHClientServer\SHCApplicationsVS2012.sln /Clean 'Release|Win32' No Local"
Note how Release|Win32 is now single-quoted ('Release|Win32').
Also, I've enclosed the entire PowerShell command in "..." for robustness.

While running a batch file from Windows 10 cmd I'm getting an error that a term is not recognised as cmdlet function

This is the exact error on the cmd window.
this is the command I typed to be executed in the cmd
F:\Fast R-CNN\Cognitive tool kit\cntk\Scripts\install\windows>install.bat
CNTK Binary Install Script
F:\Fast : The term 'F:\Fast' is not recognized as the name of a cmdlet,
function, script file, or operable program. Check the spelling of the name, or
if a path was included, verify that the path is correct and try again.
At line:1 char:1
+ F:\Fast R-CNN\Cognitive tool kit\cntk\Scripts\install\windows\ps\inst ...
+ ~~~~~~~
+ CategoryInfo : ObjectNotFound: (F:\Fast:String) [], CommandNotF
oundException
+ FullyQualifiedErrorId : CommandNotFoundException
Error during install operation
I've tried running as admin, direct clicking, changing the path etc. Kindly tell me a way to run this file. It's a batch file for a series of installations for the Microsoft cognitive tool kit.
Looks like you need to enclose the path in quotes
"F:\Fast R-CNN\Cognitive tool kit\cntk\Scripts\install\windows\install.bat"
use "start" before the filename.
Example:
F:\Fast R-CNN\Cognitive tool kit\cntk\Scripts\install\windows>start install.bat

Errors when starting a PowerShell session

I was using PowerShell normally (was using posh git, just to mention), and suddenly a weird behavior happened, I tried to restart the session, when I did, I got many errors, which are :
Split-Path : The term 'Split-Path' is not recognized as the name of a cmdlet, function, script file, or operable program. Check the spelling of the name, or if a path
was included, verify that the path is correct and try again.
At C:\Users\aymen.daoudi\Documents\WindowsPowerShell\Modules\posh-git\profile.example.ps1:1 char:16
+ Push-Location (Split-Path -Path $MyInvocation.MyCommand.Definition -P ...
+ ~~~~~~~~~~
+ CategoryInfo : ObjectNotFound: (Split-Path:String) [], CommandNotFoundException
+ FullyQualifiedErrorId : CommandNotFoundException
Import-Module : The specified module '.\posh-git' was not loaded because no valid module file was found in any module directory.
At C:\Users\aymen.daoudi\Documents\WindowsPowerShell\Modules\posh-git\profile.example.ps1:4 char:1
+ Import-Module .\posh-git
+ ~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : ResourceUnavailable: (.\posh-git:String) [Import-Module], FileNotFoundException
+ FullyQualifiedErrorId : Modules_ModuleNotFound,Microsoft.PowerShell.Commands.ImportModuleCommand
Enable-GitColors : The term 'Enable-GitColors' is not recognized as the name of a cmdlet, function, script file, or operable program. Check the spelling of the name, or
if a path was included, verify that the path is correct and try again.
At C:\Users\aymen.daoudi\Documents\WindowsPowerShell\Modules\posh-git\profile.example.ps1:26 char:1
+ Enable-GitColors
+ ~~~~~~~~~~~~~~~~
+ CategoryInfo : ObjectNotFound: (Enable-GitColors:String) [], CommandNotFoundException
+ FullyQualifiedErrorId : CommandNotFoundException
Pop-Location : The term 'Pop-Location' is not recognized as the name of a cmdlet, function, script file, or operable program. Check the spelling of the name, or if a
path was included, verify that the path is correct and try again.
At C:\Users\aymen.daoudi\Documents\WindowsPowerShell\Modules\posh-git\profile.example.ps1:28 char:1
+ Pop-Location
+ ~~~~~~~~~~~~
+ CategoryInfo : ObjectNotFound: (Pop-Location:String) [], CommandNotFoundException
+ FullyQualifiedErrorId : CommandNotFoundException
Start-SshAgent : The term 'Start-SshAgent' is not recognized as the name of a cmdlet, function, script file, or operable program. Check the spelling of the name, or if
a path was included, verify that the path is correct and try again.
At C:\Users\aymen.daoudi\Documents\WindowsPowerShell\Modules\posh-git\profile.example.ps1:30 char:1
+ Start-SshAgent -Quiet
+ ~~~~~~~~~~~~~~
+ CategoryInfo : ObjectNotFound: (Start-SshAgent:String) [], CommandNotFoundException
+ FullyQualifiedErrorId : CommandNotFoundException
Here's a picture of that :
I tried to restart the PC, but still have the same problem every time I start a new PowerShell session, I noticed that many commands don't work, what caused this problem ? and what should I do to solve it ?
Update
I removed the profiles added by PoshGit, when starting a new session, I don't have any error, but powershell still doesn't recognize commands, for example calling Clear-host, throws lots of errors that I can't understand the cause !
You're PSModulePath system environment varaible is missing C:\windows\system32\WindowsPowerShell\v1.0\Modules which is the location of all "system"/built-in modules in PowerShell.
Something you've installed (posh git maybe?) has probably messed it up. Add it to the system variable.
The easiest way to do it without PowerShell is using the GUI as described here:
http://www.computerhope.com/issues/ch000549.htm
If you just installed posh-git it added some Powershell profile files, basically some .ps1 files executed each time a powershell session starts.
Just remove (or fix) them; from the path in the errors thrown probably they are in C:\Users\aymen.daoudi\Documents\WindowsPowerShell\...
I had a similar shell error message when loading my profile after installing posh-git ... profile.example.ps1 is not recognized as the name of a cmdlet.
This happened to me when I copied over files to my user directory from an older machine - the older poshgit powershell user profiles came along with it.
The fix for me was to rename the old posh-git profile from the path below...
Original Profile Path
C:\Users\<username>\Documents\WindowsPowerShell\Microsoft.PowerShell_profile.ps1
New Profile Name
C:\Users\<username>\Documents\WindowsPowerShell\Microsoft.PowerShell_profile.ps1.notused
After choco uninstall poshgit and choco install poshgit a new profile was created with the right data (went from 5KB to 1KB in size).

Resources