Quantcast
Channel: Windows PowerShell forum
Viewing all 21975 articles
Browse latest View live

Get members list from multiple AD groups

$
0
0
Hi,

Please help me out. What I'm doing is importing 16 AD groups in a PowerShell script and finding the list of users in those AD groups. I am doing this for audit purpose. 

Since I'm exporting the user list for 16 AD groups, the -append parameter is making the list of users in the output file appear one next to it and I couldn't figure out which user belongs to which group, since there are 450 to 500 users in the output file. I need some changes in the below script so that each user appears with the group name for which it is extracted. 

Example- script run for first AD group- lists 4 users in that AD group. The script runs again for another AD group, this should display with the users' list along with the Group name which is trying to export the list. Hope I am not complicating it. Please help me out.


$groups = Get-content -path "C:\Users\Santosh\OBIP.csv"
foreach ($GroupName in $groups) 
{
Get-ADgroupmember -Id $GroupName -Recursive | Where objectclass -eq 'user' | Get-ADUser -Properties Displayname,GivenName,Surname,UserPrincipalName,Title,Department,Enabled,ObjectClass, memberof | Select DistinguishedName, samAccountName, Name, Displayname, GivenName, Surname, UserPrincipalName, Title, Department, Enabled, ObjectClass | export-csv -path "C:\Users\Santosh\OBIP\GN.csv" -Append
}

Enumerate All Admins Remotely | Getting "Group" or "User" Attribute

$
0
0

Hello, I used to use another means of extracting the administrator group from remote machines; however, PowerShell 5.0 messed that up... anyways I came across another script; however, it wasn't quite what I wanted, so I made some changes to it and I ALMOST have it the way I would like it. Any help would be appreciated. As you can tell it get's all servers in AD, for each server - get the enumerate the admin group. Here is a picture of the current output - followed by the code:

#Code#

$adservers = get-adcomputer -filter {operatingsystem -like "*server*"} | where {$_.enabled -eq $true} | sort name |Select-Object -ExpandProperty Name  | Set-Content 'C:\temp\servers.txt' -Force 

function get-localusers { 
        param( 
    [Parameter(Mandatory=$true,valuefrompipeline=$true)] 
    [string]$strComputer) 
    begin {} 
    Process { 
        $adminlist ="" 
        $computer = [ADSI]("WinNT://" + $strComputer + ",computer") 
        $AdminGroup = $computer.psbase.children.find("Administrators") 
        $Adminmembers= $AdminGroup.psbase.invoke("Members") | %{$_.GetType().InvokeMember("Name", 'GetProperty', $null, $_, $null)} 
        foreach ($admin in $Adminmembers) { $adminlist = $computer + "," + $admin + ","  

        $Computer = New-Object psobject 
        $computer | Add-Member noteproperty ComputerName $strComputer 
        $computer | Add-Member noteproperty Administrators $admin
        $computer | Add-Member noteproperty GroupType "THIS IS WHERE THE VARIABLE OF 'GROUP' OR 'USER' WOULD GO."

       Write-Output $computer
 }
 
        } 
end {} 
} 
 
Get-Content c:\temp\servers.txt | get-localusers ######## TO BE USED WHEN THE SCRIPT IS FULLY FUNCTIONAL| Export-Csv c:\temp\localusers3.csv #########

Any help would be appreciated - thanks!

Retrieving TPM data and deletion

$
0
0

Hi Everyone,

I want to list the obsolete TPM data from active directory and the to delete it.

Kindly provide your advice how to achieve the same. Thanks!!

Regards

Afsar Shariff

OperationsManager Module - Enumerate "excluded members" from Authoring groups

$
0
0


I am new to the OperationsManager module in PowerShell. I can enumerate a list of included members in an authoring group, but I am at a loss for how to enumerate the excluded members of a group. Unfortunately my organization excludes computer objects explicitly instead of through another group, otherwise I would just go that route. Below is the code I am using to get the SCOM group and its members. Thanks in advance for any help or suggestions!

