Calling Script Remotely Does Not Work - powershell

I can run this script perfectly on my SharePoint server, and the user's profile picture gets updated:
[Reflection.Assembly]::LoadWithPartialName("Microsoft.SharePoint")
[Reflection.Assembly]::LoadWithPartialName("Microsoft.Office.Server")
$siteurl = "http://SHAREPOINTSITE/"
try {
$site = New-Object Microsoft.SharePoint.SPSite($siteurl)
} catch {
New-Item -ItemType File -Path C:\Users\admin\Desktop -Name ERROR1.txt -Value $_.Exception.Message -Force
}
try {
$context = [Microsoft.Office.Server.ServerContext]::GetContext($site)
} catch {
New-Item -ItemType File -Path C:\Users\admin\Desktop -Name ERROR2.txt -Value $_.Exception.Message -Force
}
#This gets the User Profile Manager which is what we want to get hold of the users
$upm = New-Object Microsoft.Office.Server.UserProfiles.UserProfileManager($context)
$user = "DOMAIN\user.name"
#Put it in a loop for iterating for all users
if ($upm.UserExists($user)) {
try {
$profile = $upm.GetUserProfile($user)
$profile["PictureURL"].Value = "\\Sharepoint\C$\Users\admin\Desktop\1.jpg";
$profile.Commit();
} catch {
New-Item -ItemType File -Path C:\Users\admin\Desktop -Name ERROR3.txt -Value $_.Exception.Message -Force
}
}
New-Item -ItemType File -Path C:\Users\admin\Desktop -Name HELLO.txt -Force
$site.Dispose()
But when I run it from a remote PowerShell session, I am getting some weird errors:
ERROR1.txt
Exception calling ".ctor" with "1" argument(s): "The Web application at http://SHAREPOINTSITE/ could not be found. Verify that you have typed the URL correctly. If the URL should be serving existing content, the system administrator may need to add a new request URL mapping to the intended application."
ERROR2.txt
Multiple ambiguous overloads found for "GetContext" and the argument count: "1".
I have checked all of the possibilities here, but still seeing this issue.
This is how I call the above script from the remote machine:
$spfarm = "DOMAIN\admin.username"
$spfarmpw = ConvertTo-SecureString "password123" -AsPlainText -Force
$cred = New-Object -TypeName System.Management.Automation.PSCredential -ArgumentList $spfarm,$spfarmpw
$session = New-PSSession SharePoint -Authentication Default -Credential $cred
Invoke-Command -Session $session -FilePath "\\SharePoint\C$\Users\admin\Desktop\testremote.ps1"
I have tried calling this in a few different ways (e.g. hosting the script on my machine or hosting it on the SharePoint server, as well as using relative paths to call the script), but I always see these errors.
Can anyone please help me understand why this doesn't work when calling it from a remote PC? The script is clearly being called (HELLO.txt always gets created), but the SharePoint profile picture never gets updated - even though that script definitely should work.
Any help or guidance is much appreciated
nslookup
nslookup SHAREPOINTSITE
Output
Server: dc1.domain.co.uk
Address: xx.xx.x.xx
Name: sharepoint.domain.co.uk
Address: yy.yy.y.yy
Aliases: SHAREPOINTSITE.domain.co.uk
Where yy.yy.y.yy is the correct IP (it's the same address I see when executing ping SHAREPOINTSITE)

Try changing the Authentication method to CredSSP. This is required by the remote PowerShell so that it can pass the credentials on.

Related

PowerShell registry hive unload error

I have hit a problem I haven’t been able to solve despite trying quite hard.
Basically I have created a PowerShell script to alter\change values in the HKU hive for a specific user on a remote Windows 10 Amazon WorkSpace. The script loads the hive and makes the changes perfectly but I am getting an error when trying to unload the hive. I have tried various methods as suggested on different forums but to no avail. Here is the part of the script I’m having trouble with:
$WorkSpace = "blahComputerName"
$PSS = New-PSSession -ComputerName $WorkSpace
$UserAcc = "XXXXX"
$SID = (Get-ADUser -server MyDomain.com -Identity $UserAcc).SID.Value
Invoke-Command -Session $PSS -ArgumentList $SID, $UserAcc -ScriptBlock {
New-PSDrive -PSProvider Registry -Name HKU -Root HKEY_USERS
reg load "HKU\$($args[0])" "D:\Users\$($args[1])\NTUser.Dat"
Clear-ItemProperty -Path
"HKU:\$($args[0])\SOFTWARE\Microsoft\Office\Common\UserInfo" -Name
"UserInitials"
[gc]::collect()
Start-Sleep -Seconds 5
reg unload "HKU\$($args[0])"
Remove-PSDrive -Name HKU
}
Remove-PSSession -Id $PSS.Id
I have also read that using $SomeThing.Handle.Close() will close any open handles PowerShell might still have with the provider which might be causing the error but I can’t see how to use it in this context.
Here is the exact error:
ERROR: Access is denied.
+ CategoryInfo : NotSpecified: (ERROR: Access is denied.:String) [], RemoteException
+ FullyQualifiedErrorId : NativeCommandError
+ PSComputerName : blahComputerName
I have manually observed the remote registry hive being loaded and then apparently unloaded but this error worries me and would like to solve it. I have proved that its reg unload "HKU\$($args[0])" that is causing the error but cant find the correct solution.
The script runs with the required elevated privileges, so it’s not that. The remote WorkSpace is in a logged off state.
Any advice would be greatly appreciated.
Thank You
Though Garbage collection is nice, the problem stems from how this command is handled;
Clear-ItemProperty -Path
"HKU:\$($args[0])\SOFTWARE\Microsoft\Office\Common\UserInfo" -Name
"UserInitials"
I would recommend capturing it in a variable, like so;
$n = Clear-ItemProperty -Path "HKU:\$($args[0])\SOFTWARE\Microsoft\Office\Common\UserInfo" -Name "UserInitials"
Which should allow you to properly clean it up, like so;
$n.dispose()
$n.close()
Note the above is likely redundant (Dispose should close, and close should call dispose).
With the help of other examples I figured it out. Here's what needs to be done:
$tempHive = 'HKLM\TEMP_hive'
$ntUserFile = 'C:\Users\SOME_USER\NTUSER.DAT'
# Load hive
$startParams = #{
FilePath = 'reg.exe'
ArgumentList = "load `"$tempHive`" `"$ntUserFile`""
WindowStyle = 'Hidden'
Wait = $true
PassThru = $true
}
$process = Start-Process #startParams
if ($process.ExitCode) {
throw "Failed to load the temp hive '$tempHive' for '$ntUserFile': exit code $($process.ExitCode)"
}
# make registry hive drive mapping if needed
# New-Psdrive -name <blah> -PSProvider Registry -root <blih>
# close open handles for 'New-Item'
$result = New-Item -Path "HKLM:\TEMP_hive\newkey"
$result.Handle.Close()
# no need to close open handles from 'New-ItemProperty'
# $null = New-ItemProperty #newParams
# wait for garbage clean up
[gc]::Collect()
[gc]::WaitForPendingFinalizers()
# if you did drive mapping with the mapped registry hive remove it before unload
# Remove-PSDrive <blah>
# unload the hive
$startParams = #{
FilePath = 'reg.exe'
ArgumentList = "unload `"$tempHive`""
WindowStyle = 'Hidden'
Wait = $true
PassThru = $true
}
$process = Start-Process #startParams
if ($process.ExitCode) {
throw "Failed to unload the temp hive '$tempHive' for '$ntUserFile': exit code $($process.ExitCode)"
}

Install program remotely using Invoke-Command

The variable at the top of the script defines several commands/variables for New-PSDrive, as well as connection and installation.
After this, a function is created to open a text file and extract information out of it. I know this part works because I use it in 2 other scripts.
Lastly, The script executes the commands in the first variable.
The script will show as running successfully, but checking the remote computer reveals that nothing happened.
Prior to doing any of this activity, the remote computer has a script run against it that:
enables PSRemoting (setting firewall rules and starting WinRM), and
bypasses execution policies.
After those steps, the script below is run to install a piece of software.
$eAudIT2014V2Install = {
$eAudIT2014V2password = ConvertTo-SecureString "PasswordHere" -AsPlainText -Force
$eAudIT2014V2cred = New-Object System.Management.Automation.PSCredential('domain\user', $eAudIT2014V2password)
$eAudIT2014V2drive = New-PSDrive -Name eAudIT2014V2 -PSProvider FileSystem -Root "\\Server\Share" -Credential $eAudIT2014V2cred
$eAudIT2014V2job = Start-Job {"eAudIT2014V2:\Setup.cmd"}
Wait-Job $eAudIT2014V2job
Receive-Job $eAudIT2014V2job
}
Function Get-OpenFile($initialDirectory) {
[System.Reflection.Assembly]::LoadWithPartialName("System.windows.forms") |
Out-Null
$OpenFileDialog = New-Object System.Windows.Forms.OpenFileDialog
$OpenFileDialog.InitialDirectory = $initialDirectory
$OpenFileDialog.ShowDialog()
$OpenFileDialog.Filename
$OpenFileDialog.ShowHelp = $true
}
$InputFile = Get-OpenFile
if ($InputFile -eq "Cancel") {
Write-Host "Canceled By User"
exit
} else {
$Computers = #(Get-Content -Path $InputFile)
}
foreach ($computer in $computers) {
Write-Host "Installing eAudIT 2014V2 on Selected Computers"
Invoke-Command $eAudIT2014V2Install
}
I'm noticing that if I tell this script to run something basic like notepad.exe, a dllhost process starts on the machine, but notepad never does. What am I doing wrong?
The answer is pretty simple here. All of your script is for naught if you don't tell the Invoke-Command cmdlet what computer you want to execute the code on. As it is you are simply iterating a loop and invoking that command X number of times on the local machine. You need to change that second to the last line to specify the machine to execute the code on:
Invoke-Command $eAudIT2014V2Install -ComputerName $computer

new-item Host-Instance - BizTalk Powershell Extensions

I'm trying to use the Powershell Extensions to BizTalk 2010 to add a Host-Instance (the host already exists).
Add-PSSnapIn -Name BiztalkFactory.PowerShell.Extensions #NOTE: Must be in 32-bit version of Powershellto use this SnapIn
#get-PsSnapIn -registered ### list registered Snap-In's
$HostName = "TestNewHost"
$HostType = 1 # 1 = InProcess
$myNTHostGroupName = "BIZTALKDEV\Domain Users"
$AuthTrusted = $false
$domainName = "BizTalkDev"
$serverName = "BizTalkDev"
$defaultAdminUser = "Administrator"
$hostCredentials = $Host.ui.PromptForCredential("Logon Credentials","This account must have SQL Server permissions.", $domainName + "\" + $defaultAdminUser, "");
[String]$hostCredentialsPassword = [Runtime.InteropServices.Marshal]::PtrToStringAuto([Runtime.InteropServices.Marshal]::SecureStringToBSTR($hostCredentials.Password));
#cd "Biztalk:\Platform Settings\Hosts"
#New-Item $HostName -HostType:$HostType -NtGroupName:$NTGroupName -AuthTrusted:$AuthTruste
#New-Item -path $hostName -HostType:$HostType -NtGroupName:$NTGroupName -AuthTrusted:$AuthTrusted
cd "BizTalk:\Platform Settings\Host Instances"
dir
Write-Host "Try to add New HostInstance=$hostName"
New-Item $hostName -HostName $hostName -Credentials $hostCredentials -RunningServer $serverName
dir
When I supply a valid domain user/password in the credentials, I get this error:
New-Item : Instance of the WMI class is not found.
No instance was found with the specified key. This could be the result of the instance being deleted by another BizTalk Admin session.At E:\CreateHost_PSSnapIn.ps1:27
char:1
If I leave off the -Credentials argument. It prompts me on that new-item for user/pass, and same error occurs. If I provide a totally bogus userid/pass, I still get the same error.
I found this issue. I had the wrong value for $servername, should have been "BizTalk2010Dev". I didn't catch that domain name and server name were different (this is a VM that a co-worker created).
So in summary, the error, while very ambiguous, was referring to the existing HostName being missing. All Host-Instances must be associated with an existing Host.

How to test writing to a file share path using credential?

I have an array of Credential objects and I would like to test that these credentials have permissions to write a file to a file share.
I was going to do something like
$myPath = "\\path\to\my\share\test.txt"
foreach ($cred in $credentialList)
{
"Testing" | Out-File -FilePath $myPath -Credential $cred
}
but then I discovered that Out-File doesn't take Credential as a parameter. What's the best way to solve this?
You can use New-PSDrive:
$myPath = "\\path\to\my\share"
foreach ($cred in $credentialList)
{
New-PSDrive Test -PSProvider FileSystem -Root $myPath -Credential $Cred
"Testing" | Out-File -FilePath Test:\test.txt
Remove-PSDrive Test
}
Here is asituation where an old exe (net.exe) seems to do better than powershell...
I guess you could try to map a network drive with the credential provided then test to write a file to that drive :
$cred=get-credential
$pass=$cred.GetNetworkCredential().Password
net use q: \\servername\share $pass /user:$cred.username
Use this script taken from Microsofts TechNet Script Center : http://gallery.technet.microsoft.com/scriptcenter/Lists-all-the-shared-5ebb395a
It is a lot easier to alter to fit your needs then to start completely from scratch.
Open up ListSharedFolderPermissions.ps1, and find the three $Properties vars. add a line at the top of each one so you can tell which user your looking at, so it should now look like this:
$Properties = #{'Username' = $Credential.UserName
'ComputerName' = $ComputerName
. . . . . }
Next, add your new Username property to the select-object line (3 times) :
$Objs|Select-Object Username,ComputerName,ConnectionStatus,SharedFolderName,SecurityPrincipal, `
FileSystemRights,AccessControlType
Once youve added those small pieces in the six appropriate places your script is ready to use:
cd c:\Path\where\you\put\ps1\file
$permissions = #()
$myPath = "computername"
foreach ($cred in $credentialList)
{
$permissions += .\ListAllSharedFolderPermission.ps1 -ComputerName $myPath -Credential $cred
$permissions += " "
}
$permissions | Export-Csv -Path "C:\Permission.csv" -NoTypeInformation
Try using the Invoke-Command function. It will take a credential object and allow you to run an arbitrary script block under that command. You can use that to test out writing the file
Invoke-Command -ScriptBlock { "Testing" | Out-File $myPath } -Credential $cred
I think the Invoke-command approach should work. But if nothing works you can try the powershell impersonation module. It successfully impersonates a user for most Powershell commands without the -Credential switch.
A few ideas:
Create your own PowerShell Provider
Impersonate a user and then write to the share (not sure if possible in powershell)
Use net use d:... as #Kayasax has suggested
Use WScript.Network
I'm very interested in the PowerShell provider myself, but I decided to make something real quick so I went with using the WScript.Network library. I used a hash table to track whether a user would be "authenticated" or not.
$credentials = #() # List of System.Net.NetworkCredential objects
$authLog = #{}
$mappedDrive = 'z:'
$tmpFile = $mappedDrive, '\', [guid]::NewGuid(), '.tmp' -join ''
$path = [io.path]::GetPathRoot('\\server\share\path')
$net = new-object -comObject WScript.Network
foreach ($c in $credentials) {
if ($authLog.ContainsKey($c.UserName)) {
# Skipping because we've already tested this user.
continue
}
try {
if (Test-Path $mappedDrive) {
$net.RemoveNetworkDrive($mappedDrive, 1) # 1 to force
}
# Attempt to map drive and write to it
$net.MapNetworkDrive($mappedDrive, $path, $false, $c.UserName, $c.Password)
out-file $tmpFile -inputObject 'test' -force
# Cleanup
Remove-Item $tmpFile -force
$net.RemoveNetworkDrive($mappedDrive, 1)
# Authenticated.
# We shouldn't have reached this if we failed to mount or write
$authLog.Add($c.UserName, 'Authorized')
}
catch [Exception] {
# Unathenticated
$authLog.Add($c.UserName, 'Unauthorized')
}
}
$authLog
# Output
Name Value
---- -----
desktop01\user01 Authorized
desktop01\user02 Unauthorized

