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.
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?
Sorry for it being confusing, I need a script.
- I need it to send something along the lines of an error message saying that the name already exists.
- 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.
OK, something along these lines should get you started:
[CmdletBinding()] param ( [string] $Path = '.', [Parameter(Mandatory = $true)] [string] $UserName, [Parameter(Mandatory = $true)] [string] $FirstName, [Parameter(Mandatory = $true)] [string] $LastName, [Parameter(Mandatory = $true)] [string] $PhoneNumber, [Parameter(Mandatory = $true)] [string] $City, [Parameter(Mandatory = $true)] [string] $State, [Parameter(Mandatory = $true)] [string] $Zip ) $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
Thank you very much. This works perfectly.