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

Passing variable to -Identity param

$
0
0

Hello

I want to pass multiple group names in the -Identity param for Get _ADGroupMember. I tried many others ways but it did not work out.

I have $groupnames @()
with 7-8 elements in it.
I want to use this $groupname as

 $groupMembers = Get-ADGroupMember -identity $groupName  | Select SamAccountName

How do I achieve this?



Change Printer IP address

$
0
0

Hi all

I have a list of 700 printers I need to change an IP address for. I have a CSV file I am using but no luck. Both the old and new ip are in the table

What am I doing wrong?

$PrinterTable = Import-Csv D:\OldPrinterIP.csv
ForEach ($Prnt in $PrinterTable){
    If($Prnt.PortName -contains $OldIP){
    Add-PrinterPort -Name "IP_$NewIP" -LprHostAddress $NewIP -LprQueueName (Get-PrinterPort -Name IP_$OldIP).LprQueueName
    $NewIP = $PrinterTable.NewIP
    }
}


Get Network Hops without Test-NetConnection

$
0
0

I need to deploy a script that will ping various IPs and choose to connect with the closest one based on hop count. I've seen where Test-NetConnection can do this quite easily but many of my computers are Win7 or Server2008 and they don't have Test-NetConnection. Any alternatives you can think of or know a way to easily add Test-NetConnection?

Thanks!


Doug S

Exchange Powershell mailbox orginization script

$
0
0
Hey all, I am trying to set up some automated orginization for my journaling mailbox. What I would like to do is have some script that will create a subfolder based on year, then subfolders based on month and have messages moved to these folders based on the dates received. An example below is what I would like my inbox to look like

Example@abc.com
Inbox
- 2019
 - Jan
 - Feb
 - Mar
 - Apr
 - May
 - etc.
- 2018
 - Jan
 - Feb
 - Mar
 - Apr
 - May
 - etc.
- 2017
 - Jan
 - Feb
 - Mar
 - Apr
 - May
 - etc.
 And so forth.

I'm not sure where to start as scripting is my weakest link. If anyone can assist it would be greatly apprecieated. 

delete

Report with all Computers + last logged on user + User OU

$
0
0

I've been looking high and low for this, a report that's sounds easy enough to take out but it seems I can only get either Computer informationor User information, not both.

Is there a genious out there that can help me take out a report like above preferably from powershell.

I'm looking for the following fields:
Computer Name, User name, OU, Computer Description

Moving Files while copying the folder structure

$
0
0

I need help getting what I think may be a fairly simple script.

I have  a folder structure with folders within.  Each folder has a number of files with a wide range of modification dates.

I need to move all files to a new location - but I need their folder structures to stay in tact at the new location.

Any help would be greatly appreciated.

Thanks,

George Jackson

Powershell GUI Datagridview items to a combobox Question

$
0
0

Hello,

I am working on a powershell GUI project and have a datagridview with data i pulled from SQL that part works.

What i want to do it get a rows of a column to show in a combobox for selection.

Later i want to click a button to query the other columns of the row the username is on to populate text boxes.

Here is my code so far minus the SQL part that works.

Add-Type -AssemblyName System.Windows.Forms
[System.Windows.Forms.Application]::EnableVisualStyles()

$Form                            = New-Object system.Windows.Forms.Form
$Form.ClientSize                 = '800,500'
$Form.text                       = "Form"
$Form.TopMost                    = $false
$Form.FormBorderStyle = 'Fixed3D'
$Form.MaximizeBox = $false

#$gps | foreach {$dataGridView.Rows.Add($result)}
#$list = New-Object System.collections.ArrayList
#$list.AddRange($gps)

$dataGridView = New-Object System.Windows.Forms.DataGridView -Property @{
    Size=New-Object System.Drawing.Size(800,400)
    ColumnHeadersVisible = $true
    DataSource = $table
}


$dataGridView.location          = New-Object System.Drawing.Point(4,2)
$dataGridView.SelectionMode = 'FullRowSelect'
$dataGridView.MultiSelect = $true

$ComboBox1                      = New-Object system.Windows.Forms.ComboBox
$comboBox1.DropDownStyle =      [System.Windows.Forms.ComboBoxStyle]::DropDownList;
$ComboBox1.text                  = ""
$comboBox1.Sorted = $true
$ComboBox1.width                 = 190
$ComboBox1.height                = 20
$ComboBox1.location              = New-Object System.Drawing.Point(171,427)
$ComboBox1.Font                  = 'Microsoft Sans Serif,10'


