Link to home
Start Free TrialLog in
Avatar of SquigglyMonkey
SquigglyMonkey

asked on

powershell scripting help

I have a script that works, but I am trying to make it re-usable.
I needed to create the same folder in the same path, on many servers, so I used powershell, and this works fine:

$Servers='server1','server2','server3'
$NewFolder = 'Software'
$Servers | foreach { New-Item "\\$($_)\D$\$NewFolder" -ItemType Dir }
So that worked fine, but the helpdesk guys do this routinely and like I said, I wanted it to be re-useable, so I wrote this:

$servers = Read-Host "Please enter system name in this format server1"
$newfolder = Read-Host "Please enter Folder name in this format FolderName"
$path = Read-host "Please enter the path where the new folder will be, in this format D$ (If the new folder is at the root
of the D:\drive. If the folder is to be inside another folder, then that path is needed,  such as D$\tier1\"
$Servers | foreach { New-Item "\\$($_)\$path\$NewFolder" -ItemType Dir }

This works fine, but only for one system, I tried putting them in with commas, with single quotes, it keeps using the entire line
 WriteError: (\\server1...erver2\D$\Data:String) [New-Item], IOException

So how what do I need to do for this to work?
Thanks!
Avatar of Brian Murphy
Brian Murphy
Flag of United States of America image

Quick way perhaps, use a servers.txt list

Pull from that or use a variable you can pass on the command line.

You could do a FOR IF but I cannot tell if you are trying to run this remote or they are on the actual server.

In that case, a variable should work like a command line for example:  myscript.ps1 Server1

But it looks more like what you need is an "array"
Avatar of SquigglyMonkey
SquigglyMonkey

ASKER

Okay, so I thought the same thing, and found a ton of stuff on arrays.
This asks for server names comma delimited, works great.

[array]$servers = (Read-Host "Please enter system name in this format server1 if more than 1 server, separate with a ,").split(“,”) | %{$_.trim()}
$newfolder = Read-Host "Please enter Folder name in this format FolderName"
$path = Read-host "Please enter the path where the new folder will be, in this format D$ (If the new folder is at the root of the D:\drive. If the folder is to be inside another folder, then that path is needed,  such as D$\tier1\"

$Servers | foreach { New-Item "\\$($_)\$path\$NewFolder" -ItemType Dir }
I've requested that this question be closed as follows:

Accepted answer: 0 points for SquigglyMonkey's comment #a41027904

for the following reason:

This is the solution to the question I asked.
ASKER CERTIFIED SOLUTION
Avatar of Jeremy Weisinger
Jeremy Weisinger

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Looks like you found split.