Insert Sharepoint Credentials using Powershell - powershell

When trying to open or sometimes close, via powershell, a word document in a sharepoint directory hosted in my company's network, the windows security box popup.
How can I authenticate this ? Here is part of my script:
$docpath = "\\sharepoint.[Domain].com\[...]\mydoc.docx"
$word = New-Object -ComObject Word.Application
$word.Visible = $true
$doc = $word.Documents.Open("$docpath")
{...process...}
$doc.Close([ref]$true)
$word.Quit()
$word = $null
[gc]::collect()
[gc]::WaitForPendingFinalizers()
Here is a visual example of what happens.

I´ve found something that works, but only if if have an admin user. Still would like to know if there is a way to do this without this kind of permission.
Here is the code:
$User = "domain\useradmin"
$Cred = Get-Credential -Credential $User
$srv = "sharepoint.[Domain].com"
Invoke-Command -ComputerName $srv -Credential $Cred -ScriptBlock{
$docpath = "\\sharepoint.[Domain].com\[...]\mydoc.docx"
$word = New-Object -ComObject Word.Application
$word.Visible = $true
$doc = $word.Documents.Open("$docpath")
{...process...}
$doc.Close([ref]$true)
$word.Quit()
$word = $null
}

Related

How to run Command as a different user with Powershell?

I'm trying to make a script that changes the HostnameAlias for a given dns record.
But only certain users have access to editing these records, for example ADMIN can edit it but CURRENTUSER cannot.
Currently I have this piece of code:
param(
[ValidateNotNull()]
[System.Management.Automation.PSCredential]
$Credential = $(Get-Credential)
)
$Command = "Set-DnsServerResourceRecord -NewInputObject $($NewObject) -OldInputObject $($OldObject) -ZoneName $($ZoneName)"
Start-Process -FilePath PowerShell -NoNewWindow -Credential $Credential -ArgumentList $Command
But i just keep getting Start-Process : This command cannot be run due to the error: The user name or password is incorrect even though I am absolutely sure they are indeed correct.
What am I doing wrong here.
Ps, I have looked at all the related questions, none seem to answer my question.
You can call System.Management.Automation.PSCredential object to specify any credentials you want and run with it in any process
$User = 'yourdomain\youruser'
$Password = 'yourpassword'
$Secure_Password = ConvertTo-SecureString $Password -AsPlainText -Force
$Credential = New-Object System.Management.Automation.PSCredential($User, $Secure_Password)
$Command = "Set-DnsServerResourceRecord -NewInputObject $($NewObject) -OldInputObject $($OldObject) -ZoneName $($ZoneName)"
Start-Process -FilePath PowerShell -NoNewWindow -Credential $Credential -ArgumentList $Command
You can use this:
#Get User credential
$Credential = Get-Credential Domain\UserNameYouWant
#Use System.Diagnostics to start the process as User
$ProcessInfo = New-Object System.Diagnostics.ProcessStartInfo
#With FileName we're basically telling powershell to run another powershell process
$ProcessInfo.FileName = "powershell.exe"
#CreateNoWindow helps avoiding a second window to appear whilst the process runs
$ProcessInfo.CreateNoWindow = $true
#Note the line below contains the Working Directory where the script will start from
$ProcessInfo.WorkingDirectory = $env:windir
$ProcessInfo.RedirectStandardError = $true
$ProcessInfo.RedirectStandardOutput = $true
$ProcessInfo.UseShellExecute = $false
#The line below is basically the command you want to run and it's passed as text, as an argument
$ProcessInfo.Arguments = "The command you want"
#The next 3 lines are the credential for User as you can see, we can't just pass $Credential
$ProcessInfo.Username = $Credential.GetNetworkCredential().username
$ProcessInfo.Domain = $Credential.GetNetworkCredential().Domain
$ProcessInfo.Password = $Credential.Password
#Finally start the process and wait for it to finish
$Process = New-Object System.Diagnostics.Process
$Process.StartInfo = $ProcessInfo
$Process.Start() | Out-Null
$Process.WaitForExit()
#Grab the output
$GetProcessResult = $Process.StandardOutput.ReadToEnd()
# Print the Job results
$GetProcessResult
Just a mistake on my part, forgot to specify domain before username when entering credentials.
Can solve it like this Get-Credential Domain\

Run code as different user to have elevated privileges

I'm deploying a monitoring system, and even though it has a large number of plugins, some need to run as a different user to run right.
So I switched to powershell, but the problem is the same, I have some code that give me access denied, because the user has no elevated privileges.
My question how can I run this code as different user, I tried this
$usuario = "myuser#mydomain"
$pass = get-content C:\credential.txt`
$spass = $pass | Convertto-SecureString`
pass = "securepass"`
spass = $pass | ConvertTo-SecureString -AsPlainText -Force`
write-host $pass
$cred = new-object System.Management.Automation.PSCredential -argumentlist $usuario, $spass
$UpdateSession = New-Object -ComObject Microsoft.Update.Session
$UpdateSearcher = ($UpdateSession.CreateupdateSearcher())
$Updates = $UpdateSearcher.Search("IsAssigned=1 and IsHidden=0 and IsInstalled=0").updates
$total = $Updates | measure
$total.count
Then how can I pass the credentials to the variables. The problem access denied come from this line
$Updates = $UpdateSearcher.Search("IsAssigned=1 and IsHidden=0").updates
$args = ' -file path-to-script.ps1'
Start-Process -FilePath powershell.exe -Credential $creds -ArgumentList $args -Verb RunAs
Powershell also has -Command which you can use to call a function or cmdlet instead of another script.

