I am new to python development, trying to convert PowerShell code to python.
I am looking for a python code to check user exists in AD domain . Equivalent to PowerShell command (dsquery user -name $username) . if account exists then get the user CanonicalName Properties. Equivalent to PowerShell command (Get-ADUser $username -Properties * | Select CanonicalName). Thanks for your help.
Related
I recently started a new job and have never had to call sql queries within Powershell before. Any assistance would be appreciated. I know I am making newbie mistakes, but arrays are not my strong suit.
I am looking for the query stored in the $customer variable to pull a list of database names and display it in an out-gridview box. The person should be able to select the database they wish to work with and the database name should be stored in a variable as text to use in the subsequent test-path commands.
Right now when I run the command, the output I see is as shown. The $customer variable should show the customers name from the sql query, not System.Data.DataRow
Script so far:
<#
.SYNOPSIS
A script for migrating a portal from EC2/appn (N Virginia us-east-1) to a VPC cell.
.DESCRIPTION
This script is currently written in local scope. Run while logged into Pacejet RDP.
.PARAMETER customer
The name of the customer database to be migrated.
.EXAMPLE
MigratePortal.ps1 -customer Decatur
#>
#Declare command line switches
Param
(
[string]$customer
)
$ErrorActionPreference = "Stop"
#Establish Pacejet paths in variables - Update as needed.
$plugins = "\\dbn\SharedApp\WebServices\PacejetPreprocessWS\PluginLibraries\$customer\"
$occonfig = "\\dbn\SharedApp\OpenConnectors\OpenConnector\Config\$customer.xml"
$nsconfig = "\\dbn\SharedApp\OpenConnectors\OpenConnector\OpenConnectorPrograms\NetsuiteConfigs\$customer.xml"
$customer = #(Invoke-Sqlcmd -Query "SELECT name FROM master.dbo.sysdatabases" | Out-GridView -Title 'Choose Database to be Migrated to VPC:' -PassThru)
write-host "The Customer is named $customer"
if (test-path $plugins) {write-host "Plugin library for $customer detected."} else {write-host "Plugin library for $customer does not exist"}
if (test-path $occonfig) {write-host "Open Connector configuration for $customer detected."} else {write-host "Open Connector configuration for $customer does not exist"}
if (test-path $nsconfig) {write-host "NetSuite configuration for $customer detected."} else {write-host "NetSuite configuration for $customer does not exist"}
Incorrect script output:
PS SQLSERVER:\> F:\ScriptRepo\MigratePortal.ps1
The Customer is named System.Data.DataRow
Plugin library for System.Data.DataRow does not exist
Open Connector configuration for System.Data.DataRow does not exist
NetSuite configuration for System.Data.DataRow does not exist
You are assigning the data from the database/out-gridview to $customer which is a parameter you have typed to [string] so the object is being saved with it's ToString() value which is System.Data.DataRow. Change this variable to something different that is not already used like $database
#Daniel answer is correct. You might of had a lingering variable assignment or lingering function definition, be sure you remove the function from memory when you are testing to be sure you are running what you think you are. FYI spacing in a file does not increase its size all that much as compared being able to read it. Use line breaks and indentation to make it readable for your own sanity.
I ran the following:
[string]$customer = 'Fred'
$plugins = "\\dbn\SharedApp\WebServices\PacejetPreprocessWS\PluginLibraries\$customer\"
$occonfig = "\\dbn\SharedApp\OpenConnectors\OpenConnector\Config\$customer.xml"
$nsconfig = "\\dbn\SharedApp\OpenConnectors\OpenConnector\OpenConnectorPrograms\NetsuiteConfigs\$customer.xml"
$database = #(Invoke-Sqlcmd -Query 'SELECT name FROM master.dbo.sysdatabases' | Out-GridView -Title 'Choose Database to be Migrated to VPC:' -PassThru)
Write-Host "The Customer is named $customer"
if (Test-Path $plugins) {
Write-Host "Plugin library for $customer detected."
} else {
Write-Host "Plugin library for $customer does not exist"
}
if (Test-Path $occonfig) {
Write-Host "Open Connector configuration for $customer detected."
} else {
Write-Host "Open Connector configuration for $customer does not exist"
}
if (Test-Path $nsconfig) {
Write-Host "NetSuite configuration for $customer detected."
} else {
Write-Host "NetSuite configuration for $customer does not exist"
}
and got:
The Customer is named Fred
Plugin library for Fred does not exist
Open Connector configuration for Fred does not exist
NetSuite configuration for Fred does not exist
You can shorten your output statements to something like:
"Plugin library for $customer $(if(Test-Path $plugins){'detected'}else{'does not exist'}
I have this command to find a distribution list object
dsquery * -filter "(&(cn=*group))"
but now how can I find the users from that, I want to loop through and get their names and email addresses from it.
Thanks
Now that you have the group name, you can use PowerShell to iterate through the group and extract the information you need:
Import-Module ActiveDirectory
$group = read-host "Please Enter Group Name: "
$members = Get-ADGroupMember -Identity $group -Recursive
ForEach ($member in $members) {
$memberType = $member.objectClass
If ($memberType -eq 'user') {
Get-ADUser -Filter "name -like '*$member'" -Properties cn,mail | Out-File c:\temp\Group_Members.csv -append
}
}
The code above will prompt for the group name and export the list of members, including where there is a nested group into the a file called Group_Members.csv in c:\temp.
You will need to ensure that:
Script execution is enabled in Powershell;
That RSAT is installed on the device that the script is executed from;
That the script is executed with administrator privileges.
A co-worker has tasked me with creating an LDAP query for a new application he's setting up, PowerBroker. The goal is to pull the list of managers for all of the users in an OU if they have a particular AD attribute, let's call it "SecurityLevel". The OU has the current administrative accounts and the "managers" are the standard accounts of the users they belong to.
This is pretty easy to do in Powershell, but we'd like the tool to automatically update as we create new admin accounts and the tool has a field to use an LDAP query. I'm new to LDAP queries, but thought it would be simple. Unfortunately, it's proving more difficult than I anticipated.
I was thinking it would look something along the lines of (manager)(SecurityLevel=1).
The powershell for it looks something like this:
$SecondaryAccounts = Get-ADUser -Filter * -SearchBase "OU=SecondaryAccounts,OU=USERS,DC=example,DC=com" -Properties Name, manager, SecurityLevel
foreach ($account in $SecondaryAccounts)
{
if ($account.SecurityLevel -eq 1)
{
$PrimaryAccount = $account.Manager
Write-Host "Type 1 account: $PrimaryAccount"
}
}
Any recommendations on how to get the manager information?
I was thinking it would look something along the lines of (manager)(SecurityLevel=1).
Close. As an LDAP query, it should be this:
(&(manager=*)(SecurityLevel=1))
That means: If the manager attribute has a value and the SecurityLevel attribute is equal to 1.
To use an LDAP query with Get-ADUser, you need to use the -LDAPFilter parameter:
Get-ADUser -LDAPFilter "(&(manager=*)(SecurityLevel=1))" -SearchBase "OU=SecondaryAccounts,OU=USERS,DC=example,DC=com" -Properties Name, manager, SecurityLevel
The -Filter parameter uses PowerShell style conditions, and allows you to use the property names that Get-ADUser exposes rather than the raw AD attribute names (e.g. "Surname" instead of "sn"). In that format, the same conditions would look like this:
Get-ADUser -Filter "manager -like '*' -and SecurityLevel -eq 1" -SearchBase "OU=SecondaryAccounts,OU=USERS,DC=example,DC=com" -Properties Name, manager, SecurityLevel
The manager attribute contains the distinguishedName of the manager's account. So you can pass that into Get-ADUser to read the manager's account. All of that together will look something like this:
$SecondaryAccounts = Get-ADUser -LDAPFilter "(&(manager=*)(SecurityLevel=1))" -SearchBase "OU=SecondaryAccounts,OU=USERS,DC=example,DC=com" -Properties Name, manager, SecurityLevel
foreach ($account in $SecondaryAccounts)
{
$PrimaryAccount = Get-ADUser $account.Manager
Write-Host "Type 1 account: $($PrimaryAccount.Name)"
}
I am attempting to run a powershell script utilizing Invoke-SqlCmd2. For various reasons, I need to execute the sql as a specific Windows account which I have the credentials for.
The initial process that executes is not running as the domain account, so I use the credentials I have to create a new Credential object, and then use that to create a New-PSSession :
$password = ConvertTo-SecureString $credentialPass -AsPlainText -Force
$cred = New-Object System.Management.Automation.PSCredential ($credentialUser, $password)
$sess = New-PSSession -credential $cred
Next, I Invoke-Command to start up a new powershell session as my supplied user.
Invoke-Command -Session $sess -ScriptBlock $sb
Within that (scriptblock, file, whatever) I then try to execute Invoke-SqlCmd2 as a Trusted Connection
$resultListTable = Invoke-Sqlcmd2 -query $query -ServerInstance $ServerInstance -Database $db -As "DataTable" -Debug
The connectionString generated is : Data Source=ZZZZ;Initial Catalog=XXXX;Integrated Security=True;Connect Timeout=15 but the end result is the error:
Exception calling "Open" with "0" argument(s): "Login failed for user 'NT AUTHORITY\ANONYMOUS LOGON'."
This result was surprising to me, as I had fully expected the New-PSSession to solve this problem for me. To that end, I've tried to debug things a bit more, and have added the following code to explain to me what user the script thinks it is running as.
$s = #"
** From .Net Environment : [$([Environment]::UserDomainName)\$([Environment]::UserName)]
** From windows access token : [$([Security.Principal.WindowsIdentity]::GetCurrent().Name)]
** From ps environment variables: [$($env:userdomain)\$($env:username)]
** From whoami : [$(whoami)]
** From WMI object : [$(Get-WMIObject -class Win32_ComputerSystem | select username).username]
** From ps environment variables: [$($env:userdomain)\$($env:username)]
"#
Write-Host $s
Which produces the following output (just before telling me that 'NT AUTHORITY\ANONYMOUS LOGON' can't login)
** From .Net Environment : [DOMAIN\user]
** From windows access token : [DOMAIN\user]
** From ps environment variables: [DOMAIN\user]
** From whoami : [DOMAIN\user]
** From WMI object : [#{username=DOMAIN\brian}.username]
** From ps environment variables: [DOMAIN\user]
On the surface, there seems to be no possible way for the anonymous login to be utilized. The script is obviously running as my specified user (though the WMI object does still refer to me).
But, even more obviously, this isn't what is true. There must be another layer active here that I just can't see, some misunderstanding in how powershell actually works.
So, the core, underlying question... How do I get a powershell session set up so that when the Invoke-SqlCmd2 cmdlet fires, it is running as the DOMAIN\user ?
Notes
I don't think that remoting is involved here, as I'm always on the same machine. But maybe that doesn't matter...
Run checks against servers
Import-Module dbatools
Import-Module dbachecks
$Server = "AMCB123"
$Database = "DBA"
# Create recordset of servers to evaluate
$sconn = new-object System.Data.SqlClient.SqlConnection("server=$Server;Trusted_Connection=true");
$q = "SELECT DISTINCT servername FROM DBA.[dbo].[Server_Group] WHERE ID =1;"
$sconn.Open()
$cmd = new-object System.Data.SqlClient.SqlCommand ($q, $sconn);
$cmd.CommandTimeout = 0;
$dr = $cmd.ExecuteReader();
# Loop through the servers and build an array
while ($dr.Read()) {
Get-DbaMaxMemory -SqlServer $dr.GetValue(0) | Format-Table
}
$dr.Close()
$sconn.Close()
I have Listed the sql server(stage, prod, DR servers in a table as per the groups), Now I want to compare the servers with group id's to check wethere the servers(stage,prod, DR) with same group id is having same MAXMemory cofiguration or not.
For this I'm using the below powershell script can you please help me with this, I have created a table with all the servewith grop id.
Request to please help me with the loop thorugh the servers and build an array, so that I can run the MAXMEMORY powershell command to compare it using the group id for all servers.
I have collected all the servers details into a table dbo.server groups
the powershell script should iterate through the table by using the ID and check whether the servers in the ID group has same MAXMEMORY configuration ID server_name Environment
1 ABC0123 prod
1 ABC5123 stage
1 ABC4123 DR
2 DEF0123 prod
2 DEF5123 stage
2 DEF4123 DR
I'm trying to use a powershell script which will check and compare the MAXMEMORY configuration as per the ID(to check whether stage, prod, DR server of the same group_id have similar setting or not), if not then it will display a warning/message as group_ids servers are not configured similarly.
Please help me with the script
You're making this script longer than it needs to be. Also, you're using Format-Table prematurely - you should only use the Format-* functions for displaying final information to the user; they output strings, not properly typed data/variables that can be used down the line.
Use the tools that PowerShell and dbatools give you to get your server list, and then pass that list to Get-DbaMaxMemory as a collection.
import-module dbatools
$ServerList = Invoke-DbaSqlQuery -ServerInstance $Server -query "select distinct servername from dba.dbo.server_group where group_id = 1" | Select-Object -ExpandProperty servername;
Get-DbaMaxMemory -ServerInstance $ServerList | Select-Object SqlInstance, SqlMaxMB;
This will give you a list of your SQL instances and the memory they're configured to use. What you do after that...it's hard to say as you haven't clearly defined what you're looking for.
But this may not tell the full story. Wouldn't it be better to check the configured values and what you're currently running with? You can do that with Get-DbaSpConfigure.
import-module dbatools
$ServerList = Invoke-DbaSqlQuery -ServerInstance $Server -query "select distinct servername from dba.dbo.server_group where group_id = 1" | Select-Object -ExpandProperty servername;
Get-DbaSpConfigure -ServerInstance $ServerList | Select-Object ServerName,ConfiguredValue,RunningValue;
You can even create a computed column in that final Select-Object to tell you if the configured & running values differ.
If you just wanted to use dbachecks (which uses dbatools in the background) you can use
$ServerList = (Invoke-DbaSqlQuery -ServerInstance $Server -query "select distinct servername from dba.dbo.server_group where group_id = 1").servername
and
Invoke-DbcCheck -SQlInstance $ServerList -Check MaxMemory
Or you can set the configuration item app.computername and app.sqlinstance to your server list using
Set-DbcConfig -Name app.sqlinstance -Value $serverlist
Set-DbcConfig -Name app.computername -Value $serverlist
and then you can run this (or any other checks) using
Invoke-DbcCheck -Check MaxMemory