$connection.Close()
$Form.controls.AddRange(@($DataGridView,$ComboBox1))
$form.ShowDialog()

Example of the SQL datagridview output:

RecordNumber FirstName
------------ ---------
        4077 Brandie  
        4126 Ashley   
        4136 Christine
        4139 Shaleka  
        4140 Deulis   
        4142 Tiana    
        4145 Elysa    
        4146 Terri    
        4148 Paul     
        4152 Kourtney 
        4156 Edward   
        4158 Karla    
        4159 Atiya    
        4161 Lakeya   
        4164 Amiri    


Cannot run WinRM or Powershell against servers that have SPN's set up

$
0
0

When we try to run a invoke-command against our servers (we have dozens) that have SPN's set up for CRM, SSRS and other apps we get the error below.

If we remove the SPN's from AD, we can run remote PS commands like invoke-command.  We know SPN's are set up correct and we get Kerberos tickets.

I am trying to determine if some other security setting is locked down by our security dept that would not allow Remote execution. I also get a very similar error when trying to run WinRM commands on the machine. Trusted hosts is set to *.* on all of our servers.

Connecting to remote server WestCRM1 failed with the following error message : WinRM cannot process the request. The following error with errorcode 0x80090322 occurred while using Kerberos authentication: An unknown security error occurred.  

Does ConvertFrom-Json parser maintain the sequence of array elements persisted in the JSON file

$
0
0

Hi,

At a high level, I am working on building a utility where-in the overall operation and granular tasks to be performed is driven by a JSON file. A group of tasks is maintained as a JSON array and it is critical that tasks be performed in the order in which they are defined in the array.

The JSON file is read from disk in power-shell using API ConvertFrom-Json

I have an two options

  • Assume that sequence of elements of array are maintained by ConvertFrom-Json

      Here one can define the tasks as an array of strings, holding the task files

      NOTE: This is a random example, used only for the purpose of this question

"tasks": [
"C:\FirstTask.bat",
"C:\SecondTask_DependsOnFirstTaskBeingPerformed.bat"
]

       The execution script will list the elements in the array and perform them in sequence.

    $converted_json_object.tasks| Foreach-Object{

        # Perform task

    }

  • Assume that sequence of elements of array are NOT maintained by ConvertFrom-Json

      Here one can define the tasks as an array of objects, holding the task files and the sequence number

      NOTE: This is a random example, used only for the purpose of this question

"tasks": [
{"task_number": 1, "task_name": "C:\FirstTask.bat"},
{"task_number": 2, "task_name": "C:\SecondTask_DependsOnFirstTaskBeingPerformed.bat"}
]

       The execution script will list the elements in the array, sort them on task number and perform them in sequence.

    $converted_json_object.tasks | Sort-Object -Property task_number | Foreach-Object {

        # Perform task

    }

The JSON RFC states that - "An array is an ordered sequence of zero or more values." I am however not sure if ConvertFrom-Json parser is guaranteed to maintain this sequence.

I would appreciate any information on whether it is safe to assume that the current (and future) versions of ConvertFrom-Json are guaranteed to maintain the order or array elements. This will enable me to not require to maintain a "task_number" member in the array of tasks in JSON.

Thanks and Regards,

Nilesh


Assigning permissions to folders via powershell

$
0
0

Hi experts,

I am trying to assign modify permission to folders and files within a folder recursively using PowerShell. However, I am getting lot of these errors. Please advise.

Set-Acl : The security identifier is not allowed to be the owner of this object.
At C:\Folderpermissions.ps1:10 char:1
+ Set-Acl $path $acl
+ ~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : InvalidOperation: (E:\Data\Team Su...rategy Proposal:String) [Set-Acl], InvalidOperationException
    + FullyQualifiedErrorId : System.InvalidOperationException,Microsoft.PowerShell.Commands.SetAclCommand
 

You cannot call a method on a null-valued expression.
At C:\Folderpermissions.ps1:8 char:1
+ $acl = (Get-Item $path).GetAccessControl('Access')
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : InvalidOperation: (:) [], RuntimeException
    + FullyQualifiedErrorId : InvokeMethodOnNull
 

