How do run a powershell script as an admin? - powershell

I have the silent uninstall/wait/install script below that I need to push out to users, but I need to script it so it runs as administrator and I found some scripts, but I'm not understanding how to script it, any help is appreciated. Also, do I have to put the administrator script in twice? (i.e. in the first line of the uninstall script then before the line of the 2nd install script) or just once when I run it?
Get-WmiObject -Class Win32_Product | Where-Object {$_.Name -eq "On-Screen Takeoff"} | foreach-
object -process {$_.Uninstall()}
Start-Sleep -Seconds 25
$arguments="/quiet"
Start-Process "\\davisconstruction.com\ROOT\Installs\OnCenter\OST\Testverion3906\ost3906.msi" $arguments

There are two ways:
You can right-click on "Start" --> "Windows PowerShell Module" or "Windows PowerShell ISE" by going to "Start" --> "Administrative Tools" --> "Windows PowerShell Module" or "Windows PowerShell ISE".
Select "Run As administrator".
Anything you run in that window will be as "Administrator".
Run your script as:
Start-Process "$psHome\powershell.exe" -verb runas -ArgumentList "-file fullpathofthescript"

Related

I want to run Power Shell script with admin privileges

I want to run this powershell script with admin privileges so it won't give me the error:
Script Output with error
Here is the script:
$processes = "PDStyleAgent", "AdobeIPCBroker", "CCXProcess", "RichVideo64", "CCLibrary", "AdobeNotificationClient", "AdobeUpdateService", "PDHanumanSvr", "PDR"
Foreach ($process in $processes){
try {
$f = Get-Process $process -ErrorAction Stop
$f | kill
Write-Output "$process killed."
}
catch [Microsoft.PowerShell.Commands.ProcessCommandException]{
Write-Output "No instances of $process running."
}
}
Start-Sleep -Seconds 3
I want to run this script so it kill the processes that are giving errors
Some way to run PowerShell with admin privileges:
Search Powershell from the Windows search icon OR click the Windows button from the keyboard --> write Powershell --> You will see the Windows PowerShell --> Right-click on Powershell then click Run as administrator.
Run this command of a PowerShell console: Start-Process powershell -Verb runAs
Run your script from PowerShell like this: PowerShell -f C:\ScriptPath
For more details, you can check this StackOverflow question and answer.
I'm not sure what exactly you are asking about. If you want to start a script as administrator, you need to open PowerShell window "As administrator".
BTW, the script itself can be simplified without losing functionality:
$processes = "PDStyleAgent", "AdobeIPCBroker", "CCXProcess", "RichVideo64", "CCLibrary", "AdobeNotificationClient", "AdobeUpdateService", "PDHanumanSvr", "PDR"
Get-Process -Name $processes -ErrorAction SilentlyContinue | Stop-Process -Verbose
1.Create a shortcut to your Powershell script on your desktop
2.Right-click the shortcut and click Properties
3.Click the Shortcut tab
4.Click Advanced
5.Select Run as Administrator
NOTE: add powershell -f in front of the script path

Switch service running state using powershell (using UAC prompts)

$serviceName = "wsearch"
$isRunning = Get-Service | Where-Object {$_.Status -eq "Running" -and $_.Name -eq $serviceName}
$isStopped = Get-Service | Where-Object {$_.Status -eq "Stopped" -and $_.Name -eq $serviceName}
if ($isStopped) {
Start-Service -InputObject $isStopped
Start-Sleep -s 10
}
if ($isRunning) {
Stop-Service -InputObject $isRunning
Start-Sleep -s 10
}
I want to run this script, but I don't want to set Administrator execution policy (which is set to max restrictive), while regular user policy is lax.
I want to run the script as a regular user and trigger the UAC prompt for each command (akin to -Verb RunAs), however, Start-Service does not accept this parameter.
I guess I can run a Start-Process "sc" but that defeats the purpose of powershell.
The ultimate goal of the script is to swtich the state of a service based on the current running state.
There is no way to run one-off commands elevated (as admin) in a non-elevated powershell session. This would be similar to 'sudo' in Linux which just doesn't exist in the Windows world. Instead you could use something like the following to start a powershell session as administrator and run the commands there. You are not limited to calling 'sc'
Start-Process -Verb RunAs -FilePath 'powershell' -Arguments '-Command <your commands>'
To run a powershell script with elevated privileges you could substitute -Command for -File (but -Command <path to file> will also work)
Start-Process -Verb RunAs -FilePath 'powershell' -Arguments '-File <path to script>'

