繁体   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