Как использовать один сценарий PS для выполнения другого сценария PS, включая учетные данные - PullRequest
0 голосов
/ 01 февраля 2020

Простите, пожалуйста, за этот вопрос ...

Обновляя одну из наших систем до Windows Server 2016, вы можете знать, что безопасность повышается. Таким образом, возможность сохранения учетных данных для пользователя может быть недоступна, особенно если в вашем учреждении есть врач общей практики, который запрещает это делать. Например, при настройке сценария PS для запуска от имени меня или другого пользователя с повышенными правами планировщик задач не разрешит сохранение пароля этого пользователя. Фактически, вы не можете вносить изменения в задачу из-за этого ограничения.

Я изменил задачу для запуска в качестве системного пользователя, но мне нужно безопасно выполнить второй сценарий PS. Поскольку скрипт в основном копирует файлы отчетов с сервера A на сервер B, он должен выполняться как пользователь с правильными разрешениями. Конечно, если я выполняю сценарий при входе на сервер A, мои учетные данные домена AD предоставляются для того, чтобы я мог копировать файлы на сервер B.

Итак, во всем этом я ищу код, который позволит:

  1. , чтобы системный пользователь выполнял ScriptA.ps1 через планировщик задач.
  2. ScriptA.ps1 для безопасного захвата моих учетных данных AD и выполнения ScriptB.ps1.
  3. ScriptB.ps1 для правильного выполнения с правильными учетными данными успешно!

Кто-нибудь есть с рекомендацией? Ниже приведен мой код для двух сценариев:

CopyCreds.ps1 (ScriptA)

<#===================================================================================
 Name    : Run powershell script using AD credentials
 Author  : xxxxxxxxx(REB)
 Date    : 1/29/2020
 Updated : 1/30/2020
===================================================================================#>

# Obtain AD credentials to pass to CopyReports2HDSFiles script
$user = "domain\username"
$pword = ConvertTo-SecureString -String "mypassword" -AsPlainText -Force
$credential = New-Object -TypeName System.Management.Automation.PSCredential -ArgumentList $User, $pword

# Using captured credentials, pass through to execute powershell script as that user
Invoke-Command -ComputerName "Server B" -FilePath "C:\scripts\TEST-CopyReportxxxxxxxxx.ps1" -Credential $credential

<# ======================== Documentation ==============================================
1/30/2020 - Copy of original file renamed with TEST for testing purposes.

1/29/2020 - Original creation of CopyCred.ps1 file.

This script captures user (with elevated privileges) credentials to pass to the 
CopyReportsxxxxxxx.ps1 script when used by the Task Scheduler as any other user.
This user also has access to the remote computer and files therein. - REB
======================================================================================= #>

Я также включил локальный хост '-ComputerName' в команду 'Invoke', однако, что не работал.

