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

Cannot use Set-Location, Get-ChildItem, or Join-Path with IIS PSDrive

$
0
0

I'm trying to automation some IIS configuration using the webadministration module. I can see from using Get-PSDrive that it has loaded successfully--however, I can't interact with it in any way. I can't see content or set my location to the drive.

PS C:\> import-module WebAdministration PS C:\> Get-PSDrive Name Used (GB) Free (GB) Provider Root CurrentLocation ---- --------- --------- -------- ---- --------------- Alias Alias C 8.96 0.00 FileSystem C:\ Cert Certificate \ D FileSystem D:\ Env Environment HKCU Registry HKEY_CURRENT_USER HKLM Registry HKEY_LOCAL_MACHINE IIS WebAdminis... \\CITLBLDEMO04 [...]

PS C:\> iis: set-location : Cannot find path 'IIS:\' because it does not exist. At line:1 char:1+ set-location IIS:+ ~~~~~~~~~~~~~~~~~+ CategoryInfo : ObjectNotFound: (IIS:\:String) [Set-Location], ItemNotFoundException+ FullyQualifiedErrorId : PathNotFound,Microsoft.PowerShell.Commands.SetLocationCommand PS C:\> cd iis: cd : Cannot find path 'IIS:\' because it does not exist. At line:1 char:1+ cd iis:+ ~~~~~~~+ CategoryInfo : ObjectNotFound: (IIS:\:String) [Set-Location], ItemNotFoundException+ FullyQualifiedErrorId : PathNotFound,Microsoft.PowerShell.Commands.SetLocationCommand PS C:\> Get-ChildItem -Path IIS:\ Get-ChildItem : Cannot find path '\\CITLBLDEMO04\' because it does not exist. At line:1 char:1+ Get-ChildItem -Path IIS:\+ ~~~~~~~~~~~~~~~~~~~~~~~~~+ CategoryInfo : ObjectNotFound: (\\CITLBLDEMO04\:String) [Get-ChildItem], ItemNotFoundException+ FullyQualifiedErrorId : PathNotFound,Microsoft.PowerShell.Commands.GetChildItemCommand


I'm using 64-bit Powershell v5.0 on Windows 10. On my Windows 7 machine with Powershell v4.0, this doesn't appear to be a problem.

Even join-path won't work if it involves the IIS PSDrive path--I get a NullReferenceException because it can't find that part of the path.

$localsite = 'www1'
$path = join-path -path IIS:\Sites -ChildPath $localsite

produces 

join-path : Object reference not set to an instance of an object.
At line:1 char:9+ $path = join-path -path IIS:\Sites -ChildPath $localsite+         ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~+ CategoryInfo          : NotSpecified: (:) [Join-Path], NullReferenceException+ FullyQualifiedErrorId : System.NullReferenceException,Microsoft.PowerShell.Commands.JoinPathCommand

Thoughts?





Script not running in task scheduler

$
0
0
I have a script that performs a number of tasks based on info provided by a number of csv files. The last task, before emailing the results with the log file, is to perform some tasks in Office 365. I have encrypted the password, to a file, to sign in to Office 365. The script functions when I run it manually but when I run it as a scheduled task it doesn't run. I know its the encrypted password that's causing the issues because I'm logging the various tasks for any problems to a log file. The log file stops processing at the point when I get to the Office 365 tasks area and the email is never sent.

Swap Primary and Secondary SMTP addresses retaining remaining Proxy entries include X500 and other 4 SMTP addresses

$
0
0

Hi Experts,

There are many scripts in forums and gallary to swap Primary and Secondary SMTP addresses.

But our requirement is little different.

we have bunch of users and DLs with 3 to 4 SMTP addresses, SIP and X500 (for cross domain and Ex Org migrated mailboxes).

Recently we added new email address as secondary to these bunch of users and DLs (~600 objects). New email address has couple of scenarios:

