Solved

Setting variables and using them on a remote PC

Posted on 2013-12-30
11
286 Views
Last Modified: 2014-01-01
If I have an .xlsx file with columns labelled as follows 1 = first, 2 = second, 3 = third and data in say the first 10 rows of these 3 columns, I understand If
I save this file as a .csv I can call on each of these columns in a foreach-object loop like
Import-Csv "New.csv" | ForEach-Object {
Some-Cmdlet
-SomeParameter1 $_."first" `
-SomeParameter2 $_."second" `
-SomeParameter3 $_."third" `

If the .csv is on computer A and I want to execute the command on Computer B using a Invoke-Command is the simplest way to start the script
by copying the .csv to computer B and enclosing the whole Import-Csv and foreach-object part inside -Scriptblock

Thanks for your help in advance
0
Comment
Question by:Dead_Eyes
  • 6
  • 5
11 Comments
 
LVL 39

Expert Comment

by:footech
ID: 39747385
The answer could vary by what you're actually doing.  Unless you wanted to execute every row on target machine, copying the .CSV to it is probably not the best way (and even then an argument could be made against it).  You probably want to pass the variables as arguments like below.
Import-Csv "New.csv" | ForEach-Object {
    Invoke-Command -computername $_."first" -ScriptBlock { param ($arg2, $arg3) gci $arg2 -Include $arg3 } -ArgumentList $_."second", $_."third"
}

Open in new window

0
 

Author Comment

by:Dead_Eyes
ID: 39747533
I was thinking if I had a .csv file that in column 1 contained a list of folder names to be created using the new-object cmdlet and column 3 contained usernames to be assigned full control permission on the folder created.  I had the idea when I saw the following script someone was using to add AD users and thought the technique could be adapted :

Import-Csv "NewUsers.csv" | ForEach-Object {
    $userPrinc = $_."Logon Username" + "@pca.hq"
    New-QADUser -Name $_.Name `
        -ParentContainer $_."Container" `
        -SamAccountName $_."Logon Username" `
        -UserPassword "pass123!ForWhat" `
        -FirstName $_."First Name" `
        -LastName $_."Last Name" `
        -LogonScript "students.bat" `
        -Description $_."Graduating Year" `
        -UserPrincipalName $userPrinc `
        -DisplayName $_."Name" ;`
    Add-QADGroupMember -identity $_."Graduating Year" -Member $_."Logon Username" ;`
    Set-QADUser -identity $_."Logon Username" `
        -UserMustChangePassword $true `

attached it the xlsx that the above script was using (converted to a .csv before use). Hope this helps and thanks for all your help so far
New-Users-Returned.xlsx
0
 
LVL 39

Expert Comment

by:footech
ID: 39747590
I would probably do something a bit more like the below.  Sorry, but I'm not doing the permissions bit because it takes a bit too much time to put together and I don't have anything ready to drop in.  Setting permissions exclusively through PowerShell is cumbersome, so I shy away from it.  Usually I recommend using icacls as it's easy enough to use within PS passing it variables for the path and identity you wish to set.  You'd have to play around with the syntax to get what you need.
$scriptblock = {
    param ($arg2, $arg3)
    new-item -itemtype directory -path $arg2
    #set permissions with $arg3
    #icacls $arg2 /grant $arg3:F /T   #might work
}
$s = New-PsSession -computername server1
Import-Csv "New.csv" | ForEach-Object {
    Invoke-Command -session $s -ScriptBlock $scriptblock -ArgumentList $_."second", $_."third"
}

Open in new window

0
 

Author Comment

by:Dead_Eyes
ID: 39747651
I can see the logic in it and will give it a go and see how far I get (I will have to read up on param and -ArgumentList as I have not used those before). I will increase the points if I get it going and if necessary post another question to get icacls working (I know permissions are horrible in powershell). Thanks again for your help and I will try and back to you asap
0
 
LVL 39

Expert Comment

by:footech
ID: 39747697
RE:  param and -ArgumentList
Think of the scriptblock like a completely separate script (.PS1 file) or a function.  For example you might run
somefunction c:\temp
#or
somefunction $mypath

If you need to pass information into the script or function when calling it, you have to define the variables which will receive that information.  You define those variables within param().

Argumentlist is just where you specify what information is to be passed to the scriptblock.  You can use variables here or not.  If using variables, the variable names specified by ArgumentList don't have to match up with the names of the variables in param().  So for a given scriptblock
$scriptblock = {
    param ($someArg)
    write-output $someArg
}

Open in new window

the following invoke-commands are all equivalent
$someArg = "c:\temp"
invoke-command -computername server1 -scriptblock $scriptblock -argumentlist $someArg

Open in new window

$cheeseburger = "c:\temp"
invoke-command -computername server1 -scriptblock $scriptblock -argumentlist $cheeseburger

Open in new window

invoke-command -computername server1 -scriptblock $scriptblock -argumentlist "c:\temp"

Open in new window

When passing multiple arguments, they are matched to the variables specified in param() in order - first, second, third...
0
How your wiki can always stay up-to-date

Quip doubles as a “living” wiki and a project management tool that evolves with your organization. As you finish projects in Quip, the work remains, easily accessible to all team members, new and old.
- Increase transparency
- Onboard new hires faster
- Access from mobile/offline

 

Author Comment

by:Dead_Eyes
ID: 39747746
Thanks that helped loads, I will have to try a few experiments to make sure I fully understand but great examples. you will be pleased to know your script worked apart from the permissions which threw the following error. I will see if I can figure it out but any suggestions are more than welcome

    Directory: D:\users


Mode                LastWriteTime     Length Name                                                         PSComputerName                                              
----                -------------     ------ ----                                                         --------------                                              
d----        31/12/2013     08:21            testuserfolder1                                              win2k12r2srv                                                
Invalid parameter "/grant"
    + CategoryInfo          : NotSpecified: (Invalid parameter "/grant":String) [], RemoteException
    + FullyQualifiedErrorId : NativeCommandError
    + PSComputerName        : win2k12r2srv
 
d----        31/12/2013     08:21            testuserfolder2                                              win2k12r2srv                                                
Invalid parameter "/grant"
    + CategoryInfo          : NotSpecified: (Invalid parameter "/grant":String) [], RemoteException
    + FullyQualifiedErrorId : NativeCommandError
    + PSComputerName        : win2k12r2srv
0
 

Author Comment

by:Dead_Eyes
ID: 39747754
Sorry should have included the line:
icacls $arg2 /grant $arg3:F /T
0
 
LVL 39

Accepted Solution

by:
footech earned 500 total points
ID: 39748568
Try this.
icacls $arg2 /grant "$($arg3):(OI)(CI)F"
0
 

Author Comment

by:Dead_Eyes
ID: 39748609
Perfect thanks, just got to figure the net share part now but I post a new question if I get stuck. Thanks for all your help I have learned a lot and a lot to learn
0
 

Author Comment

by:Dead_Eyes
ID: 39749872
I've requested that this question be closed as follows:

Accepted answer: 0 points for Dead_Eyes's comment #a39748609

for the following reason:

Great explanations and examples
0
 
LVL 39

Expert Comment

by:footech
ID: 39748682
I think you meant to accept another post as the answer instead of http:#a39748609.  :)
0

Featured Post

Highfive + Dolby Voice = No More Audio Complaints!

Poor audio quality is one of the top reasons people don’t use video conferencing. Get the crispest, clearest audio powered by Dolby Voice in every meeting. Highfive and Dolby Voice deliver the best video conferencing and audio experience for every meeting and every room.

Join & Write a Comment

Why would I want to create a function for tracking messages? I am glad you asked. As with most monotonous/routine tasks, human error tends to creep in after doing the same task over and over again. By creating a function, you load the function once…
Microsoft Windows Server Update Service (WSUS) is free for everyone, but it lacks of some desirable features like send an e-mail to the administrator with the status of all computers on the WSUS server. This article is based on my PowerShell script …
Internet Business Fax to Email Made Easy - With eFax Corporate (http://www.enterprise.efax.com), you'll receive a dedicated online fax number, which is used the same way as a typical analog fax number. You'll receive secure faxes in your email, fr…
In this seventh video of the Xpdf series, we discuss and demonstrate the PDFfonts utility, which lists all the fonts used in a PDF file. It does this via a command line interface, making it suitable for use in programs, scripts, batch files — any pl…

746 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

12 Experts available now in Live!

Get 1:1 Help Now