Execute a batch script as admin from inside powershell - windows

I am trying to schedule a weekly task that takes a backup of some important data (Eventually, I want to run the PowerShell script from Windows task manager). The software provider already has a batch script for this (backup.bat). I have written a powershell script that invokes this batch script. But invoking backupdb from powershell fails throwing a "Permission denied" error message.
I tried the below, which did not work:
start-process $BackupCmd -verb runas -ArgumentList "$Flags `"$BackupFile`""
After looking at several posts on SO and other forums, I was able to find answers for running a powershell script from inside a batch script as admin and not the other way round.
how to run as admin powershell.ps1 file calling in batch file, Run a powershell script in batch file as administrator and How to run a PowerShell script from a batch file
EDIT 1:
1.I run the batch script and the PowerShell script as the same user.
2.I tried elevating the PowerShell using "-verb runas", but did not work. Running the PowerShell script from the same elevated window as the batch script does not work.
3.Pasting the PowerShell script below:
$CurrentDate = get-date -format yyyyMMdd
$BackupStartDate = (get-date).AddDays(-7).ToString("yyyyMMdd")
$BackupDir = "<directory path>"
$BackupFile = $BackupDir + "Backup-" + $BackupStartDate + "-to-" + $CurrentDate + ".txt"
$BackupCmd = "C:\Progra~1\bin\backup"
$Verbose = " -v "
$ArchiveStart = " -S " + $BackupStartDate
$Flags = $Verbose + $ArchiveStart
# Both commands below do not work
start-process $BackupCmd -verb runas -ArgumentList "$Flags `"$BackupFile`""
& $BackupCmd $Flags `"$BackupFile`"
4.Error:
backup.bat : Error writing to the debug log! <type 'exceptions.IOError'> [Errno 13]
Permission denied: 'C:\\Program Files\\tmp\\debug.log'
(2014/06/05 12:42:01.07) [8764] --> Exception encountered. <Unable to load config file!>
Error writing to the debug log! <type 'exceptions.IOError'> [Errno 13] Permission denied:
Thanks.