$location = "E:\Data\Path_of_folder"
$group = "SecurityGroup_RW"
$rule = New-Object system.security.accesscontrol.filesystemaccessrule($group,"Modify","ContainerInherit,ObjectInherit","None","Allow")
$folders = Get-Childitem $location -Recurse | Where-Object {$_.PSISContainer}
Foreach ($folder in $folders) {
$path = $folder.FullName
$acl = (Get-Item $path).GetAccessControl('Access')
$acl.SetAccessRule($rule)
Set-Acl $path $acl
}

Cannot remove SMB share mappings created with New-SmbGlobalMapping

$
0
0
$secpasswd = ConvertTo-SecureString PASSWORD -AsPlainText -Force;

$creds = New-Object System.Management.Automation.PSCredential ("AUTH\Admin", $secpasswd);

New-SmbGlobalMapping -RemotePath \\ABC.net\temp -Persistent:$true  -Credential $creds -LocalPath X:;

I mapped the Drive X: using above PS script.

But I cannot remove the X: drive using disconnect and remove-smbmapping.

1. Right-click and click "Disconnect"

Error: This network connection does not exist.

2. Remove-SmbMapping -LocalPath 'X:' -Force

Error:

Remove-SmbMapping : No MSFT_SmbMapping objects found with property 'LocalPath' equal to 'X:'.  Verify the value of the
property and retry.
At line:1 char:1
+ Remove-SmbMapping -LocalPath 'X:' -Force -UpdateProfile
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : ObjectNotFound: (Y::String) [Remove-SmbMapping], CimJobException
    + FullyQualifiedErrorId : CmdletizationQuery_NotFound_LocalPath,Remove-SmbMapping

Also call Get-SMBMapping, no outputs.

Anyone knows what's wrong with it?

Group policy for MDM enrollment not getting effected

$
0
0

Hi 

I am trying to create an auto enrollment for my windows 10 desktops into Intune,I have already managed to build all the supported infrastructure and able to  register any windows system in our company AD by changing the Local policy using GUI. Now I need to make it automated. I  have identified the Registry settings which actually changed during the Local policy change .I created a script as below which will create a registry key and add the two corresponding key words as below.


New-Item -path  "HKLM:\SOFTWARE\Policies\Microsoft\Windows\CurrentVersion\" -Name MDM
New-Itemproperty  -path  "HKLM:\SOFTWARE\Policies\Microsoft\Windows\CurrentVersion\MDM" -Name AutoEnrollMDM -Value 1 -Type DWord
New-Itemproperty  -path  "HKLM:\SOFTWARE\Policies\Microsoft\Windows\CurrentVersion\MDM" -Name UseAADCredentialType -Value 1 -Type DWord

But Even after successful execution of this script my systems are not getting enrolled into  Intune 

Can someone please help me on this 

-Sachin

Apply Results from a Group to Set-MailboxSearch

$
0
0

-SourceMailboxes parameter wants the values to be like "user@domain.com","user2@domain.com","user3@domain.com" any way I can achieve this?

Or rather than get the members of a group, get all mail enabled users and apply the Set-MailboxSearch command to them?

$emailaddress = Get-ADGroupMember -Identity groupname | select samaccountname | %{Get-ADUser $_.samaccountname -Properties mail} | %{write-output "$($_.mail)"}


Set-MailboxSearch -Identity "inplace hold name" -SourceMailboxes $emailaddress -SearchQuery subject:'"test test"' -MessageTypes IM -InPlaceHoldEnabled $True -ItemHoldPeriod 90 -TargetMailbox user3@domain.com -EstimateOnly $true -ExcludeDuplicateMessages $false

Start-MailboxSearch -Identity "inplace hold name"

Output is not complete Find-AdmPwdExtendedRights -Identity

$
0
0

Hi,

I am executing the below command.

Command 1 : Find-AdmPwdExtendedRights -Identity "OU=IN-Chennai,DC=constoso,DC=com" 

Output is like below

Not able to see all the details and ....  (See the GREEN BOX)

Find-AdmPwdExtendedRights -Identity "OU=IN-Chennai,DC=constoso,DC=com"  

Command 2 : Find-AdmPwdExtendedRights | Export-Csv -Path LAPS_AdmPwdExtendedRights.csv -NoType

