Author Posts

March 2, 2014 at 9:04 pm

I need to generate a function script that creates a folder using a username passed to it through a parameter. Also it can't make duplicates by making one that already exists, because that would make it a lot harder for me. I then want it to generate a txt called TextFile.txt and save it to the folder being created. Next it has to write the file with first and last name as well as some basic contact information, such as phone number, city, state, zip. Any help would be appreciated.

March 3, 2014 at 4:22 am

There are functions, and there are scripts. I'm not sure what you mean by a "function script." The rest of it is pretty straightforward, but there are a couple details left out:

  • What should the script do if the folder already exists? Generate a unique folder name? Create the TextFile.txt file in the existing folder? Do nothing?
  • Where is the script getting all of that additional contact information for the text file? Is that being passed to it as a parameter as well, or should it be querying Active Directory, or something along those lines?

March 3, 2014 at 4:35 am

Sorry for it being confusing, I need a script.
1. I need it to send something along the lines of an error message saying that the name already exists.
2. The user should be able to input the the additional contact information by typing it in.It doesn't have to be super fancy. It should be passed to it as a parameter.

March 3, 2014 at 5:05 am

OK, something along these lines should get you started:

param (
    $Path = '.',

    [Parameter(Mandatory = $true)]

    [Parameter(Mandatory = $true)]

    [Parameter(Mandatory = $true)]

    [Parameter(Mandatory = $true)]

    [Parameter(Mandatory = $true)]

    [Parameter(Mandatory = $true)]

    [Parameter(Mandatory = $true)]

$targetFolder = Join-Path -Path $Path -ChildPath $UserName

if (Test-Path -LiteralPath $targetFolder)
    throw "'$targetFolder' already exists."

$null = New-Item -Path $targetFolder -ItemType Directory -ErrorAction Stop

$text = @"
Name: $FirstName $LastName
Phone: $PhoneNumber
City: $City
State: $State
Zip: $Zip

$fileName = Join-Path -Path $targetFolder -ChildPath 'TextFile.txt'

$text | Out-File -LiteralPath $fileName -ErrorAction Stop

I made all of the contact information parameters mandatory, but you can change that if you'd like. Calling the script would look something like this:

.\ScriptName.ps1 -Path $home\Documents\ContactInfo -UserName SomeUser -FirstName Dave -LastName Wyatt -PhoneNumber 555-555-5555 -City Nowhere -State Michigan -Zip 12345

March 3, 2014 at 6:58 am

Thank you very much. This works perfectly.