$server = 'HostName'
$displayName = 'DisplayName'
$sc = Get-SCOMManagementGroupConnection -ComputerName $server
Get-SCOMGroup -DisplayName $displayName -SCSession $SC | Get-SCOMClassInstance -SCSession $SC | sort displayname


Powershell-Copy international settings to the welcome screen, system account and new user account

$
0
0

Hi,

I am trying to copy international settings to the welcome screen, system account and new user account using PowerShell script. But, I can't find any apt solution to my problem. I tried a solution but it only opens up the wizard where we have to select the settings on our own.

I am trying to do it entirely through PowerShell without any user intervention. If someone has any solution to this then please help. 

Thanks in advance

Powershell-Asp.net-IIS

$
0
0

Hi,

I have a Grid View in Asp.net Web page. Gridview populated from the Resultset of Powershell Script.in local its working fine. but its hosted in IIS, Grid view is not generating, I pasted the codes below please advice me on this,

        PowerShell powerShell;
        Runspace <g class="gr_ gr_480 gr-alert gr_spell gr_inline_cards gr_run_anim ContextualSpelling ins-del multiReplace" data-gr-id="480" id="480">runSpace</g>;
        #region PowerShell 
        protected void Runspace()
        {
             runSpace = RunspaceFactory.CreateRunspace();
             runSpace.Open();            
             powerShell = PowerShell.Create();
             RunspaceConfiguration runspaceConfiguration = RunspaceConfiguration.Create();
             powerShell.Runspace = RunspaceFactory.CreateRunspace(runspaceConfiguration);
          
        }
        #endregion
        string exmsg = "";
        
        protected void RunPSScript()
        {           
            Runspace();           
            powerShell.Runspace.Open();
            //Reading PowerShell Commands Directly From ps            
          
            powerShell.AddCommand(Request.PhysicalApplicationPath + "\\Powershell\\Sample.ps1", false);
            int count = 0;
            try
            {
                label1.Text = "Count Label Init";
                Collection<PSObject> results = powerShell.Invoke();
                count = results.Count;
                DataTable tempTable = new DataTable();
                tempTable.Columns.Add("Name");
                tempTable.Columns.Add("Location");
                tempTable.Columns.Add("ResourceGroup");
                tempTable.Columns.Add("Status");
                foreach (PSObject psObject in results)
                {
                    try
                    {

                    DataRow row = tempTable.NewRow();
                    row["Name"] = psObject.Properties["Name"].Value.ToString();
                    row["Location"] = psObject.Properties["Location"].Value.ToString();
                    row["ResourceGroup"] = psObject.Properties["resourcegroup"].Value.ToString();
                    row["Status"] = psObject.Properties["PowerState"].Value.ToString();
                    tempTable.Rows.Add(row);

                    }

                    catch(Exception e)
                    {
                        Console.WriteLine("Exception Message: " +e.Message);
                    }
                   
                  }
                gridview_vms.DataSource = tempTable;
                gridview_vms.DataBind();
                runSpace.Close();
            }
            catch(Exception ex)
            {
                count = -1;
                exmsg = ex.Message;
                Console.WriteLine("Exception Message: " + ex.Message);
            }
            finally
            {
                label2.Text = exmsg;
                label1.Text = "Count Label: " + count.ToString();
            }
          
        }
        string PssResult = "";


uninstall chrome by script in GPO

$
0
0

Hi guys, 

i need to uninstall google chrome on my 700 computers. 

Google chrome was installed by several different msi. So i have a lot of different chrome version on the computers. 

So i would like to use a script to uninstall all the google chrome, even the last version.

I used this powershell script : 

#Following steps are being used to uninstall the current version of Google Chrome

Write-host "Un-Installing the current version of Google Chrome from your machine..." 

$AppInfo = Get-WmiObject Win32_Product -Filter "Name Like 'Google Chrome'"

If ($AppInfo) 
{
    & ${env:WINDIR}\System32\msiexec /x $AppInfo.IdentifyingNumber /Quiet /Passive /NoRestart
}

