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

Powershell command to filter values

$
0
0

PS C:\> Get-EC2Instance |%{ $_.RunningInstance } | Select-Object InstanceId,@{Name='TagValues'; Expression={($_.Tag |%{$_.Value }) -join ','}}

InstanceId                                              TagValues
----------                                                  ---------
i-230151d                                                Sco
i-8c80f27                                                 landscape123,test
i-3d3195                                                  temp,landscape234
i-a2f216                                                  Ras
i-1a594c1                                                Aeau

How do I filter the values so the output can be

InstanceId                                              TagValues
----------                                                  ---------
i-8c80f27                                                landscape123
i-3d3195                                                 landscape234

*The TagValues will always be landscape*


Powershell script to get all local admin members

$
0
0

Created this from multiple sources - it works - just wanted to see comments on what I could have done better.

Input - all computers in domain.  Connects to them and then pulls all members of local admin group and writes information to a csv.  Its slow - but works.

Thanks for input.

Import-module ActiveDirectory
$computers = Get-ADComputer -Filter *
$LocalGroupName = "Administrators"

$OutputDir = "c:\temp"
$OutputFile = Join-Path $OutputDir "LocalGroupMembers.csv"
Write-Verbose "Script will write the output to $OutputFile folder"
Add-Content -Path $OutPutFile -Value "ComputerName, LocalGroupName, Status, MemberType, MemberDomain, MemberName"

foreach ($computer in $computers)
    {
        $computerName = $computer.name
		If(!(Test-Connection -ComputerName $computerName -Count 1 -Quiet)) {
			Add-Content -Path $OutputFile -Value "$computerName,$LocalGroupName,Offline"
		Continue
		}
		else {
			try {
				$group = [ADSI]"WinNT://$computerName/$LocalGroupName"
				$members = @($group.Invoke("Members"))
				if(!$members) {
					Add-Content -Path $OutputFile -Value "$Computer,$LocalGroupName,NoMembersFound"
					Continue
				}
			}
			catch {
				Add-Content -Path $OutputFile -Value "$computerName,,FailedToQuery"
				Continue
			}
			foreach($member in $members) {
				try {
					$MemberName = $member.GetType().Invokemember("Name","GetProperty",$null,$member,$null)
					$MemberType = $member.GetType().Invokemember("Class","GetProperty",$null,$member,$null)
					$MemberPath = $member.GetType().Invokemember("ADSPath","GetProperty",$null,$member,$null)
					$MemberDomain = $null
					If($MemberPath -match "^Winnt\:\/\/(?<domainName>\S+)\/(?<CompName>\S+)\/") {
						if($MemberType -eq "User") {
							$MemberType = "LocalUser"
						} elseif($MemberType -eq "Group"){
							$MemberType = "LocalGroup"
						}
						$MemberDomain = $matches["CompName"]
					} elseif($MemberPath -match "^WinNT\:\/\/(?<domainname>\S+)/") {
						if($MemberType -eq "User") {
							$MemberType = "DomainUser"
						} elseif($MemberType -eq "Group"){
							$MemberType = "DomainGroup"
						}
						$MemberDomain = $matches["domainname"]
					} else {
						$MemberType = "Unknown"
						$MemberDomain = "Unknown"
					}
					If ($MemberName -notlike "Domain Admins" -and $MemberName -notlike "Enterprise Admins" -and $MemberName -notlike "redtower1"-and $MemberName -notlike "Administrator" -and $MemberName -notlike "WorkstationAdmins" -and $MemberName -notlike "ServerAdmins")	{
					Add-Content -Path $OutPutFile -Value "$computerName, $LocalGroupName, SUCCESS, $MemberType, $MemberDomain, $MemberName"
					}
				} catch {
				Add-Content -Path $OutputFile -Value "$Computer,,FailedQueryMember"
				}
    		}
		}
		}

Compare-object memory problems

$
0
0

I tested on 20MB files and it works OK. On 300+MB files, it consumes all memory. Any suggestions to optimize?

function Compare-text
{
param(
$text1,
$text2,
[switch]$IncludeEqual
)
$comp1 = Get-Content $text1
$comp2 = Get-Content $text2
$comparisons = Compare-Object $comp1 $comp2 -IncludeEqual:$IncludeEqual | group {  $_.InputObject.ReadCount } | sort Name
$comparisons | foreach {$curr = $_
switch ($_.Group[0].SideIndicator)
{
'==' { $right=$left = $curr.Group[0].InputObject;break}
'=>' { $right,$left = $curr.Group[0].InputObject,$curr.Group[1].InputObject;break }
'<=' { $right,$left = $curr.Group[1].InputObject,$curr.Group[0].InputObject;break }
}
[PSCustomObject] @{
Line = [int]$_.Name
Source = $left
Target = $right + "`n___________________________________________________`n"
}
}
}

