Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Import-PSSession fails in script, works in shell

I'm new to Powershell scripting and I'm working on a user management Powershell script, but I have run into a strange error.

The following code works when I run it from the shell, but not when it is run from a script:

$UserCredential = Get-Credential
$Session = New-PSSession -ConfigurationName Microsoft.Exchange -ConnectionURI http://servername/Powershell/ -Authentication Kerberos -Credential $UserCredential -AllowRedirection
Import-PSSession $Session

When I run it in a script with a Param() block on the first line, it fails with the following error:

Import-PSSession: Cannot bind argument to parameter 'Path' becuase it is an empty string.

I can get the Import-PSSession to work if I remove my Param() block, but I'm not sure how to accept command-line arguments for my script otherwise. How can I keep the Param() block (or more generally, accept command-line arguments) and still be able to import the PS session?

I'm using Powershell v2 on a Windows 2008 R2 server trying to connect to a 2010 Exchange server.

Update:

I have a script named ManageUser.ps1 that I run from a Powershell prompt like

.\ManageUser.ps1 -disableUser -username someuser

The script starts like this:

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...

It is failing on the Import-PSSession command. But, if I remove the whole Param(...), the session import works. I hope this is enough for you to understand it!

like image 597
Logan Avatar asked Oct 18 '22 21:10

Logan


1 Answers

Your script works fine on it's own and also when called from within another script:

& 'C:\Scripts\ManageUser.ps1' -disableUser -username "foo"
Get-Mailbox -resultsize 5 | ConvertTo-Csv -NoTypeInformation | Out-File C:\Scripts\mytest.csv

Subsequent runs will get the import error/warning due to not having -allowclobber as mentioned by @SamuelWarren...

In your case (at least when initially writing the question long ago) the error was due to another variable that you haven't mentioned here. It's likely you fixed that after the first run, and then subsequent tests were showing the AllowClobber error.

Also worth noting (for anybody who comes across this in the future) to check the path of the file you are calling. Just because you try to use a relative path .\myfile.ps1 doesn't mean that PowerShell is currently looking in the right directory.

Check: $psscriptroot

Or Split-Path -Path $($global:MyInvocation.MyCommand.Path)

like image 151
Hicsy Avatar answered Nov 01 '22 16:11

Hicsy