Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pass argument into Powershell

I have a powershell script that completes some tasks in Active Directory and MS Exchange. I need to pass in the Active Directory username from our call logging system. Having the Call log system pass the argument is simple.

The problem i am facing is having powershell read the argument into a variable.

I will provide a proof of concept example.

Here is a sample command passing the argument into powershell.

C:\Users\UserName\Desktop\Test.ps1 -ADusername "Hello World"

Here is the sample script:

Param([string]$adusername)
$adusername
pause

I am Expecting the following output:

Hello World
Press Enter to continue...:

This is the actual output:

Press Enter to continue...:

Just wrapping my head around this core concept will help me immensely. I was unable to find any examples or tutorials that worked when applied to my scenario. I apologize if this is a duplicate post, couldnt find anything on this site as well.

EDIT: per request, this is my full script: http://pastebin.com/ktjpLQek

like image 532
mttp1990 Avatar asked Dec 19 '22 17:12

mttp1990


1 Answers

I think you will have much better luck if you avoid trying to use params and call the script exactly that way.

It is possible, but paramaters work better if you either inline the scriptfile like:

. .\scriptFile.ps1
function "Hello World"

Staying closer to what you are doing however, you should be using $args and calling PowerShell (the exe directly)

If you call your scriptfile like: (I used the runbox)

powershell c:\Path\Folder\Script.ps1 "Hello World!"

and then replace your Param([string]$adusername) with:

$adUserName = $args[0]
write-host $adUserName

Additionally, this should work for you (to dissect):

Param([string]$ad)

Write-Host $args[0]
Write-Host $ad

Read-Host
pause

Call the script with the path, powershell c:\Path\Folder\Script.ps1 "Hello World!" $ad = "JSmith"

If this does not work, you should ensure that your execution policy is set correctly. Get-ExecutionPolicy will tell you the current level. For testing you can set it very low with Set-ExecutionPolicy unrestricted

like image 132
Austin T French Avatar answered Dec 28 '22 04:12

Austin T French