Import-PSSession在脚本中失败,在shell中运行

Log*_*gan 5 powershell powershell-2.0 windows-server-2008-r2 exchange-server-2010

我是Powershell脚本的新手,我正在研究用户管理Powershell脚本,但我遇到了一个奇怪的错误.

以下代码在从shell运行时起作用,但在从脚本运行时不起作用:

$UserCredential = Get-Credential
$Session = New-PSSession -ConfigurationName Microsoft.Exchange -ConnectionURI http://servername/Powershell/ -Authentication Kerberos -Credential $UserCredential -AllowRedirection
Import-PSSession $Session
Run Code Online (Sandbox Code Playgroud)

当我Param()在第一行中带有块的脚本中运行它时,它失败并出现以下错误:

Import-PSSession: Cannot bind argument to parameter 'Path' becuase it is an empty string.
Run Code Online (Sandbox Code Playgroud)

Import-PSSession如果我删除我的Param()块,我可以得到工作,但我不知道如何接受我的脚本的命令行参数.如何保留Param()块(或更一般地,接受命令行参数)并仍然能够导入PS会话?

我在试图连接到2010 Exchange服务器的Windows 2008 R2服务器上使用Powershell v2.

更新:

我有一个脚本命名ManageUser.ps1,我从Powershell提示符运行,如

.\ManageUser.ps1 -disableUser -username someuser
Run Code Online (Sandbox Code Playgroud)

该脚本如下所示:

Param(
    [switch]$disableUser,
    [string]$username
)
$UserCredential = Get-Credential
$Session = New-PSSession -ConfigurationName Microsoft.Exchange -ConnectionURI http://servername/Powershell/ -Authentication Kerberos -Credential $UserCredential -AllowRedirection
Import-PSSession $Session
#more stuff past here...
Run Code Online (Sandbox Code Playgroud)

Import-PSSession命令失败了.但是,如果我删除整个Param(...),会话导入工作.我希望这足以让你理解它!

Hic*_*csy 3

您的脚本本身可以正常工作,并且从另一个脚本中调用时也可以正常工作:

& 'C:\Scripts\ManageUser.ps1' -disableUser -username "foo"
Get-Mailbox -resultsize 5 | ConvertTo-Csv -NoTypeInformation | Out-File C:\Scripts\mytest.csv
Run Code Online (Sandbox Code Playgroud)

由于没有-allowclobber@SamuelWarren 提到的那样,后续运行将收到导入错误/警告...

就您而言(至少在很久以前最初编写问题时),错误是由于您在此处未提及的另一个变量造成的。您很可能在第一次运行后修复了该问题,然后后续测试显示了AllowClobber 错误。

另外值得注意的是(对于将来遇到此问题的任何人)检查您正在调用的文件的路径。仅仅因为您尝试使用相对路径.\myfile.ps1并不意味着 PowerShell 当前正在查找正确的目录。

查看:$psscriptroot

或者Split-Path -Path $($global:MyInvocation.MyCommand.Path)