$Reg32Key = Get-ItemProperty -path "HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall\Google Chrome" -name "Version" -ErrorAction SilentlyContinue

$Ver32Path = $Reg32Key.Version

If ($Ver32Path) 
{
    & ${env:ProgramFiles}\Google\Chrome\Application\$Ver32Path\Installer\setup.exe --uninstall --multi-install --chrome --system-level --force-uninstall
}

$Reg64Key = Get-ItemProperty -path 'HKLM:\SOFTWARE\Wow6432Node\Microsoft\Windows\CurrentVersion\Uninstall\Google Chrome' -name "Version" -ErrorAction SilentlyContinue

$Ver64Path = $Reg64Key.Version

If ($Ver64Path) 
{
    & ${env:ProgramFiles(x86)}\Google\Chrome\Application\$Ver64Path\Installer\setup.exe --uninstall --multi-install --chrome --system-level --force-uninstall
}

But if it works in local on my computer (win7), it unfortunatly doesn't work on the 700 computers when i deploy this script by GPO.

Does anyone has an idea why? or an another idea to uninstall chrome (version 60 to 67) on my 700 computers.

Thanks!




Spawning processes with administrative privileges

$
0
0

Hello

I have a question. I try to build a powershell script that runs a batchfile with Robocopy on multiple servers. It uses Powershell jobs to spawn script that creates a cmd-file on each server and then try to run the cmd-file on that server. The script manages to create the cmd-file and also to start it. In the cmd-file there's a line that specifies that Robocopy should run. The logfile generated by Robocoppy says that Robocopy DOES start but gets an "Access Denied" error when it tries to connect to the destination. If I run the cmd-file manually on the server it works and CAN copy the files properly. My suspicion is that the Robocopy-cmdfile runs in a non administrative mode. But I'm not sure.

To start the cmd-file on the server I run this command:

$qresult = ([WmiClass]"\\$s\ROOT\CIMV2:Win32_Process").create("$cmd")

$s holds the name of the server. And the command in $cmd is "cmd /c C:\Windows\temp\EZRoboPop\rb_local_work.cmd".

I tried to add a whoami command to see that the cmd-file runs under the proper user, which it does.

Robocopy writes this in it's log:

"2018/08/07 12:26:01 ERROR 5 (0x00000005) Getting File System Type of Destination \\afsefile01\rbeztest\

Access is denied."

Any ideas?



top sender in the organization

$
0
0

I am in search of a script for generating top sender in the organization.

Kindly request powershell expert people help.


Ashraf

How do I create a string with repeating characters?

$
0
0

Is there a function to create a string with repeated characters in Powershell? I am looking for something like,

$string = repeat-char("*",35)

Thanks.

XML File Parsing

$
0
0

Hi All,

I have one xml file in below format.

My requirement is to parse this file in csv format with value of InputCredential (highlighted below)as one column and OutputCredentialas another.

<?xml version="1.0"?>

-<aaa:AAAInfo xmlns:aaa="http://www.xxx.com/AAAInfo" xmlns:dpfunc="http://www.xxx.com/extensions/functions">

<aaa:FormatVersion>1</aaa:FormatVersion>

<aaa:Filename>local:///AAAInfo/xxx.xml</aaa:Filename>

<aaa:Summary>File used to authorise Users</aaa:Summary>

<!-- xxxxxxxxxxxxxxxxxxxxxxxxxx. -->


<!-- xxxxxxxxxxxxxxxxxxxxxxx. -->


<!-- Mxxxxxxxxxxxxxxxxxxxxx. -->



-<aaa:MapCredentials>

<aaa:InputCredential>admins</aaa:InputCredential>

