从powershell内部以管理员身份执行批处理脚本

时间:2014-06-05 17:26:34

标签: windows batch-file powershell

我正在尝试安排一个每周任务来备份一些重要数据(最终,我想从Windows任务管理器运行PowerShell脚本)。软件提供商已经有一个批处理脚本(backup.bat)。我编写了一个powershell脚本来调用这个批处理脚本。但是,从powershell调用backupdb会导致抛出“Permission denied”错误消息。

我尝试了以下,但没有用:

start-process $BackupCmd -verb runas -ArgumentList "$Flags `"$BackupFile`""

在查看SO和其他论坛上的几篇帖子之后,我能够找到从批处理脚本中以管理员身份运行powershell脚本的答案,而不是相反。

how to run as admin powershell.ps1 file calling in batch fileRun a powershell script in batch file as administratorHow to run a PowerShell script from a batch file

编辑1:

1.我以同一个用户身份运行批处理脚本和PowerShell脚本。

2.我尝试使用“-verb runas”升级PowerShell,但没有用。从与批处理脚本相同的提升窗口运行PowerShell脚本不起作用。

3.发布以下PowerShell脚本:

$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:

感谢。

1 个答案:

答案 0 :(得分:1)

我在批处理脚本上使用start-process-verb runas时遇到了问题。

尝试在powershell上使用start-process,将批处理文件作为第一个参数传递:

$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