Script to clean HKEY_USERS

$
0
0

Hello, I currently have the foloowing issue.

We are running citrix and when usrs sign in, their default printer resets to the local printers, (xps writer, send to one note, etc)

This has been tracked down to the following Reistry Key HKEY_USERS 

I have found a way that has fixed this issue for everyone who is experiencing it at my company.
I had to go and edit the users registry hive:
HKEY_USERS\USERS_SID_HERE\Printers\Connections
I inevitably found old printer connections there that were no longer valid.  Upon clearing those out, after a reboot, the problem went away.
I also cleared out the HKEY_USERS\USERS_SID_HERE\Printers\Settings key - the users had old printer setting sin there also.
THANKS !!! This should be marked as the answer.
Checked HKEY_USERS\USERS_SID_HERE\Printers\Connections, found and old driver and deleted the driver. Everything is fine after restart.

via https://social.technet.microsoft.com/Forums/windows/en-US/316fd408-4957-43b1-92e3-8dda96dcdded/default-printer-keeps-changing

I manually deleted the Connections, and the Settings key and it went away. I am now trying to automate this as there are 25 servers with 400 users.

this is a idea of a powershell script i was working on but I am lost.

New-PSDrive -PSProvider Registry -Name HKU -Root HKEY_USERS
cd HKU:\
Get-ChildItem "HKU:\" | Where-Object { $_.PSIsContainer }  | Remove-Item -Force -Recurse

Get-ItemProperty -Path $_.PSPath -Name "DevModes2"
Get-ItemProperty -Path $_.PSPath -Name "Settings"
Get-ItemProperty -Path $_.PSPath -Name "Connections"

the three Get-ItemProperty are the three folder i want to delete under HKEY_USERS

can some one help?

Note I also posted in the Server 2008 forum in-case there was another way to do this.

Multiple CSV merging into single one - adding vaules from csv

$
0
0

Hello,

sorry for my question, im quite newbie in powershell and have this funny task which i have to do, i tried google it but without luck.

My problem is :

i have multiple csv files, each contains 2 collums , Foldername and Foldersize of directory on drive . Foldernames are all the same in each csv, but Foldersize is different each time.

so all csv looks like this , the only difference between them is collum Foldersize :

FolderName 1, Foldersize1

FolderName 2, Foldersize2

FolderName 3, Foldersize 3

and so on...

I would need a script witch will take all csv from folder and merge them into single one where will be only 2 collums

FolderName 1, sum of all foldersizes for FolderName 1 

FolderName 2, sum of all foldersizes for FolderName 2 

Is it possible to do it somehow? 

I hope i wrote it comprehensibly :)

Thanks for any help

Kromsa


#TYPE System.Data.DataRow Is 1st line of SSMS To CSV

$
0
0

