Author Posts

May 15, 2016 at 10:05 pm

Is there a way to write to HKU on a remote machine?
I want to map a remote drive but I don't think that I can pass New-PSDrive to New-PSSession (I understand that they have to log off\on for it to work). I

Import-Module ActiveDirectory

$RemoteComputer = Read-Host -Prompt "Enter the remote computers name"
[string]$RemoteUser = Read-Host -Prompt "Enter the remote UID"
[string]$UNC = Read-Host "Please enter the remote network Path (UNC)"
[string]$RemoteDrive = Read-Host -Prompt "Enter drive letter you would like on the remote computer"
$Sid = (Get-ADUser $RemoteUser).sid

$s = New-PSSession -ComputerName $RemoteComputer

	
Invoke-Command -Session $s -ScriptBlock {

	Write-Verbose "Create a new Registry Drive for HKU"
	New-PSDrive -PSProvider Registry -Name HKU -Root HKEY_USERS

	Write-Verbose "Create the top level RegKey"
	New-Item ("HKU:\" + $Sid + "\Network\") -Name $RemoteDrive -Force

	Write-Verbose "Create child registry values"
	New-ItemProperty ("HKU:\" + $Sid + "\Network\$RemoteDrive") -Name "ConnectionType" -Value 1 -PropertyType "DWord"
	New-ItemProperty ("HKU:\" + $Sid + "\Network\$RemoteDrive") -Name "DeferFlags" -Value 4 -PropertyType "DWord"
	New-ItemProperty ("HKU:\" + $Sid + "\Network\$RemoteDrive") -Name "ProviderName" -Value "Microsoft Windows Network" -PropertyType "String"
	New-ItemProperty ("HKU:\" + $Sid + "\Network\$RemoteDrive") -Name "ProviderType" -Value 20000 -PropertyType "DWord"
	New-ItemProperty ("HKU:\" + $Sid + "\Network\$RemoteDrive") -Name "RemotePath" -Value $UNC -PropertyType "String"
	New-ItemProperty ("HKU:\" + $Sid + "\Network\$RemoteDrive") -Name "UserName" -Value 0 -PropertyType "DWord"
}

Write-Verbose "Remove Session and Registry Drive"
Remove-PSSession $s
Remove-PSDrive HKU

I get error
Cannot find drive. A drive with the name 'HKU' does not exist.
+ CategoryInfo : ObjectNotFound: (HKU:String) [New-Item], DriveNotFoundException
+ FullyQualifiedErrorId : DriveNotFound,Microsoft.PowerShell.Commands.NewItemCommand
+ PSComputerName : $computername

May 16, 2016 at 4:11 am

The problem, I think, is variable scope. Your New-PSDrive command uses $RemoteDrive, which doesn't exist in the remote scope. It's a local variable. So New-PSDrive is likely failing. You need to pass $RemoteDrive and your other local variables into the scriptblock using the -Argument parameter of Invoke-Command (read the help file for how to do that correctly).

May 16, 2016 at 5:54 pm

Thanks Don!
I was looking at the wrong command by thinking it was a problem with New-PSdrive. I'll check the help on Invoke-Command now instead.

May 16, 2016 at 6:32 pm

Exactly what I was missing.
As I'm using PSv3 I could just call my variables like so "$using:RemoteDrive" and it is all good.

I was clearly banging my head against the wrong door when I was thinking the error related to New-PSDrive