I have encountered problems using start-process with -verb runas on batch scripts.
Try using start-process on powershell instead, passing your batch file as the first argument:
$CurrentDate = get-date -format yyyyMMdd
$BackupStartDate = (get-date).AddDays(-7).ToString("yyyyMMdd")
$BackupDir = "C:\"
$BackupFile = $BackupDir + "Backup-" + $BackupStartDate + "-to-" + $CurrentDate + ".txt"
$BackupCmd = "C:\Progra~1\bin\backup.bat"
$Verbose = "-v"
$ArchiveStart = "-S $BackupStartDate"
$Flags = "$Verbose $ArchiveStart"
$Args = "$BackupCmd $Flags `"$BackupFile`""
start-process powershell -verb runas -ArgumentList $Args

Related

Why won't this script run?

# Set the path to the AOMEI Backupper Technician executable
$abtExecutable = "C:\Program Files (x86)\AOMEI Backupper Technician\Backupper.exe"
# Set the destination for the system image backup
$backupDestination = "C:\Backups\System Image"
# Set the password for the backup
$password = "12121212121212121212"
# Set the compression level to 'high'
$compression = "high"
# Check if there is already a system image backup from 30 days ago
$thirtyDaysAgo = (Get-Date).AddDays(-30)
$oldBackup = Get-ChildItem $backupDestination | Where-Object { $_.LastWriteTime -lt $thirtyDaysAgo }
# If there is an old backup, delete it
if ($oldBackup) {
Remove-Item -Path $oldBackup.FullName -Force
}
# Create the full system image backup
& $abtExecutable backup system -d $backupDestination -p $password -c $compression
Whenever I try to run this in Powershell, the most it does is it launches the AOMEI backupper exe. But it doesn't do any of the other steps.
I expected it to work. Whenever I try to run this in Powershell, the most it does is it launches the AOMEI backupper exe. But it doesn't do any of the other steps.
As per my comment,
powershell /?
EXAMPLES
...
PowerShell -Command {Get-EventLog -LogName security}
PowerShell -Command "& {Get-EventLog -LogName security}"
PowerShell- Running Executables - TechNet Articles - United States (English) - TechNet Wiki
doing your console stuff in a script via Start-Process.
$ConsoleCommand = 'Some Console Command'
$startProcessSplat = #{
FilePath = 'powershell'
ArgumentList = '-NoExit', 'NoProfile', '-Command &{ $ConsoleCommand }'
Wait = $true
}
Start-Process #startProcessSplat
Or just call directly in your script without calling the powershell console at all, since your $abtExecutable is a stand-alone executable and really calls cmd.exe to run, which Start-Process will do by default.

Use PowerShell to create a shortcut to launch a PowerShell script

I have a need to create a shortcut on a Windows 2019 Server for the Eclipse application so that it runs a PowerShell script instead of opening Eclipse. The script runs a few commands first and then opens the Eclipse application. When I edit an existing shortcut for Eclipse, I can modify the target to be:
"powershell.exe -ExecutionPolicy bypass C:\temp\eclipse-fix.ps1 -WindowStyle Hidden"
This works fine when completed manually. However, when I try to do the same with a PowerShell script, to automate the process, I get an error.
Contents of the script:
$WshShell = New-Object -comObject WScript.Shell
$Shortcut = $WshShell.CreateShortcut("C:\Users\Administrator\Desktop\Eclipse.lnk")
$Shortcut.TargetPath = "C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe -ExecutionPolicy bypass C:\cfn\temp\eclipse-fix.ps1 -WindowStyle Hidden"
$Shortcut.IconLocation = "%SystemDrive%\eclipse\eclipse.exe"
$Shortcut.Save()
Error Returned:
PS C:\Users\Administrator> $WshShell = New-Object -comObject WScript.Shell
PS C:\Users\Administrator> $Shortcut = $WshShell.CreateShortcut("C:\Users\Administrator\Desktop\Eclipse.lnk")
PS C:\Users\Administrator> $Shortcut.TargetPath = "powershell.exe -File C:\cfn\temp\eclipse-fix.ps1"
Value does not fall within the expected range.
At line:1 char:1
+ $Shortcut.TargetPath = "powershell.exe -File C:\cfn\temp\eclipse-fix. ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : OperationStopped: (:) [], ArgumentException
+ FullyQualifiedErrorId : System.ArgumentException
PS C:\Users\Administrator> $Shortcut.IconLocation="%SystemDrive%\eclipse\eclipse.exe, 0"
PS C:\Users\Administrator> $Shortcut.Save()
Result:
The icon is created but has no value for target.
Does anyone know what I am missing to get this to work? Is there another option to use that I may not be aware of?
Thanks.
You need to specify the Arguments separate from the TargetPath
$WshShell = New-Object -comObject WScript.Shell
$Shortcut = $WshShell.CreateShortcut("C:\Users\Administrator\Desktop\Eclipse.lnk")
$Shortcut.TargetPath = "C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe"
$Shortcut.Arguments = "-ExecutionPolicy bypass C:\cfn\temp\eclipse-fix.ps1 -WindowStyle Hidden"
$Shortcut.IconLocation = "%SystemDrive%\eclipse\eclipse.exe"
$Shortcut.Save()
You can also use just powershell.exe in place of the full path. Either will work.
Here is a script I wrote that will create a shortcut to itself on the desktop that is executable (Can run by double clicking) when run.
I did this to take the step-by-step process out of colleagues having to create their own shortcuts of my powershell automation scripts.
Because our shared drive at work is a different location for everybody, I use the "Get-location" command which gets the pwd, then trim it and parse it for use within the shortcut's argument field.
In order to have the arguments contain double quotes, you have to use the escape character ` preceding another set of quotes, this will allow for the script to send quotes to the arguments field. It will not work without this. '" '"
Make sure that when you are running the script you are not running it from the powershell IDE, or the file paths will be wrong. You need to save the script in your target source path and the nrun it from there by either right ckicling it and running it as a powershell script or creating an executable shortcut for it. Let me know if you need instructions on how to create an executable powershell shortcut.
Hope this helps!
#Grap the pwd
$location = Get-Location | Select Path | ft -HideTableHeaders | Out-String;
#Trim the pwd variable of any extra spaces and unwanted characters
$location = $location.Trim();
$locations = $location.replace(' ' , '');
$locations = $locations.replace("`n","");
#Make the source file location my path to powershell.exe
$SourceFileLocation = "`"C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe`"";
# Declare where I want to place the shortcut, I placed it on the desktop of whomever is running the script with the dynamic $env:USERNAME which takes the username of whomever is running the script - You can name the shortcut anything you want at the end as long as it ends with .LNK
$ShortcutLocation = “C:\Users\$env:USERNAME\OneDrive\Desktop\PopupSortcut.lnk”;
#Create a now com
$WScriptShell = New-Object -ComObject WScript.Shell;
#create shortcut and provide the location parameter as an argument
$Shortcut = $WScriptShell.CreateShortcut($ShortcutLocation);
#set the target path
$Shortcut.TargetPath = $SourceFileLocation;
#Add arguments that will bypass the execution policy as well as provide a path to the source powershell script (make sure that the entire argument has double quotes around it and that the internal quotes have escape characters (`) behind them, these are not apostrophes but back ticks, located on the same key as the tilde (~) key on the keyboard
$Shortcut.Arguments = “-ExecutionPolicy Bypass -file `"$locations"+"Pop-up.ps1`"”;
#Save the Shortcut
$Shortcut.Save();
########################### This is the meat of our script Performing an Operation #######################
$wshell = New-Object -ComObject Wscript.Shell;
$wshell.Popup("Operation Completed",0,"Done",0x1);

