powershell的超级破烂的设置问题。

参见:http://technet.microsoft.com/en-us/library/ee176949.aspx  

微软开发了powershell,但是使用起来麻烦。因为缺省情况下不能双击执行PS1文件运行。这是由powershell的安全特性决定的。

使用assoc .ps1查看 ps1文件扩展名关联,得到.ps1=Microsoft.PowerShellScript.1

写一个ps1脚本sample.ps1,内容如下

write-host "hello,world"

保存后双击运行不了。双击启动记事本了。


解决办法

命令行窗口提示符下键入powershell

进入powershell提示符,然后

执行. /sample.ps1

得到错误提示:File C:\scripts\test.ps1 cannot be loaded because the execution of scripts is disabled on this system. Please see "get-help about_signing" for more details. At line:1 char:19 + c:\scripts\test.ps1 <<<<  

PS C:\Windows\system32> get-help about_signing
主题
    about_signing
简短说明
    说明如何对脚本进行签名以使其符合 Windows PowerShell 执行策略。
详细说明
    Restricted 执行策略不允许任何脚本运行。
    AllSigned 和 RemoteSigned 执行策略可防止 Windows PowerShell 运行没有数字签

名的脚本。 

 允许运行签名脚本
 -------------------------------
    首次在计算机上启动 Windows PowerShell 时,现用执行策略很可能是 Restricted(
默认设置)。
    Restricted 策略不允许任何脚本运行。
    若要了解计算机上的现用执行策略,请键入:
        get-executionpolicy
运行未签名脚本(REMOTESIGNED 执行策略)如果 Windows PowerShell 执行策略是
RemoteSigned,Windows PowerShell 不会运行从 Internet 下载的未签名脚本,包括您
通过电子邮

件和即时消息传递程序接收到的未签名脚本。 

解决办法,执行如下命令:set-executionpolicy remotesigned

 现在PS模式下输入./sample.ps1就可以执行脚本了。

如果要在run下执行ps1,可以如此:

Running Scripts from the Run Dialog 或者C:\vbs>powershell -noexit .\write.ps1

 如果你要在登录脚本中加入ps1脚本,必须这样调用。

Set objShell = CreateObject("Wscript.Shell")  

objShell.Run("powershell.exe -noexit c:\scripts\test.ps1")

总结:

1.检查执行策略 

2.在当前目录执行一个ps1,使用.\xxx.ps1方式

不指定完整路径的话,powershell会搜索PATH环境变量中的路径,即使是在当前路径当中。

3 如果要使用完整路径执行,并且路径中含有空格,就必须使用&符号,加上引号包含的全路径。例如:

& "C:\My Scripts\Test.ps1" 

原文地址:https://www.cnblogs.com/jjkv3/p/2529231.html