1. Both local-part and domain-part is new (new.name@NewDomain.com

2. Change only for local-part of email address (new.name@OldDomain.com)

Our requirement is to swap already existing Primary and secondary, Newly added smtp address, while retaining all the existing Proxy addresses - smtp, x500, SIP etc.

How do it swap the SMTP primary and secondary addresses retaining other entries?

Thanks in Advance.

Veera.


Veerappan Sundaram


Exchange PowerShell not running The pipeline was not run because a pipeline is already running. Pipelines cannot be run concurrently. issue ?

$
0
0

Hi All,

I need to run this PowerShell command to get the Distribution group status:

$Session = New-PSSession -ConfigurationName Microsoft.Exchange -ConnectionUri http://PRODHT01-VM/PowerShell/ -Authentication Kerberos
Import-PSSession $Session -AllowClobber
Import-Module ActiveDirectory -ErrorAction STOP

Function GetDLStatistics {
   Get-DistributionGroup -ResultSize Unlimited -ErrorAction SilentlyContinue | ForEach {$_.GUID} | ForEach {

      ## Run the Get-DistributionGroup Cmdlet
      $DLData = (Get-DistributionGroup -ErrorAction SilentlyContinue -Identity "$_")

      ## Run the Get-QADGroupMember Cmdlet - The @ makes sure it can count 0 and 1 values.
      $DLMembers = @(Get-ADGroupMember -Identity "$_" -ErrorAction SilentlyContinue)

      ## Get values from Get-DistributionGroup Cmdlet
      $ACE_DL_Alias = $DLData.Alias
      $ACE_DL_DisplayName = $DLData.DisplayName
      $ACE_DL_AcceptMessagesOnlyFrom = $DLData.AcceptMessagesOnlyFrom
      $ACE_DL_AcceptMessagesOnlyFromDLMembers = $DLData.AcceptMessagesOnlyFromDLMembers
      $ACE_DL_HiddenFromAddressListsEnabled = $DLData.HiddenFromAddressListsEnabled

      ## Put all values in a string separated by ^ so that it can be put into a CSV.

      $String =  $ACE_DL_DisplayName +"^"+ $ACE_DL_Alias +"^"+ $_ +"^"+ $DLMembers.Count +"^"+
      $ACE_DL_HiddenFromAddressListsEnabled +"^"+ $ACE_DL_AcceptMessagesOnlyFrom +"^"+
      $ACE_DL_AcceptMessagesOnlyFromDLMembers

      $String | Out-File C:\temp\DLGroup.txt -Append
   }
}

GetDLStatistics

Using the <g class="gr_ gr_124 gr-alert gr_spell gr_run_anim ContextualSpelling ins-del multiReplace" data-gr-id="124" id="124">powershell</g> remoting as per https://blogs.technet.microsoft.com/samdrey/2015/04/06/reminder-adding-exchange-2010-or-2013-snap-in-using-add-pssnapin-not-supported-better-use-remote-powershell-from-rmilne/

However, I always get this error when I execute it from my laptop PowerShell ISE:

The pipeline was not run because a pipeline is already running. Pipelines cannot be run concurrently.
   + CategoryInfo          : OperationStopped: (Microsoft.Power...tHelperRunspace:ExecutionCmdletHelperRunspace) [], PSInvalidOperationException
    + FullyQualifiedErrorId : RemotePipelineExecutionFailed
 
Get-DistributionGroup : The session Session1, c26e3c87-4520-4fae-a161-a2e4e898c74d, PRODHT01-VM is not available to run commands.  The session availability is Busy.
At C:\Users\Administrator\AppData\Local\Temp\fd154ca6-4cb6-49ed-959f-c256e6a65d34.ps1:9 char:7
+       $DLData = (Get-DistributionGroup -ErrorAction SilentlyContinue  ...
+       ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : InvalidOperation: ([PSSession]Session1:PSSession) [Invoke-Command], InvalidRunspaceStateException
    + FullyQualifiedErrorId : InvokeCommandCommandInvalidSessionAvailability,Microsoft.PowerShell.Commands.InvokeCommandCommand
 
No valid sessions were specified.  Ensure you provide valid sessions that are in the Opened state and are available to run commands.
At C:\Users\Administrator\AppData\Local\Temp\fd154ca6-4cb6-49ed-959f-c256e6a65d34.ps1:line:9 char:7
+       $ <<<< DLData = (Get-DistributionGroup -ErrorAction SilentlyContinue -Identity "$_")

I also tried to execute the same PowerShell command above in the Exchange Server itself but I got this error instead:

[PRODHT01-VM] Connecting to remote server failed with the following error message : The WinRM client cannot complete the operation within the time specified. Check if the machine name is valid and is reachable over the network and firewall exception for Windows Remote Management service is enabled. For more information, see the about_Remote_Troubleshooting Help topic.
    + CategoryInfo          : OpenError: (System.Manageme....RemoteRunspace:RemoteRunspace) [], PSRemotingTransportException
    + FullyQualifiedErrorId : PSSessionOpenFailed
Import-PSSession : Cannot validate argument on parameter 'Session'. The argument is null. Supply a non-null argument and try the command again.
At C:\TEMP\GetDLStats.ps1:2 char:17
+ Import-PSSession <<<<  $Session -AllowClobber
    + CategoryInfo          : InvalidData: (:) [Import-PSSession], ParameterBindingValidationException
    + FullyQualifiedErrorId : ParameterArgumentValidationError,Microsoft.PowerShell.Commands.ImportPSSessionCommand

Import-Module : The following error occurred while loading the extended type data file:
Microsoft.PowerShell, C:\Program Files\Microsoft\Exchange Server\V14\bin\Exchange.partial.Types.ps1xml : File skipped because it was already present from "Microsoft.PowerShell".
Microsoft.PowerShell, C:\Program Files\Microsoft\Exchange Server\V14\bin\exchange.types.ps1xml : File skipped because it was already present from "Microsoft.PowerShell".
Microsoft.PowerShell, C:\Windows\system32\WindowsPowerShell\v1.0\Modules\ActiveDirectory\ActiveDirectory.Types.ps1xml : File skipped because it was already present from "Microsoft.PowerShell".

At C:\TEMP\GetDLStats.ps1:3 char:14
+ Import-Module <<<<  ActiveDirectory -ErrorAction STOP
    + CategoryInfo          : InvalidOperation: (:) [Import-Module], RuntimeException
    + FullyQualifiedErrorId : FormatXmlUpateException,Microsoft.PowerShell.Commands.ImportModuleCommand

Creating a new session for implicit remoting of "Get-DistributionGroup" command...
ForEach-Object : The term 'Get-ADGroupMember' is not recognized as the name of a cmdlet, function, script file, or operable program. Check the spelling of the name, or if a path was included, verify
that the path is correct and try again.

At C:\TEMP\GetDLStats.ps1:6 char:107
+    Get-DistributionGroup -ResultSize Unlimited -ErrorAction SilentlyContinue | ForEach {$_.GUID} | ForEach <<<<  {
    + CategoryInfo          : ObjectNotFound: (Get-ADGroupMember:String) [ForEach-Object], CommandNotFoundException
    + FullyQualifiedErrorId : CommandNotFoundException,Microsoft.PowerShell.Commands.ForEachObjectCommand

Any help would be greatly appreciated.

Thanks,


/* Server Support Specialist */

DSC - How to use the Package Resource for EXE files

$
0
0

I'm trying to use the PowerShell Desired State Configuration to deploy software packaged in an EXE file. When installed manually, the software does show up in Programs and Features. However, Win32_Product doesn't see it.  DSC won't install the EXE files, usually by just hanging there and not doing anything.

The documentation out there on the Internet for the Package Resource of DSC (both Microsoft generated and admin generated) is, at best, really poor in helping me to troubleshoot, or even understand why it's not working.

  1. I know using a Product ID is preferred.  Aside from installing the software on a "reference" computer, how would I retrieve the product ID without deconstructing the EXE file with development software, like Visual Studio?  (Especially since deconstructing another vendor's EXE file tends to violate support agreements)
  2. How should the software name be formatted?  For my EXE files, I've used the name in the Details tab of properties, the one listed in Programs and Features, and the one in the setup.ini file.  All of these generate an error saying the Name doesn't match.  Where does DSC look to validate that the name matches the software package?
  3. Most of the examples I've seen show the arguments property filled out.  Are the EXE files required to be compatible with command line install to be used by DSC?  If so, is there a standard set of arguments that Microsoft recognizes. or is it determined per developer?
  4. When the DSC Package resource fails to install, where do I look to troubleshoot?  I have the DEBUG and Analytic event logs enabled on the server I'm testing on, and I've also added the LogPath parameter to the Config file, but they don't appear to say anything that would point me in the right direction.  Additionally, the file generated by LogPath remains blank.  I've also used the xDSCDiagnostics module, but while it helps in getting the events, it doesn't help me in understanding where the problem lies, and where to start troubleshooting.  Where else would I look to troubleshoot a DSC initiated installation?

Thank you ahead of time for any assistance you can provide.

Downloading and Installing DSC Resource using Powershell on a Server Core installation

$
0
0

I have been struggling to download the DSC Reskit Wave #10 and install it on a Win2012 R2 Server Core installation using PowerShell 4.0. I have read and tried to navigate through the blog from the Scripting Guys of October 13, 2014 regarding this subject but their PowerShell code suggestions error out. Does anyone one know of a reference or can document for me the procedure for downloading and installing a DSC Resource Kit Wave using PowerShell on a Server Core installation. Thanks for your help.

Michael T. Glenn


Michael T. Glenn

SizeLimit Exceeded error - Get-AdGroupMember

$
0
0

Good day all,

I'm having a problem running the below command: 

Get-ADGroupMember -Identity AllStaff | Get-ADUser -Properties * | select employeeNumber, displayName, mail, extensionAttribute1, extensionAttribute3, extensionAttribute2 | Export-Csv -NoTypeInformation D:\TestFile.csv

error:

Get-ADGroupMember : The size limit for this request was exceeded
At line:1 char:1
+ Get-ADGroupMember -Identity AllStaff | Get-ADUser -Properties * | select employe ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : NotSpecified: (AllStaff:ADGroup) [Get-ADGroupMember], ADException
    + FullyQualifiedErrorId : ActiveDirectoryServer:8227,Microsoft.ActiveDirectory.Management.Commands.GetADGroupMember

How do I change the size limit to around 7000.

Your help would be kindly appreciated.

Regards,

Dominique.

Help with Select-String and Context when output to file

$
0
0

Hello all this is my first post and have only been using PowerShell for about a week.

I have a simple script to pull some lines from text files.

It works great if I don't add the pipe to export.

If I run the full script, it no longer executes Context.

I've read the help on Context and it doesn't seem to tell me why.

Is there another way to do this?

Select-String \\shared\e_drive\Process\Scrub\*.txt -pattern "Str1","Str2","Str3",-Context 0,1

This works great to the console window and shows me the next line after match.

Select-String \\shared\e_drive\Process\Scrub\*.txt -pattern "Str1","Str2","Str3",-Context 0,1|export-csv \\shared\e_drive\Process\Scrub\result.csv

This seems to ignore context as the file clearly doesn't contain the next lines after match.  Any help is appreciated.



error setting displayname

$
0
0

I have a simple .csv file that looks like this
username,upn
thatguy,thatguy@domain.com

Why does this work: 
Get-RemoteMailbox -Identity thatguy | Get-User | %{ $dispName=$_.LastName + ", " + $_.FirstName ; set-remotemailbox -Identity thatguy -Displayname $dispName }

but this doesn't.
Get-RemoteMailbox -Identity $_.username | Get-User | %{ $dispName=$_.LastName + ", " + $_.Firstname ; set-remotemailbox -Identity $_.username -Displayname $dispName }

Above this line in my script, I'm using the $_.username variable to enable-remotemailbox and set the email address with no problems. I get this error.

Cannot bind argument to parameter 'Identity' because it is null.
    + CategoryInfo          : InvalidData: (:) [Set-RemoteMailbox], ParameterBindingValidationException
    + FullyQualifiedErrorId : ParameterArgumentValidationErrorNullNotAllowed,Set-RemoteMailbox

Overwrite Zip contents

$
0
0

Hi guys,

Over the past month I have been trying to write a script that extracts it's contents, makes changes and then rezips it. Unfortunately I need to change the requirements of the script so that instead of creating a new zip file, I need to overwrite the current one. 

Here's my code right now:

[io.compression.zipfile]::CreateFromDirectory("C:\temp\contents\","C:\test\test.zip")


So the .zip file already exists at this location. What I want to see is that the contents of the test.zip get overwritten. This instead does nothing. It's really important that the zip is not deleted, just that it's contents are overwritten. 

Is there anyway to do this? 

EDIT: I do get an error.

"Exception calling "CreateFromDirectory" with 2 arguments: "C:\test\test.zip" already exists."

Powershell Get-Item Issue

$
0
0

Hi I have a powershell script which picks a file and copies it to sharepoint library. Tested the script with local drive and the file gets copied across to sharepoint.

Changed the localdrive to a UNC path, I have full access to the folders, my script lists all the files in the folders and then just exits. Doesn't even catch an exception

$files = ([System.IO.DirectoryInfo] (Get-Item $localFolderPath)).GetFiles()
 
 write-host $files
 
 ForEach($file in $files)
    {

  if($file.Name.Contains(".pdf"))       
  {
   
            $fname = $file.Name
            write-host $file  # Displays the filename on the console
    try
    { 
     $fileStream = ([System.IO.FileInfo] (Get-Item $file.FullName)).OpenRead()

     $folder =  $web.getfolder($docLibraryName)
                      
                      
      write-host "Copying file " $file.Name " to " $folder.ServerRelativeUrl "..."
                  
      $spFile = $folder.Files.Add($folder.Url + "/" + $file.Name,[System.IO.Stream]$fileStream, $true)

      write-host -f Green "Success"

      $fileStream.Close();     

      Send-MailMessage -From $From -to $To -Subject $Subject -Body $Body  -SmtpServer $SMTPServer

catch
    {
                    #move-item $file $localfailure -force
                   
                    $Body = $Body + $fname + " Upload Failure"
                   
                    Send-MailMessage -From $From -to $To -Subject $Subject -Body $Body  -SmtpServer $SMTPServer
                    write-host -f Red "Failure"
                    Write "Error: $file.name: $_" >>c:\srini\spfiles\splogfile.txt
     continue;
    }

Not sure what the issue is, as it works fine from a localdrive, but not an UNC path

Any pointers appreciated

Thanks

Sri

Automated Patching Script

$
0
0


I need a script that will read a text file with a list of server names, examine the server for the OS and remotely run the designated script locally on the server.

Each month we change the name of the script file to correspond to the month that is being patched.

We can change this to a generic name if necessary.



Input:

A Text file with a server name (attached).



Processing:

The script will read the text file and for each server: Examine the servername for the OS of the server

Using the OS, select the right script to run (samples below)

Execute the script locally on the server (Could be Powershell or use PSEXEC – we may need an option for both)

Write an entry to a log file that the processing was completed.

The scripts below run individual patches from a different share.

If we cannot change the names of the scripts by month, we can use a generic name.

For example:  Instead of using Oct2015.cmd, we could use the OS Name such as  W2K8x32.cmd, W2K8x64.cmd, W2K8R2.cmd, W2K12.cmd, W2K12r2.cmd

The current scripts we use are:

For Windows 2008  - 32 bit

\\SERVER1\w2k8Prod$\scripts\Oct2015.cmd

For Windows 2008  - 64 bit

\\SERVER1\w2k8x64Prod$\scripts\Oct2015.cmd

For Windows 2008R2

\\SERVER1\w2k8r2Prod$\scripts\Oct2015.cmd

For Windows 2012

\\SERVER1\w2k12Prod$\scripts\Oct2015.cmd

For Windows 2012R2

\\SERVER1\w2k12Prod$\scripts\Oct2015r2.cmd

Powershell cmdlet copyHere zipping issue on first three execution after a system reboot - File not found or no read permission

$
0
0

Hi,

Once I execute powershell script on Windows Server 2008 R2 or Windows 2012 R2 which try to zip files using copyHere cmdlet after a reboot, for first 3 execution, it pops up window with error msg - File not found or no read permission. After first three runs compression occurs successfully.

Instead if I use CreateFromDirectory, compression is successful each execution after reboot.

If I execute the two scripts (one with copyHere and another with CreateFromDirectory) one after another after a reboot, then again copyHere throws same error as above till the first three attempts while CreateFromDirectory runs successfully in each of the attempt.

What is the reason behind copyHere failure for only first three attempts and how can I overcome this?

can anyone look over this PS script to write event ID to log if any folder contains files older than 12 hours?

$
0
0

following is the code, it would work if each folder only contains 1 file, but will not work correctly if multiple files with different creation time were in the folders. 

$Locations = @("D:\folder1", "D:\folder2", "D:\folder3")

foreach ($Location in $Locations)
{

if  ((Get-ChildItem -Force $Location) -ne $Null)
  {
    $oldest = Get-ChildItem -Path $Location | Sort CreationTime | select -First 1

    if($oldest.TimeCreated -lt [datetime]::Now.AddHours(-12))

        {Write-Eventlog -computername LocalHost -logname Application -Category 3 -source SCOM_Custom_Monitor -eventID 200 -EntryType Information -message "File Age Check Results for '$Location', all files are newer than 12 hours."}
    Else
        {Write-Eventlog -computername LocalHost -logname Application -Category 3 -source SCOM_Custom_Monitor -eventID 400 -EntryType Information -message "File Age Check Results for '$Location', there are file(s) older than 12 hours."}

  }
else
    {Write-Eventlog -computername LocalHost -logname Application -Category 3 -source SCOM_Custom_Monitor -eventID 200 -EntryType Information -message "File Age Check Results for '$Location', folder contains no file"}

}

               

PowerShell window opens and closes immediately

$
0
0

I'm using Windows 7 x64 Pro, just recently updated to Windows Management Framework 5.0 (Win7AndW2K8R2-KB3134760-x64.msu).  Ever since the update, whenever I click the powershell icon, the command console opens and closes immediately. 

Error message:

Windows PowerShell terminated with the following error:
 Could not load file or assembly 'System.Configuration.Install, Version=4.0.0.0, Culture=neutral, PubblicKeyToken=b03f5f7f11d50a3a' or one of its dependencies. The module was expected to contain an assembly manifest.

I have tried uninstalling and re-installing Win7AndW2K8R2-KB3134760-x64.msu, still without success in fixing this issue.


New to powershell trying to make a windows log collection script help!

$
0
0

our previous admin collected logons manually, our system is growing and this it is taking to long so I started working on a script to collect all of our machines logs.  My challenge is I also need it to collect only the event ID's of bad log on attempts but I dont know how to add it into here to pull just those.  Could you help me out?

cls
# server you want to export from
$computers = @("MXXXXXX")
#  logs you want to export
$Logs = @("System")
# amount of days you want to go back in time
$Days = "7"

$timestamp = get-date -f yyyyMMddHHmm
[dateTime]$After = (get-date).addDays(-$Days)
foreach ($computer in $computers) {
    write-host $computer
    foreach ($log in $logs) {
        write-host "- $Log"
        get-eventlog -logname $log -EntryType Error,warning -After $After -ComputerName $computer | Select-Object TimeGenerated,MachineName,Logname,EventID,EntryType,Source,Message | % {
        $_.Message = $_.Message -replace "`n",' '
        $_.Message = $_.Message -replace "`r",' '
        $_.Logname = $Log
        $_
        } | Export-Csv -Path "C:/myscripts/$timestamp-Eventlog.csv" -Append -NoTypeInformation -NoClobber
    }
    Write-Host "- Done! Exported to ./$timestamp-Eventlog.csv"
}

Also is it possible that each log has there own tab?

Select single value in results

$
0
0

i have a simple powershell script that queries AD and brings back a list of names based on the user input, it looks like the following;

$input = read-host "enter string to search for"
$counter = 0
$results = Get-ADUser -Filter "name -like '*$input*'" | Select-Object @{ Name = "ID" ; Expression= {$global:counter; $global:counter++} }, Name | FT -Autosize
$results

and returns the following

ID Name               

-- ----               
 0 user 1
 1 user 2


what i would like to do is be able to select a user by typing in the ID that corresponds to that user in the results. Havent had any luck on this one yet though.







- Please remember to mark post's as helpful if they assist you with your issue.
- Please remember to mark post's as an answer if they provide you with an answer to your issue.

Need to force a password reset for every user in the entire organization (Office 365)

$
0
0

I'm looking for an Office 365 powershell command (or two) that would let me force a mandatory password reset for the entire organization.

I'd like this to happen to every user as soon as possible.

Does anyone know such a command?

PS: We're not syncing with our active directory domain passwords.

Thanks!

Multiple checkboxes in Powershell form

$
0
0

I'm looking to setup a checkbox selector for Organizational Units in a domain, I can create the checkboxes correctly but I don't know how to access what has been checked when the user clicks the 'Apply' button?

import-module activedirectory

function checkbox_ou
{
	[void] [System.Reflection.Assembly]::LoadWithPartialName("System.Windows.Forms")
	[void] [System.Reflection.Assembly]::LoadWithPartialName("System.Drawing")

	$Form = New-Object System.Windows.Forms.Form
	$Form.width = 500
	$Form.height = 600
	$Form.Text = "OU Picker v0.1"


	$Font = New-Object System.Drawing.Font("calibri, verdana, Times New Roman",8)
	$Form.Font = $Font

	$cbheight = 20

	$adorgunit = get-adorganizationalunit -filter * -properties canonicalname | sort name
	foreach ($adou in $adorgunit)
	{
		$ou_name = $adou.name
		$ou_cn = $adou.canonicalname
		$ou_dn = $adou.distinguishedname
		$cbheight += 20

		$checkBox = New-Object System.Windows.Forms.checkBox
		$checkBox.Name = "$ou_dn"
		$checkBox.Text = "$ou_name"
		$checkbox.Location = new-object System.Drawing.Size(30,$cbheight)
		$checkbox.Size = new-object System.Drawing.Size(300,23)
		$Form.Controls.Add($checkBox)
	}



	$ApplyButton = new-object System.Windows.Forms.Button
	$ApplyButton.Location = new-object System.Drawing.Size(130,400)
	$ApplyButton.Size = new-object System.Drawing.Size(100,40)
	$ApplyButton.Text = "Apply"
	$ApplyButton.Add_Click({$Form.Close()})
	$form.Controls.Add($ApplyButton)



    	$Form.Add_Shown({$Form.Activate()})
    	[void] $Form.ShowDialog()

}


checkbox_ou

Powershell - Create Distribution Lists that exist in AD

$
0
0

Hello,

Is there a script that can create distribution lists on mass (100 plus)  in Exchange that already exist in Active Directory?

Thanks

Joshua


Viewing all 21975 articles
Browse latest View live


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