I'm logged in at domain "domain1" with my account. I wish via powershell to be able to update users in domain "domain2" via my supe ruser account "suaccount" with password "password1". Trust is established between the two.
Running PowerShell 2.0 and .NET 3.5 SP1
I have gotten this far:
Add-Type -AssemblyName System.DirectoryServices.AccountManagement
$ctype = [System.DirectoryServices.AccountManagement.ContextType]::Domain
$context = New-Object -TypeName
System.DirectoryServices.AccountManagement.PrincipalContext -ArgumentList $ctype, "domain2", "OU=TestOU,DC=domain2", "suaccount", "password1"
$usr = New-Object -TypeName System.DirectoryServices.AccountManagement.UserPrincipal -ArgumentList $context
$usr.Name = "AM Test1"
$usr.DisplayName = "AM Test1"
$usr.GivenName = "AM"
$usr.SurName = "Test1"
$usr.SamAccountName = "AMTest1"
$usr.UserPrincipalName = "amtest1#mtest.test"
$usr.PasswordNotRequired = $false
$usr.SetPassword("errr")
$usr.Enabled = $true
$usr.Save()
Pretty new to PowerShell, any pointers? I want to edit/create users on the "other" domain so to speak.
I get the error:
"Exception calling "Save" with "0" argument(s): "General access denied error
"
At C:\Script\Sandbox\Morris PowerShell Application\includes\mo\mo.ps1:104 char:14
+ $usr.Save <<<< ()
+ CategoryInfo : NotSpecified: (:) [], MethodInvocationException
+ FullyQualifiedErrorId : DotNetMethodException"
Any pointers?
From comments: Try using for username this format domain2\username, and always use the FQDN for the domain. – Christian yesterday
Related
I need to change the timezone for all sites within sharepoint. I run this code that i found online.
Add-Type -Path "C:\Program Files\Common Files\Microsoft Shared\Web Server Extensions\16\ISAPI\Microsoft.SharePoint.Client.dll"
Add-Type -Path "C:\Program Files\Common Files\Microsoft Shared\Web Server Extensions\16\ISAPI\Microsoft.SharePoint.Client.Runtime.dll"
#function to change Timezone regional settings of a SharePoint Online site
Function Set-SPOnlineTimeZone([String]$SiteURL,[String]$TimezoneName,[PSCredential]$Cred)
{
Try
{
#Setup Credentials to connect
$Credentials = New-Object Microsoft.SharePoint.Client.SharePointOnlineCredentials($Cred.Username, $Cred.Password)
#Set up the context
$Ctx = New-Object Microsoft.SharePoint.Client.ClientContext($SiteURL)
$Ctx.Credentials = $credentials
#Get the Root web from given URL
$Web = $Ctx.web
$Ctx.Load($Web)
#Get the Time zone to update
$Timezones = $Web.RegionalSettings.TimeZones
$Ctx.Load($Timezones)
$Ctx.ExecuteQuery()
$NewTimezone = $Timezones | Where {$_.Description -eq $TimezoneName}
#Update the timezone of the site
$Web.RegionalSettings.TimeZone = $NewTimezone
$Web.Update()
$Ctx.ExecuteQuery()
Write-host -f Green "Timezone has been updated for "$Web.Url
#Get all subsites of the web
$Ctx.Load($Web.Webs)
$Ctx.executeQuery()
#Iterate through each subsites and call the function recursively
Foreach ($Subweb in $Web.Webs)
{
#Call the function to set Timezone for the web
Set-SPOnlineTimeZone -SiteURL $Subweb.URL -TimezoneName $TimezoneName -Cred $AdminCredentials
}
}
Catch [System.Exception]
{
Write-Host -f Red $_.Exception.Message
}
}
#Config parameters for SharePoint Online Admin Center and Timezone description
$AdminSiteURL = "https://crescent-admin.sharepoint.com/"
$TimezoneName ="(UTC+04:00) Abu Dhabi, Muscat"
#Get credentials to connect to SharePoint Online Admin Center
$AdminCredentials = Get-Credential
#Connect to SharePoint Online Tenant Admin
Connect-SPOService -URL $AdminSiteURL -Credential $AdminCredentials
#Get all Site Collections
$SitesCollection = Get-SPOSite -Limit ALL
#Iterate through each site collection
ForEach($Site in $SitesCollection)
{
Write-host -f Yellow "Setting Timezone for Site Collection:"$Site.URL
#Call the function to set Timezone for the site
Set-SPOnlineTimeZone -SiteURL $Site.URL -TimezoneName $TimezoneName -cred $AdminCredentials
}
#Read more: https://www.sharepointdiary.com/2017/06/sharepoint-online-change-time-zone-using-powershell.html#ixzz68Mt3Xrom
I gett the following error
At line:10 char:16
+ ... edentials = New-Object Microsoft.SharePoint.Client.SharePointOnlineCr ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidOperation: (:) [New-Object], MethodInvocationException
+ FullyQualifiedErrorId : ConstructorInvokedThrowException,Microsoft.PowerShell.Commands.NewObjectCommand
Exception calling "ExecuteQuery" with "0" argument(s): "The sign-in name or password does not match one in the Microsoft account system."
At line:19 char:1
+ $Ctx.ExecuteQuery()
+ ~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : NotSpecified: (:) [], MethodInvocationException
+ FullyQualifiedErrorId : IdcrlException
An error occurred while enumerating through a collection: The collection has not been initialized. It has not been requested or the request has not been executed. It may need to be explicitly requested..
At line:22 char:1
+ $Timezones | Select ID, Description
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidOperation: (Microsoft.Share...lient.TimeZone]:<GetEnumerator>d__0) [], RuntimeException
+ FullyQualifiedErrorId : BadEnumeration
The account that i'm using is admin account for office365 (globle admin)however it has 2fa. I'm assumuing there needs to be some other method for this but no idea. Any help will be appreciated
According the Microsofts documentation on the Connect-SP* command, if your account is using 2FA you'll want to omit the credentials from your connect statement and let it prompt you for credentials manually.
https://learn.microsoft.com/en-us/powershell/module/sharepoint-online/connect-sposervice?view=sharepoint-ps
See example 3
If you are using MFA in your environment, I would suggest you use sharepoint pnp powesrhsell.
You could refer to the below articles for more:
https://techcommunity.microsoft.com/t5/SharePoint/Using-SharePoint-Client-Side-Object-Model-with-PowerShell-and/m-p/92734
https://www.c-sharpcorner.com/blogs/using-csom-to-connect-to-a-sharepoint-site-with-multi-factor-authentication-enabled
I'm trying to write a powershell script to publish a theme in my on-premise installation of Dynamics CRM.
According to this page it should be really straight forward, I create an object of type PublishThemeRequest which derives from OrganizationRequest and call the method ExecuteCrmOrganizationRequest.
This is the code I'm running:
Import-Module Microsoft.Xrm.Data.Powershell
Add-PSSnapin Microsoft.Xrm.Tooling.Connector
$orgName = "<my organization name>";
$serverUrl = "http://server_url";
$Cred = Get-Credential -UserName "<my username>" -Message "Please Enter admin credentials for CRM"
$conn = Get-CrmConnection -Credential $Cred -OrganizationName $orgName -ServerUrl $serverUrl
$req = New-Object Microsoft.Crm.Sdk.Messages.PublishThemeRequest
$req.Target = New-CrmEntityReference -EntityLogicalName "theme" -Id "DB80D57A-6410-4D11-B784-0093122802AC"
$result = [Microsoft.Crm.Sdk.Messages.PublishThemeResponse]$conn.ExecuteCrmOrganizationRequest($req, $null)
This is what I get when I execute the code above:
Cannot convert argument "req", with value: "Microsoft.Crm.Sdk.Messages.PublishThemeRequest", for "ExecuteCrmOrganizationRequest" to type
"Microsoft.Xrm.Sdk.OrganizationRequest": "Cannot convert the "Microsoft.Crm.Sdk.Messages.PublishThemeRequest" value of type
"Microsoft.Crm.Sdk.Messages.PublishThemeRequest" to type "Microsoft.Xrm.Sdk.OrganizationRequest"."
At C:\Users\xxxxxxxxxx\Desktop\PublishTheme.ps1:21 char:1
+ $result = [Microsoft.Crm.Sdk.Messages.PublishThemeResponse]$conn.Exec ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : NotSpecified: (:) [], MethodException
+ FullyQualifiedErrorId : MethodArgumentConversionInvalidCastArgument
I have been reading the documentation and other websites for a couple of hours now but seem to have hit a wall.
Any ideas of what my problem might be?
I am trying to connect to some independent LDAP stores (ADAM - Active Directory Application Mode) using a specific set of credentials to bind with, but having trouble working out the best way to do this. Here is an example which I had hoped would work:
$ldapHost = New-Object System.DirectoryServices.DirectoryEntry("LDAP://{serverip}:{port}/dc=acme,dc=com","cn=myuser,dc=acme,dc=com","myPassw0rd")
$ldapQuery = New-Object System.DirectoryServices.DirectorySearcher
$ldapQuery.SearchRoot = $ldapHost
$ldapQuery.Filter = "(objectclass=*)"
$ldapQuery.SearchScope = "Base"
$ldapQuery.FindAll()
This will get me:
Exception calling "FindAll" with "0" argument(s): "A local error has occurred.
"
At line:1 char:19
+ $ldapQuery.FindAll <<<< ()
+ CategoryInfo : NotSpecified: (:) [], MethodInvocationException
+ FullyQualifiedErrorId : DotNetMethodException
I also tried:
$ldapHost = New-Object System.DirectoryServices.DirectoryEntry("LDAP://{myip}:{port}/dc=acme,dc=com")
$ldapHost.Username = "cn=myuser,dc=acme,dc=com"
which results:
The following exception occurred while retrieving member "Username": "The specified directory service attribute or valu
e does not exist.
"
At line:1 char:11
+ $ldapHost. <<<< Username = "cn=myuser,DC=acme,dc=com"
+ CategoryInfo : InvalidOperation: (:) [], RuntimeException
+ FullyQualifiedErrorId : PropertyAssignmentException
I've tried a few variations with filter etc. Most of the documentation I can find on this just assumes that I'm connecting to ldap from within the same directory/am connecting with the correct user for the query.
If you're familiar with Python's ldap module, this is how I do it in that:
import ldap
ld = ldap.initialize("ldap://{myip}:{port}")
ld.bind_s("cn=myuser,dc=acme,dc=com","Passw0rd")
ld.search_s("dc=acme,dc=com",ldap.SCOPE_BASE,"objectclass=*")
Any pointers on how to approach this? I can definitely connect via the various LDAP clients out there. I might need to explicitly specify authentication, but I'm not sure because there is so little information on querying from outside the domain.
You can try this...I use it to connect to an OpenLDAP instance and it works well. Works against AD also so it should fit your needs. You'll need to update the $basedn variable and the host/username ones.
$hostname = ''
$username = ''
$Null = [System.Reflection.Assembly]::LoadWithPartialName("System.DirectoryServices.Protocols")
#Connects to LDAP
$LDAPConnect = New-Object System.DirectoryServices.Protocols.LdapConnection "$HostName"
#Set session options (SSL + LDAP V3)
$LDAPConnect.SessionOptions.SecureSocketLayer = $true
$LDAPConnect.SessionOptions.ProtocolVersion = 3
# Pick Authentication type:
# Anonymous, Basic, Digest, DPA (Distributed Password Authentication),
# External, Kerberos, Msn, Negotiate, Ntlm, Sicily
$LDAPConnect.AuthType = [System.DirectoryServices.Protocols.AuthType]::Basic
# Gets username and password.
$credentials = new-object "System.Net.NetworkCredential" -ArgumentList $UserName,(Read-Host "Password" -AsSecureString)
# Bind with the network credentials. Depending on the type of server,
# the username will take different forms.
Try {
$ErrorActionPreference = 'Stop'
$LDAPConnect.Bind($credentials)
$ErrorActionPreference = 'Continue'
}
Catch {
Throw "Error binding to ldap - $($_.Exception.Message)"
}
Write-Verbose "Successfully bound to LDAP!" -Verbose
$basedn = "OU=Users and Groups,DC=TEST,DC=NET"
$scope = [System.DirectoryServices.Protocols.SearchScope]::Subtree
#Null returns all available attributes
$attrlist = $null
$filter = "(objectClass=*)"
$ModelQuery = New-Object System.DirectoryServices.Protocols.SearchRequest -ArgumentList $basedn,$filter,$scope,$attrlist
#$ModelRequest is a System.DirectoryServices.Protocols.SearchResponse
Try {
$ErrorActionPreference = 'Stop'
$ModelRequest = $LDAPConnect.SendRequest($ModelQuery)
$ErrorActionPreference = 'Continue'
}
Catch {
Throw "Problem looking up model account - $($_.Exception.Message)"
}
$ModelRequest
Credit for most of this goes here..
http://mikemstech.blogspot.com/2013/03/searching-non-microsoft-ldap.html
This worked for me. Only use this for testing purposes since password is not secured at all.
Add-Type -AssemblyName System.DirectoryServices.Protocols
$server = test.com
$username = "CN=username,OU=users,DC=test,DC=com"
$password = "userpassword"
$Credentials = new-object System.Net.NetworkCredential($username, $password)
$LdapConnection = New-Object System.DirectoryServices.Protocols.LdapConnection $server
# Basic auth, cleartext password using port 389
$LdapConnection.AuthType = [System.DirectoryServices.Protocols.AuthType]::Basic
$LdapConnection.Bind($Credentials)
$LdapConnection.Dispose()
I'm trying to create a new server audit on a WinServer 2008 R2 with the following PowerShell Script.
[System.Reflection.Assembly]::LoadWithPartialName("Microsoft.SqlServer.SMO") | out-null
$server = "SM1111" #change to desired instance
$instance = "S111"
$auditName = "$instance"+"TestAudit"
$auditDir = 'F:\Microsoft SQL Server\'+$instance+'AuditTestLogsNew\'
$srv = new-Object ('Microsoft.SqlServer.Management.Smo.Server') -argumentlist $instance
$newAudit = New-Object Microsoft.SqlServer.Management.Smo.Audit($srv, "$auditName")
$newAudit.DestinationType = [Microsoft.SqlServer.Management.Smo.AuditDestinationType]::File
$newAudit.FilePath = $auditDir
$newAudit.MaximumRolloverFiles = 10
$newAudit.MaximumFileSize = 100
$newAudit.QueueDelay = 1000
$newAudit.Create()
$newAudit.Enable()
However the following line always fails:
$newAudit = New-Object Microsoft.SqlServer.Management.Smo.Audit($srv, "$auditName")
I get the following error message:
New-Object : Exception calling ".ctor" with "2" argument(s): "SetParent failed for Audit 'S111TestAudit'. "
At MYFOLDER\Documents\Auditing_Test\CreateAudit.ps1:9 char:13
+ $newAudit = New-Object Microsoft.SqlServer.Management.Smo.Audit($srv, "$auditNam ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidOperation: (:) [New-Object], MethodInvocationException
+ FullyQualifiedErrorId : ConstructorInvokedThrowException,Microsoft.PowerShell.Commands.NewObjectCommand
I've been googling a lot, but still haven't found anything that might solve the problem, since I don't quite understand what raises the error to begin with.
I have full administrator privileges.
Any help would be appreciated!
You are missing the server name for your instance. Your variable $srv is not pointing to an actual server instance.
$server = "SM1111" #change to desired instance <- This isn't doing anything
$instance = "S111"
$srv = New-Object Microsoft.SqlServer.Management.Smo.Server -argumentlist "$server\$instance"
I am trying to implement a way to use a stored secure string so that my SFTP password is not visiable in the script. For example, I'd like to generate a variable $password that could be used instead. I found the following examples online but I can't get them to work unfortunately. I've done something similar in the past but can find my notes or links to the website that explained how to complete the task.
read-host -assecurestring | convertfrom-securestring | out-file C:\securestring.txt
$pass = cat C:\securestring.txt | convertto-securestring
$mycred = new-object -typename System.Management.Automation.PSCredential -argumentlist "test",$pass
Here is my script. Here is a link to the snapin if anyone is interested. http://www.k-tools.nl/index.php/sftp-in-powershell/
#Add the SFTP snap-in
Add-PSSnapin KTools.PowerShell.SFTP
#Define some variables
$sftpHost = "ftp.domain.com"
$userName = "user"
$userPassword = "password"
$localFile = "C:\bin\emp1.xlsx"
#Open the SFTP connection
$sftp = Open-SFTPServer -serverAddress $sftpHost -userName $userName -userPassword $userPassword
#Upload the local file to the root folder on the SFTP server
$sftp.Put($localFile)
#Close the SFTP connection
$sftp.Close()
Again, thanks for everyones help!
UPDATE
I tried this:
$pass = cat c:\bin\ftpcreds.txt | convertto-securestring
$mycred = new-object -typename System.Management.Automation.PSCredential -argumentlist "usertest1",$pass
$sftpHost = "ftp.domain.com"
$userName = $mycred.username
$userPassword = $mycred.password
$sftp = Open-SFTPServer -serverAddress $sftpHost -userName $userName -userPassword $userPassword
$sftp.Put($localFile)
$sftp.Close()
And get this error:
Method invocation failed because [Tamir.SharpSsh.jsch.JSchException] doesn't contain a method named 'Put'.
At C:\bin\SFTP Upload Samples.ps1:21 char:1
+ $sftp.Put($localFile)
+ ~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidOperation: (:) [], RuntimeException
+ FullyQualifiedErrorId : MethodNotFound
Method invocation failed because [Tamir.SharpSsh.jsch.JSchException] doesn't contain a method named 'Close'.
At C:\bin\SFTP Upload Samples.ps1:36 char:1
+ $sftp.Close()
+ ~~~~~~~~~~~~~
+ CategoryInfo : InvalidOperation: (:) [], RuntimeException
+ FullyQualifiedErrorId : MethodNotFound
Any suggestions?
Thanks!
If your SFTP is wanting to use a decrypted version of your secured password then you'll want to extract it from your $mycred by:
$userpassword = $mycred.getnetworkcredential().password.tostring()