簡體   English   中英

在啟動時運行 powershell 腳本 (.ps1)

[英]Running a powershell script (.ps1) on startup

用這個撓我的頭。 Powershell 也很新。

目標:在機器啟動時,Powershell 腳本啟動並詢問計算機名稱,然后將其添加到域中,進行清理並重新啟動機器。

這是我的腳本:

$getName = Read-Host -Prompt "Enter the new name for this computer"
$user = "mdt_join"
$password = Read-Host -Prompt "Enter password for $user" -AsSecureString
$username = "bc\mdt_join"
$credential = New-Object System.Management.Automation.PSCredential($username,$password)

Add-Computer -NewName $getName -DomainName DOMAIN -OUPath "OU=Managed Stations,DC=DC,DC=DC,DC=DC" -Credential $credential -restart

Rename-Computer –NewName $getName

Remove-Item C:\Users\ladmin\AppData\Roaming\Microsoft\Windows\Start Menu\Programs\Startup\startup.cmd

Remove-Item $MyINvocation.InvocationName

如果我手動運行這個腳本,但是當我使用這個 startup.cmd 時

REM   Attempt to set the execution policy by using PowerShell version 2.0 syntax.
PowerShell -Version 2.0 -ExecutionPolicy Unrestricted .\script1.ps1 >> "%TEMP%\StartupLog.txt" 2>&1

IF %ERRORLEVEL% EQU -393216 (
   REM   PowerShell version 2.0 isn't available. Set the execution policy by using the PowerShell version 1.0 calling method.

   PowerShell -Command "Set-ExecutionPolicy Unrestricted" >> "%TEMP%\StartupLog.txt" 2>&1
   PowerShell .\startup.ps1 >> "%TEMP%\StartupLog.txt" 2>&1
)

REM   If an error occurred, return the errorlevel.
EXIT /B %errorlevel%

我沒有得到相同的結果。 它只是恢復到 PS C:> 位。 我需要 startup.cmd 以不受限制的方式運行它。

有人可以看看這個,看看我哪里出錯了嗎? 放輕松 - 我昨天才開始涉足 powershell。

嗯,這就像在調用 powershell 時添加一些開關一樣簡單

Powershell -noninteractive -nologo .\\startup.ps1

此外, .\\startup.ps1假定腳本位於 powershell 啟動的目錄中(猜測 C:),為了安全起見,我要么將CD放到腳本位置,要么只使用完整路徑,即。 Powershell -noninteractive -nologo C:\\Scripts\\startup.ps1

我沒有對您的代碼進行太多測試,但是根據我對 powershell 執行策略的了解,它是為了防止腳本更改它(因此是目的)。 話雖如此,我假設這是在新構建的計算機上運行的,在這種情況下,您需要找到另一種修改執行策略(注冊表、本地 GPO 等)的方法。

您可以創建每次 powershell 啟動時執行的 powershell 配置文件腳本。 我找到了這個鏈接; http://www.computerperformance.co.uk/powershell/powershell_profile_ps1.htm ,它告訴您如何創建和管理 PS 配置文件腳本。

在腳本中,您可以附加啟動腳本並將腳本分配給變量名稱,以便它們在命令提示符中的作用與環境變量相同。

因此,在您的情況下,只需將腳本添加到配置文件腳本的開頭,以便在 powershell 啟動時執行。

執行下面的 PowerShell 命令以在用戶登錄時通過任務調度程序運行 PowerShell 腳本.ps1

Register-ScheduledTask -TaskName "TASKNAME" -Trigger (New-ScheduledTaskTrigger -AtLogon) -Action (New-ScheduledTaskAction -Execute "${Env:WinDir}\System32\WindowsPowerShell\v1.0\powershell.exe" -Argument "-WindowStyle Hidden -Command `"& 'C:\PATH\TO\FILE.ps1'`"") -RunLevel Highest -Force;

-AtLogOn - 指示觸發器在用戶登錄時啟動任務。

-AtStartup - 指示觸發器在系統啟動時啟動任務。

-WindowStyle Hidden - 在啟動時不顯示 PowerShell 窗口。 如果不需要,請刪除。

-RunLevel Highest - 以管理員身份運行 PowerShell。 如果不需要,請刪除。

聚苯乙烯

如有必要,請執行下面的 PowerShell 命令以啟用 PowerShell 腳本執行。

Set-ExecutionPolicy -Scope LocalMachine -ExecutionPolicy Unrestricted -Force;

Bypass - 沒有被阻止,也沒有警告或提示。

Unrestricted - 加載所有配置文件並運行所有腳本。 如果您運行從 Internet 下載的未簽名腳本,系統會在運行前提示您獲得許可。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM