I am struggling to create a function to do this using New-PSession and importing list of computers from a text file. I think my confusion is in two areas :-
- Do I still need to use the Foreach construct, or will the PSession connection to eachj computer handle this part ?
- Parameters - some do not work (like $path) if declared outside of the PSSession - get unable to determine $path ?
Have reproduced what I have so far below. The first is running this as a script which works fine. The second is after trying to convert to a function - I cannot get how to do this…
- Non-function (works)
#######################################
##Check existence of WSP Share ##
######################################
Set-Location -Path D:\Updates $Computers = get-content ".\computers.txt" $s = New-PSSession -Computername $Computers $command = { ## Variables $path = "d:\WSP" $share = "WSP" ## Create Folder IF (!(test-path $path)){ write-host "Creating folder: " $path -ForegroundColor green New-Item -Path $path -ItemType directory } else { write-host "The folder already exists: "$path -ForegroundColor Yellow } ## Create Share IF (!(Get-SmbShare -Name $share -ErrorAction SilentlyContinue)) { write-host "Creating share: " $share -ForegroundColor green New-SmbShare –Name $share –Path $path –Description 'Test Shared Folder' –FullAccess Administrator -ChangeAccess Everyone } else { write-host "The share already exists: " $share -ForegroundColor Yellow } } Invoke-Command -Session $s -scriptblock $command
- Function (not working)
Function Check-Share { param($username = 'testdomain\spdevadmin', $password = 'DevSP13', $cred = (New-Object System.Management.Automation.PSCredential -ArgumentList @($username,(ConvertTo-SecureString -String $password -AsPlainText -Force))), $Computers = (get-content ".\computers.txt") ) $s = New-PSSession -Computername $Computers -Credential $cred $command = {param( $path = 'd:\wsp', $share = 'WSP' ) Foreach ($computer in $computers) { if (!(test-path $path)){ write-host "Creating folder: $path on computer : $computer" -ForegroundColor green New-Item -Path $path -ItemType directory } else { write-host "The folder already exists: "$path -ForegroundColor Yellow } } } Invoke-Command -Session $s -scriptblock $command } ## Create Share IF (!(Get-SmbShare -Name $share -ErrorAction SilentlyContinue)) { write-host "Creating share: " $share -ForegroundColor green New-SmbShare –Name $share –Path $path –Description 'Test Shared Folder' –FullAccess Administrator -ChangeAccess Everyone } else { write-host "The share already exists: " $share -ForegroundColor Yellow } } Invoke-Command -Session $s -scriptblock $command