<aaa:OutputCredential> */*/*?Access=r+w+a+d+x</aaa:OutputCredential>

</aaa:MapCredentials>


-<aaa:MapCredentials>

<aaa:InputCredential>backup</aaa:InputCredential>

<aaa:OutputCredential>*/*/*?Access=r */*/config/backup?Access=x */*/access/change-password?Access=x */*/config/remove-chkpoint?Access=x */*/config/rollback-chkpoint?Access=x */*/config/save-chkpoint?Access=x */*/config/secure-backup?Access=x */*/status/chkpoints?Access=r */*/login/web-mgmt?Access=x </aaa:OutputCredential>

</aaa:MapCredentials>


-<aaa:MapCredentials>

<aaa:InputCredential>readers</aaa:InputCredential>

<aaa:OutputCredential>*/*/*?Access=r </aaa:OutputCredential>

</aaa:MapCredentials>


-<aaa:MapCredentials>

<aaa:InputCredential>cn=xxx,o=xxx.com</aaa:InputCredential>

<aaa:OutputCredential>admins </aaa:OutputCredential>

</aaa:MapCredentials>


-<aaa:MapCredentials>

<aaa:InputCredential>cn=xxx,o=xxx.com</aaa:InputCredential>

<aaa:OutputCredential>admins </aaa:OutputCredential>

</aaa:MapCredentials>

Please suggest.

Thanks

Powershell GUI - Adding and Removing Controls

$
0
0

I have created some powershell tools with a GUI. I am trying to combine all the Tools into one GUI so that you can use a menu to switch between the different tools.

Just trying to test this by adding and removing Labels depending on the Menu item selected. This is what I have so far but can't seem to get the Remove to work:

###################Load Assembly for creating form & button######

[void][System.Reflection.Assembly]::LoadWithPartialName( “System.Windows.Forms”)
[void][System.Reflection.Assembly]::LoadWithPartialName( “System.drawing.systemcolours”)
[void][System.Reflection.Assembly]::LoadWithPartialName( “Microsoft.VisualBasic”)
Add-Type -AssemblyName PresentationCore,PresentationFramework
#####Define the form size & placement

$form = New-Object “System.Windows.Forms.Form”;
$form.Width = 550;
$form.Height = 350;
$form.Text = "Test";
$form.StartPosition = [System.Windows.Forms.FormStartPosition]::CenterScreen;

#####Define Menu and items

$mainToolStrip = New-Object "System.Windows.Forms.ToolStrip";
$form.Controls.Add($mainToolStrip);


$Test1 = New-Object "System.Windows.Forms.ToolStripbutton";
$mainToolStrip.Items.Add($Test1);
$Test1.Text = "Test 1";


$Test2 = New-Object "System.Windows.Forms.ToolStripMenuItem";
$mainToolStrip.Items.Add($Test2);
$Test2.Text = "Test 2";


$Clear = New-Object "System.Windows.Forms.ToolStripMenuItem";
$mainToolStrip.Items.Add($clear);
$clear.Text = "Clear";




$buttoneventHandlerTest1 = [System.EventHandler]{
##############Define text label1
$textLabel1 = New-Object “System.Windows.Forms.Label”;
$textLabel1.Left = 25;
$textLabel1.Top = 135;
$textLabel1.AutoSize = $True;
$textLabel1.Text = "This is a Test";
$form.Controls.Add($textLabel1);
$form.Controls.Remove($textLabel2);
$form.Refresh();
}


$buttoneventHandlerTest2 = [System.EventHandler]{
##############Define text label2
$textLabel2 = New-Object “System.Windows.Forms.Label”;
$textLabel2.Left = 25;
$textLabel2.Top = 100;
$textLabel2.AutoSize = $True;
$textLabel2.Text = "This is a Test 2";
$form.Controls.Add($textLabel2);
$form.Controls.Remove($textLabel1);
$form.Refresh();
}

$buttoneventHandlerclear = [System.EventHandler]{
$form.Controls.Remove($textLabel2);
$form.Controls.Remove($textLabel3);
$form.Refresh();
Write-host "Clearing"
}


##### Action Buttons

$Test1.Add_Click($buttoneventHandlerTest1) ;
$Test2.Add_Click($buttoneventHandlerTest2) ;
$Clear.Add_Click($buttoneventHandlerclear) ;
$form.ShowDialog()

   or is there a better way to do this?

Restart-computer command in start-job scriptblock always returns as state “blocked”.

$
0
0

If I run the code below then the created job “test3” always has a state “blocked”. It never executes. It has no additional error message. When I run the command in the start-job scriptblock separately, then it does work (restart-computer -computername $computer -credential $MySecureCreds -force).

[void][System.Reflection.Assembly]::LoadWithPartialName('presentationframework')
[xml]$XAML = @"<Window 
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
        Title="CSS Server Reboot" Height="450" Width="800"><Grid><ComboBox Name="Server_Combobox" SelectedValuePath="Content" HorizontalAlignment="Left" Margin="240,107,0,0" VerticalAlignment="Top" Width="120"><ComboBoxItem Name="Server1">10.15.12.148</ComboBoxItem>          </ComboBox><Label Name="Title_Label" Content="CSS – Server Reboot&#xD;&#xA;" HorizontalAlignment="Left" Margin="240,41,0,0" VerticalAlignment="Top" Height="34" Width="284" FontSize="16"/><Button Name="Reboot_Button" Content="Reboot" HorizontalAlignment="Left" Margin="449,107,0,0" VerticalAlignment="Top" Width="75"/><TextBox Name="Reboot_Textbox" Grid.Column="1" HorizontalAlignment="Left" Height="173" Margin="81,180,0,0" TextWrapping="Wrap" VerticalScrollBarVisibility="Auto" Text="" VerticalAlignment="Top" Width="294"/></Grid></Window>"@
#Read XAML
$reader=(New-Object System.Xml.XmlNodeReader $xaml) 
try{$Form=[Windows.Markup.XamlReader]::Load( $reader )}
catch{Write-Host "Unable to load Windows.Markup.XamlReader"; exit}
# Store Form Objects In PowerShell
$xaml.SelectNodes("//*[@Name]") | ForEach-Object {Set-Variable -Name ($_.Name) -Value $Form.FindName($_.Name)}


# Secure credential creation
$Username = "XXX"
$Password = "XXX"
$pass = ConvertTo-SecureString -AsPlainText $Password -Force
$SecureString = $pass
$MySecureCreds = New-Object -TypeName System.Management.Automation.PSCredential -ArgumentList $Username,$pass 

# Use the combobox
$computer
$jobtest
$timer = new-object System.Windows.Threading.DispatcherTimer


$Server_Combobox.add_SelectionChanged( { 

    param($sender, $args)

    $Script:computer = $sender.SelectedItem.Content
   
} )

 

#Assign reboot event to button
$Reboot_Button.Add_Click({

$sb = [scriptblock]::Create("restart-computer -computername $computer -credential $MySecureCreds -force")
Start-Job -Name "test3" -ScriptBlock $sb

$Script:jobtest = Get-Job -Name "test3"

$Reboot_Textbox.AddText("The restart procedure is starting.`n")

$timer.Interval = [TimeSpan]"0:0:5.00"


$timer.add_Tick({

if($jobtest.State -ne "Running"){
$Reboot_Textbox.AddText("The restart failed, please contact IT Ops !!!`n")
$Reboot_Textbox.AddText("The error message is:`n")
$Reboot_Textbox.AddText($jobtest.ChildJobs[0].JobStateInfo.State)
$Reboot_Textbox.AddText("`n")
$Reboot_Textbox.AddText($jobtest.ChildJobs[0].JobStateInfo)
$Reboot_Textbox.AddText("`n")
$Reboot_Textbox.AddText($jobtest.ChildJobs[0].Error)
$Script:timer.Stop()
}elseif($jobtest.State -eq "Completed"){
$Reboot_Textbox.AddText("The restart procedure completed successfully.")
$Script:timer.Stop()
Wait-Job -Name test3 | Remove-Job
}else{
$Reboot_Textbox.AddText("The restart procedure is ")
$Reboot_Textbox.AddText($jobtest.State)
$Reboot_Textbox.AddText("`n")
}         
})

$timer.Start()
           
})

$Form.ShowDialog() | out-null


   



Azure PowerShell: display Varibale info when I add the Format-List to command

$
0
0

Hi,

I executed the following command:

$VM17= Get-AzureRmVM -ResourceGroupName "RG-123" -Name "VM17" | FL

Get-AzureRmVM puts all VM info in $VM17 but when I just want to show $VM17.Name nothing is displayed.

When I run the same command without Format-List I can see the name of VM when I run $VM17.Name

How can I display variable Info when I added Format-List ?

Thanks


Nabil BEN SLAMA

Import-PfxCertificate appears to not 'fully' import the .p12 certificate

$
0
0

Hi,

I'm trying to import OpenVPN client certs (.p12 (PFX) to Windows 10 Enterprise workstations. When I use PowerShell Import-PfxCertificate, it installs quickly and I can see the cert in the CurrentUser\My (Personal) store. It 'looks' right, but when I try to connect the client, it fails with a cert error.

When I manually Right-Click the cert 'Install PFX', choosing default options, it installs and the OpenVPN client works as it should.

Question is: What is PowerShell not doing, that the manual Cert install seems to do?
One thing I notice is that the script runs very fast...the GUI takes a couple seconds...

Manual deployment is not an option...300 or so mostly remote users.

Any ideas or alternate deployment methods would be great. We do have ME Desktop Central, but the User Cert deployment options doesn't' work at all, so that is apparently out.

Mark


New-ADUser : A positional parameter cannot be found that accepts argument '$null'

$
0
0


Hi Guys,

Can someone tell me what is wrong with my scripts. I'm getting Errors. See below Output. Thanks for your help.

PS C:\Users\Administrator> New-ADUser  -SamAccountName "K2Workflow-Dev" $SamAccountName -Name "K2Workflow" $SamAccountNa
me –UserPrincipalName "K2Workflow-Dev" $upn -AccountPassword (ConvertTo-SecureString $Pa$$w0rd! -AsPlainT
ext -Force) -path "gerald-it.com/GeraldIT/Research/K2Workflow" $UserPath -server "geraldit-dc" $serv -GivenName "K2Workf
low" $User.Vorname -Surname "Dev" $User.Nachname -DisplayName "K2Workflow-Dev" $DisplayName -City  "Virginia-Woodbridge"
 -StreetAddress "Carl-Benz-Str. 007"   -Company "Gerald IT Service GmbH" $Company -PostalCode "74007" $PostalCode -enabl
ed $true -Description "Serviceaccount - J.Henk" $Description

=============================================================================


New-ADUser : A positional parameter cannot be found that accepts argument '$null'.
At line:1 char:1
+ New-ADUser  -SamAccountName "K2Workflow-Dev" $SamAccountName -Name "K ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : InvalidArgument: (:) [New-ADUser], ParameterBindingException
    + FullyQualifiedErrorId : PositionalParameterNotFound,Microsoft.ActiveDirectory.Management.Commands.NewADUser

PS C:\Users\Administrator>


Powershell Script to Backup Wallpaper

$
0
0
Was wondering if there was a way to <g class="gr_ gr_6 gr-alert gr_spell gr_inline_cards gr_run_anim ContextualSpelling ins-del multiReplace" data-gr-id="6" id="6">backupa</g> wallpaper when reimaging a system so that I could use that previous wallpaper I had on my new system?

PowerShell 5.1 Desired State Configuration - ConfigurationModeFrequencyMins less than 15 minutes

$
0
0

Hi, I want to know if LCM ConfigurationModeFrequencyMins property value limit of 15 minutes is still valid or it can be set to for instance 10 minutes? PowerShell version on all "managed" systems is 5.1.

Thank you in advance.

get-aduser, error on -filter's arguments syntax error

$
0
0

Hello!,

Trying this:

Get-ADUser `
-Filter "pwdLastSet -lt $((Get-Date).AddDays(-90).ToFileTimeUTC()) -and pwdLastSet -ne 0" `
-Properties pwdLastSet, sAMAccountname | select pwdLastSet, @{name='pwdLastSetDT'; expression={[datetime]::fromFileTime($_.pwdlastset)}}, sAMAccountname

This works well.

When I try to add -and enabled -eq $true to the filter it fails, like so

"

PS C:\Users\Administrator>  Get-ADUser `
>> -Filter "pwdLastSet -lt $((Get-Date).AddDays(-90).ToFileTimeUTC()) -and pwdLastSet -ne 0 `
>> -and enabled -eq $true" `
>> -Properties pwdLastSet, sAMAccountname | select pwdLastSet, sAMAccountname
>>
Get-ADUser : Error parsing query: 'pwdLastSet -lt 131703935522131912 -and pwdLastSet -ne 0
-and enabled -eq True' Error Message: 'syntax error' at position: '75'.
At line:1 char:2
+  Get-ADUser `
+  ~~~~~~~~~~~~
    + CategoryInfo          : ParserError: (:) [Get-ADUser], ADFilterParsingException
    + FullyQualifiedErrorId : ActiveDirectoryCmdlet:Microsoft.ActiveDirectory.Management.ADFilterParsingException,Micr
   osoft.ActiveDirectory.Management.Commands.GetADUser

"

Additionally but of less importance, select with -expand is not working when multiple "select" parameters are present, any other way to sort it?

Thanks in advanced!

Can't delete NS records for delegated DNS zone

$
0
0

Please excuse the mess of code and all the comments - it's WIP - what I'm trying to achieve is to delete the NS records within the delegated zone of web.example.com

This zone currently has 6 x NS records - I want to ensure only the 10.1.1.10-12 records in this example are the only NS records for the zone web.example.com

$ns = $null
$delete_ns = $null
$delegatedzone = $null

$delegatedzone = @()

$delegatedzone = Get-DnsServerZoneDelegation -Name "example.com" -ChildZoneName "web"

#$delegatedzone = $delegatedzone.IPAddress.RecordData.IPv4Address.IPAddressToString
$nshostname = $delegatedzone.IPAddress.HostName

$unbound_test = @("10.1.1.10","10.1.1.11","10.1.1.12")

$delete_ns =@()

foreach ($ns in $unbound_test)
{
    If (!$unbound_test.Contains($ns))
    {  
        Add-DnsServerZoneDelegation -Name "example.com" -ChildZoneName "web" -NameServer $ns -IPAddress $ns -Verbose
    }
    else
    {
        write-host "$ns already exists as NS record"
        #$delete_ns += $ns
    }
}


foreach ($i in $delegatedzone)
{   
     #$i | Where-Object {$_ -eq $unbound_test}

    #If (!$unbound_test.Contains($i))
    If (!$unbound_test.Contains($i.IPAddress.RecordData.IPv4Address.IPAddressToString))
    {
        #$delete_ns += $i
        $delete_ns += $i
    }
}

    
foreach ($blah in $delete_ns)
{
    #Remove-DnsServerZoneDelegation -Name "example.com" -ChildZoneName $blah.NameServer.RecordData.NameServer -ComputerName pw1dc01 -Force -Verbose

    Remove-DnsServerResourceRecord -ZoneName example.com -RRType Ns -Name $blah.NameServer.RecordData.NameServer

    #Remove-DnsServerResourceRecord -ZoneName "web.example.com" -RRType Ns -Name $blah.NameServer.RecordData #-RecordData "$blah.IPAddress.RecordData.IPv4Address.IPAddressToString" # -Name $blah.NameServer.RecordData
    #Get-DnsServerResourceRecord -ZoneName
}

When I run this code the error I receive is:

Remove-DnsServerResourceRecord : Failed to get "aws address record". record in "example.com" zone on "DNS" server.

This record doesn't exist in example.com zone but does exist in web.example.com zone - however you can't specify a child domain with the cmdlet.

Viewing all 21975 articles
Browse latest View live


<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>