Powershell is returning exit code too quickly

I have a script to uninstall McAfee antivirus and the agent associated with it.
The issue i'm having is that the script provides an exit code too early and doesn't continue through. If I run the script multiple times I get the desired result, but as we're trying to push it out via PDQ remotely, we need it to run through the script and only provide an exit code at the end of the script.
I'm a powershell novice so there's probably a much better and easier way to write this script but any advice would be greatly appreciated.
Start-Process -FilePath "msiexec.exe" -ArgumentList "/x {CE15D1B6-19B6-4D4D-8F43-CF5D2C3356FF} REMOVE=ALL REBOOT=R /q"; Write-Host "Uninstalling McAfee VirusScan Enterprise 8.8..."
$version = (Get-WmiObject -class Win32_OperatingSystem).Caption
Write-Host "Detected OS as $version"
if ($version -like '*Windows 7*')
{
Write-Host "Uninstalling McAfee Agent..."
Start-Process -FilePath "C:\Program Files (x86)\McAfee\Common Framework\frminst.exe" -ArgumentList "/forceuninstall"
}
elseif ($version -like '*Windows 10*')
{
Write-Host "Unmanaging McAfee Agent for Uninstall Process.."
Start-Process -FilePath "C:\Program Files\McAfee\Agent\maconfig.exe" -ArgumentList "/provision /unmanaged";
Write-Host "Uninstalling McAfee Agent..."
Start-Process -FilePath "C:\Program Files\McAfee\Agent\x86\frminst.exe" -ArgumentList "/forceuninstall"
}
else
{
exit
}
Start-Process reports a return code as soon as it starts the process indicating whether it was successful or not. Either use -wait to force the script to wait until it finishes or capture the output and proceed based on what the returnvalue is. See the docs for Start-Process

Can I check which Version my PS Script needs?