Powershell start IE in private and log in to page

I'm trying to automate a process of activating accounts by logging in to email, I have it working when I am not on the business network with the following code.
$username = "user"
$password = "pass"
$url = "url"
$ie = New-Object -com InternetExplorer.Application
$ie.visible=$true
$ie.navigate($url)
while ($ie.Busy -eq $true){Start-Sleep -seconds 1;}
$usernamefield = $ie.Document.getElementByID('UsernameTextBox')
$usernamefield.value = $username
$passwordfield = $ie.Document.getElementByID('PasswordTextBox')
$passwordfield.value = $password
$ie.document.getElementById("ctl00_ContentPlaceHolder1_SubmitButton").click()`
My issue is that once connected to the business network it then uses SSO to log in so I do not get the option to put in a username and password. To be able to put in a username and password I need to start IE in private mode. I have been able to start IE in private with the start-process command but I cannot find a way to select the window to type in the username and password.
Is there a way I can use powershell to log in to the website in a private browser?
You can get a handle to the private IE by starting it with start-process, as you referred to.
Start-Process -FilePath "C:\Program Files (x86)\Internet Explorer\iexplore.exe" -ArgumentList ' -private http://bogus.bogus'
Then you can connect to it by finding it -
$Shell = New-Object -Com Shell.Application
$apps = $shell.windows()
$ie = $apps | where { $_.locationname -eq 'http://bogus.bogus/' }
Happy scripting. :)

Create a user in MongoDb using powershell

I'm using MongoDb v3.0.3 and want to create a user in a database with admin privileges using powershell. I hook into the C# driver but I don't get very far:
$pathToMongoDbCSharpDriver = "F:\Work\...\mongocsharpdriver.1.9.2\lib\net35"
Add-Type -Path "$pathToMongoDbCSharpDriver\MongoDB.Bson.dll"
Add-Type -Path "$pathToMongoDbCSharpDriver\MongoDB.Driver.dll"
$client = New-Object -TypeName MongoDB.Driver.MongoClient -ArgumentList "mongodb://localhost:30000"
$server = $client.GetServer()
$databaseName = "Dev"
$collectionName = "Settings"
$database = $server.GetDatabase($databaseName)
$collection = $database.GetCollection($collectionName)
$credentials = New-Object -TypeName MongoDB.Driver.MongoCredential("Admin", "password", $true);
$user = New-Object -TypeName MongoDB.Driver.MongoUser($credentials, $false)
$credentials fails because argument 1 it is not a MongoIdentity and I can't find any information about how to create one of these. Any help would be gratefully received
I use all the parameters in the argument list. The following works fine for me:
$Client = New-Object -TypeName MongoDB.Driver.MongoClient -ArgumentList "mongodb://dbuser:dbpass#localhost:27017/test"

Powershell - Some commands won't run with Invoke-Command

I am trying to send some commands from a server to about 50 clients running Powershell. Most commands work using Invoke-Command. I used the exact same format as my other commands, yet this one won't work. Basically I want to have each client fetch an .xml file from my server to import it later on. I am missing $credentials and other variables from my code sample here but they are setup correctly somewhere else in my script.
Permission wise, TrustedHosts in winrm is set to * and script execution is set to Unrestricted.
clear
$temp = RetrieveStatus
$results = $temp.up #Contains pinged hosts that successfully replied.
$profileName = Read-Host "Enter the profile name(XML file must be present in c:\share\profiles\)"
$File = "c:\profiles\profile.xml"
$webclient = New-Object System.Net.WebClient
$webclient.Proxy = $NULL
$ftp = "ftp://anonymous:anonymous#192.168.2.200/profiles/$profileName"
$uri = New-Object System.Uri($ftp)
$command = {write-host (hostname) $webclient.DownloadFile($uri, $File)}
foreach($result in $results)
{
# download profile from C:\share\profiles
Invoke-Command $result.address -ScriptBlock $command -Credential $credentials
# add profile to wireless networks
# Invoke-Command $result.address -ScriptBlock {write-host (hostname) (netsh wlan add profile filename="c:\profiles\$args[0].xml")} -argumentlist $profileName -Credential $credentials
}
I get the following error:
You cannot call a method on a null-valued expression.
+ CategoryInfo : InvalidOperation: (DownloadFile:String) [], RuntimeException
+ FullyQualifiedErrorId : InvokeMethodOnNull
Any idea? The same command works flawlessly on the clients when run locally.
You use $webclient within a scriptblock where $webclient will not be defined on the other end. Why don't you create the web client in the scriptblock e.g.:
$command = {
param($profileName)
$File = "c:\profiles\profile.xml"
$webclient = New-Object System.Net.WebClient
$webclient.Proxy = $NULL
$ftp = "ftp://anonymous:anonymous#192.168.2.200/profiles/$profileName"
$uri = New-Object System.Uri($ftp)
Write-Host (hostname)
$webclient.DownloadFile($uri, $File)}
}
$profileName = Read-Host "Enter the profile name(XML file must be present in c:\share\profiles\)"
Invoke-Command $result.address -ScriptBlock $command -Credential $credentials -Arg $profileName
This will require you to provide some of the variables from the client to the remote machine via the -ArgumentList parameter on Invoke-Command. Those supplied arguments then map to the param() statement in the scriptblock.