Random string showing up in exported CSV

I have the powershell script built and I'm getting a "Random" bit of output into the CSV file. The string is MailboxExport(and a number). It looks like a value that (Get-MailboxExportRequest).name would return but I can't see where I would pull something like that or how it is being inserted. I think I may have just been staring at it too long and I may just need a fresh pair of eyes to spot my mistake. I would go into what the script is trying to do but I've put quite a few notes in the script that should explain it fairly well.
################################################## PST Extraction Script ##################################################
# Completed October 2013 by Trey Nuckolls
#
# This script is meant to extract PST files from the Site 1 Exchange server at the Site2 site and deliver those PST
# files to a share on the Site2 network. The script will change the input CSV file to keep track of which PSTfiles have been
# extracted and when that occoured. The script will also set security on the PST file so only the user and IT administraion
# can access the PST file.
#
# To run this script, enter the username of the Site 1 domain account that you want to target for extraction of a PST file then
# Run the script. Can be run from any machine on the network as long as it is run by someone with domain admin rights on the
# Site 2 network. Powershell v2 or v3 is required to run the script.
#
#############################################################################################################################
$InPstPath = '\\Site1_Server\PST_Store'
$OutPstPath = '\\Site2_Server\PST_Store'
$AdminPath = '\\Site2_Server\PST_Store\Admin\'
#Container for Site1 username
$User = Get-Content $AdminPath'login.txt'
#Container for encrypted Site1 Password
$PWord = Cat $AdminPath'pass.txt' | ConvertTo-SecureString
#Credential package for accessing Site1 resouces
$Credentials = New-Object –TypeName System.Management.Automation.PSCredential –ArgumentList $User, $PWord
#Creation of Powershell Drives for use during session
New-PSDrive -Name Site1Share -PSProvider FileSystem -Root $InPstPath -Credential $Credentials
New-PSDrive -Name Site2Share -PSProvider FileSystem -Root $OutPstPath
#Container for Powershell session to Exchange server
$PSSession = New-PSSession -ConfigurationName Microsoft.Exchange -ConnectionUri http://Site1_Server/powershell -Credential $Credentials
#Creation of Powershell session to Site1 Exchange server, including import of exchange commandlets
Import-PSSession $PSSession
#Import of the CSV file that lists users to be targeted
$In_List = Invoke-Command {Import-Csv "\\Site1_Server\PST_Store\To_Be_Exported.csv"} -computername Site1_Server -Credential $Credentials
$Processed = foreach ($objUser in $In_List) {
if ($objUser.Completed -ne "Yes") {
$TargetUser = $objUser.name
$ShortDate = (Get-Date).toshortdatestring()
$SourceFile = "Site1Share:\$TargetUser.pst"
$DestinationFile = "Site2Share:\$TargetUser.pst"
#Export Mailbox to PST File
New-MailboxExportRequest -Mailbox $TargetUser -Filepath $InPstPath\$TargetUser.pst
do {Start-Sleep -Seconds 10}
until((Get-MailboxExportRequest -Status InProgress).count -eq 0)
#Copy PST File to PST Share
Copy-Item -Path $SourceFile -Destination $DestinationFile
#Add Security access on PST file (Target_User-Modify). Domain Admin-Full is inherited from parent.
$Acl = Get-Acl $DestinationFile
$Permission = "Site2_Domain\$TargetUser","Modify","Allow"
$AccessRule = New-Object System.Security.AccessControl.FileSystemAccessRule $Permission
$Acl.SetAccessRule($AccessRule)
$Acl | Set-Acl $DestinationFile
#Remove PST file From Temporary area
Remove-Item -Path $SourceFile -Force
#Write back to checklist for new items that have just been processed
[PSCustomObject]#{Name=$TargetUser;Completed="Yes";Date=$ShortDate}
} else { if ($objUser.Completed -eq "Yes") {
#Passthrough of items that have already been completed
[PSCustomObject]#{Name=$objUser.name;Completed=$objUser.Completed;Date=$objUser.Date}}
}}
#Output the new version of the checklist
$Processed | export-csv -Path C:\TEMP\processed.csv
#Overwrite the old version checklist with the new one
Move-Item -Path C:\TEMP\processed.csv -Destination Site1Share:\To_Be_Exported.csv -force
#Cleanup PsDrives and PsSessions
Remove-PSDrive -Name Site1Share
Remove-PSDrive -Name Site2Share
Remove-PSSession -Session (Get-PSSession)
Input CSV is...
"Name","Completed","Date"
"User1","Yes","10/8/2013"
"User2","Yes","10/11/2013"
"User3",,
and output is...
"Name","Completed","Date"
"User1","Yes","10/8/2013"
"User2","Yes","10/11/2013"
"MailboxExport7",,
"User3","Yes","10/11/2013"
It is indeed very likely that the issue is caused by New-MailboxExportRequest, as you already suspected. The cmdlet prints information about the created object, which lumped together with the rest of the output you create in the loop, and then assigned to the variable $Processed.
To avoid this you can suppress the cmdlet output like this:
New-MailboxExportRequest -Mailbox ... | Out-Null
or like this:
New-MailboxExportRequest -Mailbox ... >$null
Assigning the output to a variable should work as well:
$exportRequest = New-MailboxExportRequest -Mailbox ...
On you Export-CSV, try adding the flag: "-NoTypeInformation"
I think this may be some sort of name space crossover issue between the custom object and another existing object (probably the mailboxexportrequest object on the exchange server). After messing around with this for a while I was able to get it to fail in a new way where the resultant csv file was full of details from the mailbox exports and their was a 'name' column that also had listed the usernames. I changed the hashes on the input csv from 'name to 'username' and the resultant MailboxExport entries have ceased. There are now blank row but I'm certainly willing to live with that imperfection as it doesn't break this (short lived) process.
If anyone has any insight into the root cause I'd certainly love to hear what it is but I think I've figured out a solution to the point that I can live with.