CopyReportsxxxxx.ps1 (ScriptB)

 <#===================================================================================
 Name    : New Micros POS Daily reports file copy script or CopyReportsxxxxxx.ps1
 Author  : xxxx
 Date    : 12/20/2019
 Updated : 1/29/2020 (see "Documentation" section at the bottom for more information.
 ===================================================================================#>

# Create/append log file for any errors with copying files
Start-Transcript -Path "C:\scripts\CopyReports_logfile.txt" -Append  

# Set the execution policy on Micros server to allow for scrip to properly run, if needed, then remove hash:
# Set-ExecutionPolicy RemoteSigned #-Scope CurrentUser 

# Map the necessary network drives to Server B
New-PSDrive -Verbose -Name "target" -PSProvider FileSystem -Root "\\Server B\share\folder\TEST"

# Set "ret" variable as the previous day's date
Set-Variable -Verbose -Name ret -Value (Get-Date (Get-Date).AddDays(-1) -Format "MM-dd-yy")
Set-Variable -Verbose -Name ret2 -Value (Get-Date (Get-Date).AddDays(-1) -Format "yyyyMMdd")
Set-Variable -Verbose -Name ret3 -Value (Get-Date -Format "yyyy")

# Copy the CC Batch Details, CC Transfer Details, and Consolidated RVC Sales reports for "user" to the Server B folder
Copy-Item -Verbose "C:\C_DTP\RVC Reports\CC Batch Detail\CC_Batch_Detail.pdf" -Destination "target:\CC Batch Detail\FY20\January 2020\$ret.pdf"
Copy-Item -Verbose "C:\C_DTP\RVC Reports\CC Transfer Status\CC_Transfer_Status.pdf" -Destination "target:\Batch Transfer Status Reports\2020\$ret.pdf"
Copy-Item -Verbose "C:\C_DTP\RVC Reports\RVC Sales Detail\Daily_RVC_Sales_Detail.pdf" -Destination "target:\Sales Report\FY20\January 2020\$ret.pdf"

# Copy the Journal files (individual register receipt files) from Micros to Server B:
Copy-Item -Verbose "C:\MICROS\Res\Pos\ARCHIVES\HOLD\Journal_$ret3*.zip" -Destination "target:\Manual Journal Files\"

# From .bat script of "user", rewritten for Powershell, to create the new dated directory
New-Item -Verbose -Path "C:\MICROS\Res\Pos\ARCHIVES\HOLD\" -Name "$ret2" -ItemType "Directory"

# and copy report Excel files
Copy-Item -Verbose "C:\c_dtp\a RVC 1 VZ QC\" -Destination "C:\MICROS\Res\Pos\ARCHIVES\HOLD\$ret2\RVC1-VanZile-QC\" -Recurse
Copy-Item -Verbose "C:\c_dtp\a RVC 2 KR QC\" -Destination "C:\MICROS\Res\Pos\ARCHIVES\HOLD\$ret2\RVC2-Kramer-QC\" -Recurse
Copy-Item -Verbose "C:\c_dtp\a RVC 3 MR QC\" -Destination "C:\MICROS\Res\Pos\ARCHIVES\HOLD\$ret2\RVC3-Moore-QC\" -Recurse
Copy-Item -Verbose "C:\c_dtp\a RVC 4 JR CS\" -Destination "C:\MICROS\Res\Pos\ARCHIVES\HOLD\$ret2\RVC4-Jardine-CS\" -Recurse
# Copy-Item -Verbose "C:\c_dtp\a RVC 5\" -Destination "C:\MICROS\Res\Pos\ARCHIVES\HOLD\$ret2\RVC5-JPs-Servers\" -Recurse
Copy-Item -Verbose "C:\c_dtp\a RVC 6 JPs\" -Destination "C:\MICROS\Res\Pos\ARCHIVES\HOLD\$ret2\RVC6-JPs-Bar\" -Recurse
Copy-Item -Verbose "C:\c_dtp\a RVC 7\" -Destination "C:\MICROS\Res\Pos\ARCHIVES\HOLD\$ret2\RVC7-Bakery\" -Recurse
Copy-Item -Verbose "C:\c_dtp\a RVC 8 Cliffside\" -Destination "C:\MICROS\Res\Pos\ARCHIVES\HOLD\$ret2\RVC8-Cliffside\" -Recurse
Copy-Item -Verbose "C:\c_dtp\a RVC 9 Overtime\" -Destination "C:\MICROS\Res\Pos\ARCHIVES\HOLD\$ret2\RVC9-Overtime\" -Recurse
Copy-Item -Verbose "C:\c_dtp\a RVC 10 KR CS\" -Destination "C:\MICROS\Res\Pos\ARCHIVES\HOLD\$ret2\RVC10-Wefald-CS\" -Recurse
# Copy-Item -Verbose "C:\c_dtp\a RVC 11\" -Destination "C:\MICROS\Res\Pos\ARCHIVES\HOLD\$ret2\RVC11-Wefald-CS\" -Recurse
Copy-Item -Verbose "C:\c_dtp\a RVC 20 Union Station\" -Destination "C:\MICROS\Res\Pos\ARCHIVES\HOLD\$ret2\RVC20-Union-Station\" -Recurse
Copy-Item -Verbose "C:\c_dtp\a RVC 21 Fast Track\" -Destination "C:\MICROS\Res\Pos\ARCHIVES\HOLD\$ret2\RVC21-Fast-Track\" -Recurse 

# Now to copy the new folder to HDS-Files
Copy-Item -Verbose "C:\MICROS\Res\Pos\ARCHIVES\HOLD\$ret2\" -Destination "target:\Micros to IM Upload\" -Recurse

# Disconnect temporary mapped drives
Remove-PSDrive -Verbose target

# Stop writing logfile
Stop-Transcript

<# ================================================== Documentation =============================================================================
1/30/2020 - This test copy of the copy file has been created in an attempt to test passing of credentials from CopyCreds.ps1 to this file.
        The \TEST folder has been set as the root directory of TARGET so not to interfere with live data.

1/14/2020 - added the capacity to create a log file with line 9, Start-Transcript to line 55, Stop-Transcript. Also included -Verbose command
        to allow each command's result to be added to the log file. This may be removed later on as this was all added to assist with
        troubleshooting Autosequence report and copy file issues.

1/6/2020 - changed New-PSDrive from 3 separate targets to one; possibly causing the issue with writing reports.

12/20/2019 - after Micros server upgrade on 12/11/2019, it was determined that these files were not uploading to the Server B per the old 
        batch file that ran on the previous Micros server. Using Powershell, that batch file was re-written so as to take advantage of newer
        code of powershell scripting. Batch file was using ROBOCOPY, which still could be used.
        All of this is to help automate manual process by Heather Neidfeldt where she was creating the first 3 reports manually, then copying
        them, via a RDC to a MMWS console, to the Server B. The "Micros to IM Upload" files are for reports to be used with updating
        FIS system (Income Management) for accounting purposes.
=========================================================================================== #>

Все это сэкономит одному из наших сотрудников бухгалтерии несколько минут работы, чтобы скопировать файлы и запустить отчеты. Система автоматически генерирует несколько отчетов, но это скопирует их для них.

Я нашел несколько статей здесь, в Переполнении стека, относительно передачи учетных данных, однако, похоже, ничего не работает так, как мне нужно это к. Я открыт для любых предложений, даже другого подхода к решению этой задачи.

Спасибо, что нашли время, чтобы прочитать это и с нетерпением ждем обратной связи. :)

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...