Sometimes when I'm writing a script on my Windows 10 Machine (PowerShell 5.0) I use commands, parameters or aliases which are not available on earlier versions of PowerShell, e.g the -persist parameter of new-psdrive is not available on PowerShell 2.0 which all of our Win7 machines use.
to set my #requires -version x statement correctly, I need to know if there are commands in my script which aren't available to earlier PowerShell Versions. When you wrote a code with 1000 lines it could be a little difficult to find unavailable commands in your script.
Is there a way to check this programmatically, other than just run the script in different PowerShell environments and see what's happening?
Have you considered developing on your Windows 10 machine but set your powershell profile to always run a powershell -version 2?
You'll launch powershell which will launch version 2 to develop in and if there are errors in the script you'll know when they're created and commands that would run in version 5 (or whatever version your Win10 machine has) would fail.
It should be noted that launching powershell like this:
powershell -version 2
will keep the logic the same and act like the version 2 powershell but the help file and output from commmands Get-Help will still show the version 5(or whatever) syntax that is true powershell version.
Setting your Powershell Profile:
http://www.howtogeek.com/50236/customizing-your-powershell-profile/
You can check the running version with
$PSVersionTable
This doesnt really answer your question
but i use the "Script Analyser" that comes with https://gallery.technet.microsoft.com/scriptcenter/Getting-started-with-57e15ada
I had previously thought that it would be good if it was enhance to check at different version levels. either output the minimum version for your script. or you specify a target version and it would tell you what was wrong.
We decided to make Powershell v.4 baseline for all systems. So I wrote a powershell script to ensure v.4 is install on all systems. This is set to run via GPO shutdown script under machine configuration.
IF ($PSVersionTable.PSVersion.Major -like "4*"){$StringToWrite | Out-File -FilePath $Logpath\PwrShl\Powershell_UpToDate_$hostname.log -Append; IF (Test-Path -Path $Logpath\PwrShl\Powershell_OutofDate_$hostname.log){Remove-Item $Logpath\PwrShl\Powershell_OutofDate_$hostname.log -Force}; exit}
IF (($PSVersionTable.PSVersion.Major -like "2*") -or ($PSVersionTable.PSVersion.Major -like "3*")){$StringToWrite | Out-File -FilePath $Logpath\PwrShl\Powershell_OutofDate_$hostname.log -Append}
if ($env:PROCESSOR_ARCHITECTURE -eq "x86"){
if (!(Test-Path C:\SchTsk\Temp\Windows6.1-KB2819745-x86-MultiPkg.msu)){Copy-Item "\\ad.dcpds.cpms.osd.mil\SYSVOL\ad.dcpds.cpms.osd.mil\Policies\{31B2F340-016D-11D2-945F-00C04FB984F9}\MACHINE\Scripts\Startup\Windows6.1-KB2819745-x86-MultiPkg.msu" -Destination C:\SchTsk\Temp\Windows6.1-KB2819745-x86-MultiPkg.msu -Force}
}
if ($env:PROCESSOR_ARCHITECTURE -eq "AMD64"){
if (!(Test-Path C:\SchTsk\Temp\Windows6.1-KB2819745-x64-MultiPkg.msu)){Copy-Item "\\ad.dcpds.cpms.osd.mil\SYSVOL\ad.dcpds.cpms.osd.mil\Policies\{31B2F340-016D-11D2-945F-00C04FB984F9}\MACHINE\Scripts\Startup\Windows6.1-KB2819745-x64-MultiPkg.msu" -Destination C:\SchTsk\Temp\Windows6.1-KB2819745-x64-MultiPkg.msu -Force}
}
IF ($env:PROCESSOR_ARCHITECTURE -eq "x86"){
Set-Location C:\SchTsk\Temp
if (!(Test-Path C:\SchTsk\Temp\Windows6.1-KB2819745-x86-MultiPkg.msu)){exit}
expand -F:* .\Windows6.1-KB2819745-x86-MultiPkg.msu C:\SchTsk\Temp
Start-Process dism.exe -ArgumentList '/online /add-package /PackagePath:C:\SchTsk\Temp\Windows6.1-KB2872035-x86.cab /NoRestart' -Wait
Start-Process dism.exe -ArgumentList '/online /add-package /PackagePath:C:\SchTsk\Temp\Windows6.1-KB2872047-x86.cab /NoRestart' -Wait
Start-Process dism.exe -ArgumentList '/online /add-package /PackagePath:C:\SchTsk\Temp\Windows6.1-KB2819745-x86.cab /NoRestart' -Wait
}
IF ($env:PROCESSOR_ARCHITECTURE -eq "amd64"){
Set-Location C:\SchTsk\Temp
if (!(Test-Path C:\SchTsk\Temp\Windows6.1-KB2819745-x64-MultiPkg.msu)){exit}
expand -F:* .\Windows6.1-KB2819745-x64-MultiPkg.msu C:\SchTsk\Temp
Start-Process dism.exe -ArgumentList '/online /add-package /PackagePath:C:\SchTsk\Temp\Windows6.1-KB2809215-x64.cab /NoRestart' -Wait
Start-Process dism.exe -ArgumentList '/online /add-package /PackagePath:C:\SchTsk\Temp\Windows6.1-KB2872035-x64.cab /NoRestart' -Wait
Start-Process dism.exe -ArgumentList '/online /add-package /PackagePath:C:\SchTsk\Temp\Windows6.1-KB2872047-x64.cab /NoRestart' -Wait
Start-Process dism.exe -ArgumentList '/online /add-package /PackagePath:C:\SchTsk\Temp\Windows6.1-KB2819745-x64.cab /NoRestart' -Wait
}
Are network speed is kind of crapy and I was having problems with it trying to continue to run and the file not be existant. So I simply had it exit if the file isn't there to extract and install. Since it takes a restart, shutdown script made the most since. This was pretty successful for me, had a few trouble childs.

Powershell Start-job new window run as administrator

I have script which write some COMMAND to another script and start them in new window with Start-Job command (I really need that). $cred is credential of local administrator. Main script started from powershell windows which opened "run as administrator" (as machine administrator). COMMAND need to open with machine administrator account (like new window open with "run as administrator"). BUT new window open only with local administrator rights. I search in the internet for information to round this issue, but failed. May be someone know how i can run new window with start-job command with machine administrator ("run as administrator")?
$ScriptFile = "$env:TEMP\ScriptBlock.ps1"
Write-Output "`$ProfileApp = <COMMAND> | Out-File $ScriptFile -Width 300
$PJob = Start-Job -Name PJob -Credential $cred -FilePath $ScriptFile -Verbose -InitializationScript {Add-PsSnapin Microsoft.SharePoint.PowerShell} | Wait-Job
Receive-Job -Name PJob -Verbose
Remove-Job -Name PJob -ErrorAction SilentlyContinue -ErrorVariable err
Remove-Item -Path "$env:TEMP\ScriptBlock.ps1"
I believe this might be what you are looking for:
A self elevating PowerShell script