A customer asked me the other day of creating a DFSN folder from a remote PowerShell session, but they were faced with the issue

Access to a CIM resource was not available to the client.
+ CategoryInfo          : PermissionDenied: (MSFT_DfsNamespaceFolder:Root\Microsoft\…NamespaceFolder) [New-DfsnFolder
], CimException
+ FullyQualifiedErrorId : MI RESULT 2,New-DfsnFolder
+ PSComputerName        : COMPUTERNAME

Basically this is due to the permissions problem, cause the invoke-command is not possible to run elevated.

Solution? It could possibly be solved with delegating permission in the WMI namespace, I did not manage this and didn’t have time to troubleshoot any deeper. Another way to solve this is to install the DFS management tools on the remote machine, in this case this was not possible.

So I choose the path of creating a scheduled task on the remote machine

This code did not work

$session = New-PSSession -ComputerName “Server1” -ThrottleLimit 4
Invoke-Command -Command {
New-DfsnFolder -Path “\\subdomain.domain.local\Public\Test” -TargetPath \\Server1\Test
} -Session $session

This is what I ended up with, comments in-line

$session = New-PSSession -ComputerName “Server1” -ThrottleLimit 4
Invoke-Command -Command {#Create the scheduled task, note the –RunLevel Highest, to make sure the command is run eleveted
$stAction = New-ScheduledTaskAction -Execute “PowerShell.exe” -Argument “-Command `”& { New-DfsnFolder -Path `”\\subdomain.domain.local\Public\Test`” -TargetPath `”\\Server1\Test`”; }`””
$task = Register-ScheduledTask -TaskName “Create DFSN folder” -Action $stAction -User “Domain\DFSAdmin” -Password “ComplexPassword” -RunLevel Highest –Force
# Start the scheduled task
Start-ScheduledTask -InputObject $task
# Wait for the task to be ready
sleep -Seconds 10
$task = Get-ScheduledTask -TaskPath $task.TaskPath -TaskName $task.TaskName
while ($task.State -ne “Ready”)
{
Write-Host “Waiting”
sleep -Seconds 5
$task = Get-ScheduledTask -TaskPath $task.TaskPath -TaskName $task.TaskName
}
Write-Host “Ready to delete the Scheduled Task”
$taskInfo = Get-ScheduledTaskInfo -InputObject $task
Write-Host “Status from the task. LastRunTime: $($taskInfo.LastRuntime) LastTaskResult: $($taskInfo.LastTaskResult)”
# Remove the scheduled task
Unregister-ScheduledTask -InputObject $task -Confirm:$false

} -Session $session

Now it runs successfully!

Advertisements