Passing a response file to a process in Powershell

I have a process that would traditionally be run like so (in the command line):
filepath.exe #"respfile.resp"
where respfile.resp is a response file that has command line arguments for the executable.
Running the command like that works as desired in the command prompt.
However I am trying to use a powershell script to run multiple programs. Here is what I have:
if (Test-Path $respPath){
$executionResposne = Start-Process -NoNewWindow -Wait -PassThru -FilePath $bimlcExePath -ArgumentList $respPath
if ($executionResposne.ExitCode -eq 1){
Write-Output "Unable to successfully run the process. Exiting program."
return
}
}
and I am getting the following error message:
Error:: filepath\to\resp\file Data at the root level is invalid.
How can I make this work?
You need to embed the quotes for the interpreter:
-ArgumentList "#`"$respPath`""

Powershell output doesn't log properly when called from Task Scheduler

I need to log my powershell output. My ps file is something like this:
#Set-ExecutionPolicy Unrestricted
$ErrorActionPreference="SilentlyContinue"
Stop-Transcript | out-null
$ErrorActionPreference = "Continue"
$date = (Get-Date).tostring("MMddyy HHmmss")
$filename = 'C:\apierror\logs\' + $date + '.txt'
Start-Transcript -path $filename -append
$python = "C:\Python34\python.exe"
$python_path = "C:\script.py"
cd (split-path $python_path)
& $python $python_path
Stop-Transcript
Now, when I run this file directly from powershell, the output is logged correctly. But when I try to run it from taskscheduler - only some portion of the console output is stored in the file.
Any ideas why that might be?
Using transcript only stored partial output for some reason. I ended up using logs directly into the python file as opposed to powershell. Seems to be working correctly.

Powershell Write Bitlocker status to text file

I am trying to write the bitlocker status to a text file via powershell by invoking a cmd shell but it doesn't seem to work. Any ideas?
Here is what i have tried so far
#doesn't work
cmd /c manage-bde.txt>c:\bitlockerstatus.txt
# makes an empty file
$oProcess = Start-Process cmd.exe -ArgumentList "manage-bde>c:\bitlockerstatus.txt" -wait -NoNewWindow -PassThru
$oProcess.HasExited
$oProcess.ExitCode
#doesn't work
[Diagnostics.Process]::Start("cmd.exe","/c manage-bde>c:\bitlockerstatus.txt")
why don't you call the exe directly from powershell using the & operator ?
& manage-bde.exe -status > c:\temp\bl.txt

Resources