初始化EC2实例时,永久设置Windows PowerShell系统路径

时间:2018-01-16 02:56:17

标签: python windows powershell amazon-ec2 environment-variables

我的目标是run powershell commands on EC2 Windows Server 2016 instance at launch,以便永久设置多个系统路径。

<powershell>
######### SET SYSTEM PATHS #########
# We need to restart the compute in order for the system paths to take effect.
# Source: https://www.quora.com/Why-wont-Python-work-in-PowerShell-for-me

### aws ###
[System.Environment]::SetEnvironmentVariable("PATH", $Env:Path + “;C:\Users\Administrator\AppData\Local\Programs\Python\Python36\Lib\site-packages\awscli", "Machine")

### python ###
[System.Environment]::SetEnvironmentVariable("PATH", $Env:Path + ";C:\Users\Administrator\AppData\Local\Programs\Python\Python36", "Machine")

### pip ###
[System.Environment]::SetEnvironmentVariable("PATH", $Env:Path + “;C:\Users\Administrator\AppData\Local\Programs\Python\Python36\Scripts", "Machine")
</powershell>

当我们手动运行脚本并确保重新启动powershell控制台时,代码完全正常。请注意,路径不一定需要存在才能设置。

但是,当通过EC2初始化实例时系统地运行代码不起作用。添加Restart-Computer作为尝试重新启动我假设在后台运行的PowerShell控制台不起作用。

其他来源:

2 个答案:

答案 0 :(得分:0)

PowerShell不是在Windows上运行的服务,但它确实具有对WinRM的服务依赖性和WMI的组件依赖性。 PowerShell是一组.exe,您必须专门启动才能执行任何操作。

  1. powershell_ise.exe,用于通过此UI进行脚本编写工作(仅限Windows)
  2. powershell.exe(仅限Windows)
  3. pwsh.exe(PowerShell Core,Win,OSX,Linux)
  4. 如果您在启动时尝试执行.ps1,请使用启动脚本,是否使用GPO。那是使用PowerShell作业或PowerShell登录脚本。

    # Use PowerShell to Create Job that Runs at Startup
    # 
    # Beginning with Windows PowerShell 3.0, with Windows PowerShell scheduled jobs, it is possible to natively and easily create a Windows PowerShell startup script (and one that does not rely on Group Policy).
    # 
    # A few steps are required to create a Windows PowerShell script that runs at startup as a Windows PowerShell scheduled job:
    # 1. Open the Windows PowerShell console with admin rights.
    # 2. Create a new job trigger and specify the type as a startup trigger.
    # 3. Specify a short random interval for the startup trigger to prevent race conditions at startup.
    # 4. Create the new scheduled job and specify the job trigger and the full path to the startup script.
    # 
    # 
    # https://blogs.technet.microsoft.com/heyscriptingguy/2014/05/14/use-powershell-to-create-job-that-runs-at-startup
    
    # Use Startup, Shutdown, Logon, and Logoff Scripts
    # You can use Windows PowerShell scripts, or author scripts in any other language supported by the client computer.
    # https://technet.microsoft.com/en-us/library/cc753404(v=ws.11).aspx
    

答案 1 :(得分:0)

powershell.exe。\ foo.ps1

确保指定脚本的完整路径,并确保已将执行策略级别设置为至少“RemoteSigned”,以便可以运行未签名的本地脚本。