Output:

ObjectDNExtendedRightHolders
OU=IN-Chennai,DC=constoso,DC=comSystem.Collections.ObjectModel.ReadOnlyCollection`1[System.String]

Please help to the powershell command to get the complete output


Regards, Boopathi


Unzip GZ files using Powershell

$
0
0
I have  Windows 2008 Server with some GZ type files in a folder. I would like to script unzipping them using Powershell, can someone tell me if this is possible and how I would do it?

The folder is d:\data_files\ and I'd like to uncompress all the .gz files in there

I've searched around on the Net but can't find much that deals with GZ files specifically. The files are all named data-1.gz, data-2.gz etc
Hello

I have  Windows 2008 Server with some GZ type files in a folder. I would like to script unzipping them using Powershell, can someone tell me if this is possible and how I would do it?

The folder is d:\data_files\ and I'd like to uncompress all the .gz files in there

I've searched around on the Net but can't find much that deals with GZ files specifically.

Powershell script to list all mountpoints

$
0
0

Hello all

I'm trying to build a script to list all mountpoints in a windows 2016 server, but my problem is cant had the disk id that is viewed in disk manager.

$TotalGB = @{Name="Capacity(GB)";expression={[math]::round(($_.Capacity/ 1073741824),2)}}
$FreeGB = @{Name="FreeSpace(GB)";expression={[math]::round(($_.FreeSpace / 1073741824),2)}}
$FreePerc = @{Name="Free(%)";expression={[math]::round(((($_.FreeSpace / 1073741824)/($_.Capacity / 1073741824)) * 100),0)}}

function get-mountpoints {
$volumes = Get-WmiObject win32_volume -Filter "DriveType='3'"
$volumes | Select Name, Label, DriveLetter, FileSystem, $TotalGB, $FreeGB, $FreePerc | Format-Table -AutoSize
}

get-mountpoints

This script will show the mount points and other volumes but no the disk id that match the mount point.

Is it possible?

Thanks

is it possible to create a command that runs a script

$
0
0

I'm new to powershell so this is probably very easy. I have a script which I want to run by executing "audit". Is it possible to register custom commands like that?

Thanks!


Senior .NET Developer

Need help with script to export shared mailbox full access permissions and security group membership.

$
0
0

Pretty much every shared mailbox we have in our environment has a security group assigned to it that is the same name except starting with SG_.  I'm looking to have a script that can parse through all the shared mailboxes, review the security group assigned to it and export the members out with it.  I have something below but it's not complete and I'm unsure how to set it.  Any suggestions are appreciated.

Ideally it would output something like:

Mailbox Name     Security Group Name       Access

Mailbox1                 SG_Mailbox1                 domain\user1

mailbox1                sg_mailbox1                   domain\user2

MailboxABC            SG_MailboxABC              domain\userA

$sharedmailbox = Get-Mailbox -RecipientTypeDetails "shared" -ResultSize unlimited

foreach ($mb in $sharedmailbox) { 

$securitygroup = Get-Mailbox -id $mb | Get-MailboxPermission | where { ($_.User -like "domain\SG_*") } 
$securitygroup = ($securitygroup.identity -split "/")[-1]
#Write-Host "security group" $securitygroup.User

foreach ($member in $securitygroup.User) {

write-host $member
$SGMember = Get-DistributionGroupMember -Identity $member

Write-Host $SGMember

$outarray += New-Object PsObject -property @{
'Mailbox' = $mb
'security group' = $securitygroup.User
'SG Member' = $SGMember
}
}

}

$outarray

Get folder size of a list of folders and export to Excel

$
0
0

Hi, could you see what i am doing wrong, with export to excel. I have a list of folders, I want to capture the size of the folders and output it to CSV.

$Folders = Get-Content D:\folders.txt
Foreach ($Folder in $Folders)
{
$size = ("{0:N2} MB" -f ((Get-ChildItem $Folder -Recurse | Measure-Object -Property Length -Sum -ErrorAction Stop).Sum / 1MB))
$size | export-csv -Path d:\FolerSize.csv -NoTypeInformation -append
}

The Resulting .csv is not capturing the size but the Length. How come?

Length
7
7
9
8
11
9
8
7
7

Thank you

Viewing all 21975 articles
Browse latest View live


Latest Images

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