0

我有一个自定义 PowerShell 脚本,它接受一些参数作为输入。

但是,其中一个参数属于在外部程序集中定义的类型。这意味着当我使用 PowerShell.exe 从命令行运行脚本时,程序集不会加载并且脚本会失败。

以下是脚本的相关部分:

[CmdLetBinding()]
param(
    [Parameter(Mandatory=$true, Position=0)]
    [Microsoft.SharePoint.PowerShell.SPWebPipeBind]$Web
)

# The SharePoint snapin will load 'Microsoft.SharePoint.PowerShell'
Add-PSSnapin Microsoft.SharePoint.PowerShell -EA 0
Write-Host "Let's dance"

以及我如何触发脚本(实际上来自 SharePoint 项目的部署后事件):

"%WINDIR%\SysNative\WindowsPowerShell\v1.0\powershell.exe" -file "c:\pathto\fixeditablefields.ps1" "http://myapp"

有没有办法告诉 PowerShell.exe 在运行脚本之前加载程序集?

[编辑]在使用 SharePoint 时,我坚持使用 PowerShell V2

4

2 回答 2

1

我会说,不。您可以做的一件事是使用 #Requires 语句在程序集不存在时阻止脚本运行:

#Requires -PSSnapin Microsoft.SharePoint.PowerShell

如果您无权访问脚本或无法以任何方式控制它,那么我建议更改参数的类型并在函数内添加验证。

于 2013-07-05T10:27:07.243 回答
0

好的,我设法使它起作用。

我使用以下命令启动我的脚本:

"%WINDIR%\SysNative\WindowsPowerShell\v1.0\powershell.exe" -command "& {Add-PSSnapin Microsoft.SharePoint.PowerShell -EA 0; & 'c:\pathto\fixeditablefields.ps1' -Web 'http://myapp'}"

基本上,我不是直接运行我的脚本文件,而是运行一个脚本块,它包含运行两个命令: ,它加载我丢失的程序集,然后使用构造Add-PSSnapin执行脚本。& c:\pathto\script.ps1

对于未来的读者,我的 PostDeployment 事件正是:

"%WINDIR%\SysNative\WindowsPowerShell\v1.0\powershell.exe" -command "& {Add-PSSnapin Microsoft.SharePoint.PowerShell -EA 0; & '$(SolutionDir)fixeditablefields.ps1' -Web '$(SharePointSiteUrl)'}"
于 2013-07-05T10:31:45.837 回答