almost a complete noob when it comes to powershell so please dumb down any response :).  This is the script I am using (created by bill fellows ... I can't find his blog post to link back to)

$server = "localhost"
$database = "master"
$query = "SELECT D.* FROM sys.databases D"

# powershell raw/verbatim strings are ugly
# Update this with the actual path where you want data dumped
$extractFile = @"
C:\test.csv"@

# If you have to use users and passwords, my condolences
$connectionTemplate = "Data Source={0};Integrated Security=SSPI;Initial Catalog={1};"
$connectionString = [string]::Format($connectionTemplate, $server, $database)
$connection = New-Object System.Data.SqlClient.SqlConnection
$connection.ConnectionString = $connectionString

$command = New-Object System.Data.SqlClient.SqlCommand
$command.CommandText = $query
$command.Connection = $connection

$SqlAdapter = New-Object System.Data.SqlClient.SqlDataAdapter
$SqlAdapter.SelectCommand = $command
$DataSet = New-Object System.Data.DataSet
$SqlAdapter.Fill($DataSet)
$connection.Close()

# dump the data to a csv
# http://technet.microsoft.com/en-us/library/ee176825.aspx
$DataSet.Tables[0] | Export-Csv $extractFile

Getting "Open File - Security Warning" using Start-Process

$
0
0

Hello everyone...

I am trying to include the silent installation of Report Viewer 2010.

The following command works in both PowerShell and the old command prompt (with no prompting):

\\{FileServerName}\commonfiles\ReportViewer\ReportViewer_2010_Sp1.exe /q

So, I want to take this command and run it using the "Start-Process" command.  (The reason why I am doing this is to use the "-Wait" option... I don't want the next commands running until the installation is done.)

Both of the following attempts cause the "Open File -Security Warning" prompt to appear:

Start-Process -FilePath \\{FileServerName}\commonfiles\ReportViewer\ReportViewer_2010_Sp1.exe -ArgumentList "/q" -Wait

Start-Process -FilePath \\{FileServerName}\commonfiles\ReportViewer\ReportViewer_2010_Sp1.exe -ArgumentList "/q" -Wait -Verb RunAs

So, something is happening that is making "Start-Process" prompt me.  (Execution Policy is currently "RemoteSigned")

Any suggestions?

Thanks!


SCCM Client cmdlet Win32Reg_AddRemovePrograms

$
0
0
I am trying to write a powershell script to get a list of all application install on the local compouter, using the the SCCM Client cmdlet Win32Reg_AddRemovePrograms, the computers do have the SCCM 2012 R2 client installed, but I am running into an issue. The command will only collect the programs base on the bit level of powershell.  So if I open Powershell (x86) and run Get-WmiObject -Class Win32Reg_AddRemovePrograms, I get the 32 bit applications on a 64 bit computer.  I need to run that same command in Powershell (x64) to get the 64 bit applications.  I tried using Win32Reg_AddRemovePrograms64, but I get the same list as the other cmdlet.  Am I missing something with this cmdlet?

Need Help Adding Snapin for Exchange Admin script

$
0
0

Years ago, I created a Windows app that allowed an admin user to create users in Active Directory via Exchange Management using Powershell commands executed in a vb.net program.

No, I'm trying to implement the same functionality in a custom workflow activity.  This activity runs under the credentials that the workflow system runs under and does not have the capability to create users/mailboxes.

So, I'm trying to rewrite the code and so far have found the only way to make a good connection with a new credential we created just for this is to create the runspace using a WSManConnection instead of a RunSpaceConfiguration.

The problem:  how do I now add the Microsoft.Exchange.Management.Powershell.Admin snapin that I've always used?

When I try (in the code below) I get an error:  Unhandled Exception: System.Management.Automation.PSNotImplementedException: Cannot perform operation because operation NewNotImplementedException at offset 93 in file:line:column <filename unknown>:0:0 is not implemented.

I am almost totally inexperienced in Powershell as I've gotten these routines from example sources and I'm no Exchange expert by any stretch of the imagination.

Any help would be GREATLY appreciated.

Sincerely,
Glen

    Dim securePassword As System.Security.SecureString = New System.Security.SecureString()
    Dim c As Char
    Dim password As String = "adminPassword"
        For Each c In password.ToCharArray()
            securePassword.AppendChar(c)
        Next
    Dim adminCred = New PSCredential("millermartin\adminUser", securePassword)

    Dim psConn = New WSManConnectionInfo()
        psConn.ComputerName = "ourserver"
        psConn.Credential = adminCred
        psConn.ShellUri = "http://schemas.microsoft.com/powershell/Microsoft.Exchange"

    Dim rsp As Runspace = RunspaceFactory.CreateRunspace(psConn)
    rsp.RunspaceConfiguration.AddPSSnapIn("Microsoft.Exchange.Management.PowerShell.Admin", snapEx)
    rsp.Open()

    Dim psCmd As Command

Network map with logon script

$
0
0

Hello,

I have a strange issue with my logon script in powershell with some of my users. In my logon script, I want to map a network drive. Here is my code for doing that :

$networkDriverLetter = "N:"

if(-not (Test-Path -Path $networkDriverLetter))
{
	# Unmap network drive if present
	try
	{
		$net = $(New-Object -ComObject WScript.Network)
		$net.RemoveNetworkDrive($networkDriverLetter, $true, $true)
		$msgUnmapNetworkDrive =  "Unmap network drive " + $networkDriverLetter + " for user " + [Environment]::UserName
		Write-EventLog -LogName "Application" -Source "Application" -EventId 9876 -EntryType "Warning" -Message $msgUnmapNetworkDrive -Category 0 -ErrorAction SilentlyContinue
	}
	catch
	{
		# Do nothing, network drive might not be mapped
		$msgDoNothingNetworkDrive =  "Do nothing, network drive might not be mapped for user " + [Environment]::UserName
		Write-EventLog -LogName "Application" -Source "Application" -EventId 9876 -EntryType "Warning" -Message $msgDoNothingNetworkDrive -Category 0 -ErrorAction SilentlyContinue
	}


	# Map network drive pointing to customer app DB folder
	$mapDestPath = $appSharePath + "\" + $customerNumber + "\DB"
	$net.MapNetworkDrive($networkDriverLetter, $mapDestPath, $true)
	$msgMapNetworkDrive =  "Map network drive " + $networkDriverLetter + " for user " + [Environment]::UserName
	Write-EventLog -LogName "Application" -Source "Application" -EventId 9876 -EntryType "Warning" -Message $msgMapNetworkDrive -Category 0 -ErrorAction SilentlyContinue
}




When the script run, I have this in my log :

Do nothing, network drive might not be mapped for user

.Map network drive N: for user USER01

This log is added after the "$net.MapNetworkDirve..."

But, in the log "Microsoft-Windows-PowerShell/Operational", I have this message :

Error Message = Could not find the drive 'N:\'. The drive might not be ready or might not be mapped.

Provider name = Microsoft.PowerShell.Core\FileSystem


Context:
        Severity = Warning
        Host Name = ConsoleHost
        Host Version = 4.0
        Host ID = bce11ead-1dab-492d-a930-7563f2fed196
        Host Application =  -ExecutionPolicy ByPass -File \\domain.lan\sysvol\domain.lan\scripts\ConfigureAppSession.ps1
        Engine Version = 4.0
        Runspace ID = 0dd628e5-44d4-4f8a-87db-05fcd7ccfbd6
        Pipeline ID = 1
        Command Name =
        Command Type =
        Script Name =
        Command Path =
        Sequence Number = 22
        User = DOMAIN\USER01
        Shell ID = Microsoft.PowerShell


User Data:

The event log added by my script say the network drive is mapped, but powershell says something goes wrong. The script does not work every time. Sometimes everything is good, and sometimes something not work.

Can you help me ? 



Move Email Attachment to another folder using powershell

$
0
0

Up until i was given this assignment last week I had never heard of PowerShell.  I am to move emails with attachments such as PDF to a different folder.  I found a tutorial on how to move emails by subject line and it works I just can not figure out how weed out a pdf.  Here is the code to move by subject line.  Any help would be awesome.

 Add-Type -assembly "Microsoft.Office.Interop.Outlook"
 $Outlook = New-Object -comobject Outlook.Application
 $namespace = $Outlook.GetNameSpace("MAPI")
 $inbox =
   $namespace.GetDefaultFolder([Microsoft.Office.Interop.Outlook.OlDefaultFolders]::olFolderInbox)
 $MyFolder1 =
   $namespace.Folders.Item('cander@myCompany.com').Folders.Item('AA_REPORTS_PDF')
 $rules = $namespace.DefaultStore.GetRules()
 $rule = $rules.create("My rule1: Notification",
   [Microsoft.Office.Interop.Outlook.OlRuleType]::olRuleReceive)
   $rule_body = $rule.Conditions.Subject
 $rule_body.Enabled = $true
 $rule_body.Text = @('Notification')
 $action = $rule.Actions.MoveToFolder
 $action.enabled = $true
   [Microsoft.Office.Interop.Outlook._MoveOrCopyRuleAction].InvokeMember(
     "Folder",
     [System.Reflection.BindingFlags]::SetProperty,
     $null,
     $action,
     $MyFolder1)
 $rules.Save()

"Register this connection's addresses in DNS"

$
0
0

"Register this connection's addresses in DNS" <- can this be set with Powershell?

Please? Thank you.

How to get local user rights?

$
0
0

I need to test local user accounts for user rights applied at the local computer level.  Is there any way to do this short of exporting the current local security policy?

I've seen some scripts use secedit /export /areas USER_RIGHTS /cfgto export settings, then update these settings, and re-import them.  This appears to be the only way to modify Local User Rights.

Is there any way to simply inspect them -- without using secedit? 

I can successfully get a list of accounts in the Local Admins group with Get-CimAssociatedInstance:

$localadmins = @(Get-CimAssociatedInstance -InputObject $(Get-CimInstance -ClassName Win32_Group -Filter "Name = 'Administrators'") -ResultClassName Win32_UserAccount | select -ExpandProperty Caption)

Is it possible to enumerate User Rights this way?

cf: technet.microsoft.com/en-us/library/hh875542.aspx

Get RDS/TS Clients IP, as seen by the server

$
0
0

We have an application that runs on our RDS/TS servers that uses Powershell to query the OS to obtain the RDP clients IP to determine which location they are at, and offer up printers available at that site. This has been working great, but we've come across an issue.

Some of our client networks happen to have overlapping subnets with us, so their network is NATTED to a non-overlapping subnet. The issue our application is having is when we query for the clients IP, we're getting the true IP of the client and not the NATTED address that is actually connected to the RDS/TS server.

It seems this information should be obtainable. While researching, I've seen several suggestions of using NETSTAT, but I need to associate that output with RDS/TS sessions.

Denny

Warning: 'EnableWriteOrderPreservationAcrossDisks' is not required for 'Set-VMReplication'.

$
0
0

When we run set-vmreplication -vmname **** -EnableWriteOrderPreservationAcrossDisks 1we get WARNING: 'EnableWriteOrderPreservationAcrossDisks' is not required for 'Set-VMReplication'.

I can see other threads asking the exact same question I'd be about to - so is it even enabled? There's no confirmation. Checking the Technet for "Get-VMReplication" doesn't give anything obvious how to check.

As obscure as this command to enable the write order preservation is, so is the command to check which requires piping and advanced knowledge of Powershell, and no where I can find documentation how to find this info how to check.

Get-vmreplication -VMname ****** | fl enab* shows True for the server we've just ran the command on. Great.

But then curious I ran the command on each server we have utilising Replica. Result? It shows all servers as having this enabled. I've googled and looked into this and as far as I can possibly tell the default for Write Order Preservation is disabled and you are required to enable it - reading the Technet article explaining SQL support clearly says you need to enable the featurelink here.

So what's the go? Is it enabled for our one server we specified? Is it enabled for all? Is the command Get-VMReplication indeed showing the correct information?

And then some bigger questions - Why is this not in the GUI? It's clearly a very important thing to have and be made clear about it's presence.

Why is it so poorly documented the use of this feature? Even where mentioned to "enable" it say in the SQL blog it gives no information if you are meant to enable it from any PC, the Hyper V host, the SQL guest etc.

What frustrates me most is no one from Microsoft will do anything with these really important questions and there'll be no clear answer to this headache of what is an essential thing apparently.


Fail to download python using powershell

$
0
0

I need to download python using powershell:

(New-Object System.Net.webclient).DownloadFile("https://www.python.org/ftp/python/2.7.9/python-2.7.9.amd64.msi","C:\python-2.7.9.amd64.msi" )

but it always failed because it can't connect to remote server:

9.amd64.msi","C:\python279.msi")
Exception calling "DownloadFile" with "2" argument(s): "Unable to connect to the remote server"
At line:1 char:47
+ (new-object System.net.webclient).downloadfile <<<< ("https://www.python.org/ftp/python/2.7.9/python-2.7.9
,"C:\python-2.7.9.amd64.msi")
    + CategoryInfo          : NotSpecified: (:) [], MethodInvocationException
    + FullyQualifiedErrorId : DotNetMethodException

but I can manually download it on the same machine. So I am wondering whether I need a special setting to download python?

Missing Get-WindowsFeature cmdlet on Windows 8.1 Enterprise

$
0
0

Hi

Just installed Windows 8.1 Enterprise. I don't have the cmdlet "Get-WindowsFeature". I do howerver have "Get-WindowsOptionalFeature" For Windows 2012 R2 I have both.

Is WindowsFeature removed on Windows 8.1?

Regards,

Michael Klinteberg

test powershell execution policy RemoteSigned

$
0
0

Hi,

How do I practically test powershell's execution policy RemoteSigned?

I did downloaded a sample powershell ps1 script from the internet but when I copied over to my local drive and executed the script, it executed successfully. I would imagine that if you copy over a script downloaded to your local drive then it would be treated as a local script then?

Regards,

Ochen

Editing Azure/AD with CSV files

$
0
0

Hello,

Over the past year I've learned a lot in managing Azure and Exchange Online via powershell. One of the areas that still escapes me is importing csv files for configuration. Mainly the structure of the csv file.

I have a request to add office locations to all user accounts in a domain. The office location fields are not set currently. I have the users email addresses, first names, last names, log on ids, and office locations. How would I structure the csv file and what command would I run to import it and make the changes. Also will I need to know the distinguished name?

On another note. If you can provide me any comprehensive information on the structuring of csv files that would be appreciated as well.

Thanks in advance.

Count Rows In DataSet

$
0
0

When I run my script it gives me a count on-screen in the powershell window...is this the syntax that is actually "counting"?  What I am wanting to do is if after the SSMS query is run if their are 0 results to export then don't save the file. BUT if the count is >=1 then export and save as usual.

$SqlAdapter = New-Object System.Data.SqlClient.SqlDataAdapter
$SqlAdapter.SelectCommand = $command
$DataSet = New-Object System.Data.DataSet
$SqlAdapter.Fill($DataSet)
$connection.Close()

Viewing all 21975 articles
Browse latest View live


Latest Images

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