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

get 504 error when I use invoke-command

$
0
0

Hello community! I'm getting this error, while using invoke-command:

the winrm client received an http status code of 504 from the remote ws-management service

WinRM service is running on target. We're using the firewall only for Internet, it's disabled for local web-sites. Most of PC's is connected to Internet via Cisco AnyConnect, which gives IP to PC's itself. Connect between my and target machine is OK, no any packet is lost. Why i'm then getting such error?



Disk activity on server 2012 SMB share by user

$
0
0

We actively monitor the actual disk activity buy i rarely investigate what user is behind the load. I was wondering if there would be an easy way to achieve this with PowerShell.

Currently right now i would look at what file is causing the load then check that against Openfiles.exe but is there a better way?

Problem for send the result for a script

$
0
0

Hiii ,

I execute my script I get the test results of two, but the third does not work, I do not get the final result. I get email with the name of the machine and the SID, as in the picture attached, for against the third script I do not get the result, I added the double quote , I do synxtaxe that of the here-body it not. I have to do, thank you for you have answered.

This a code for the firt test in green of pickture : 

$body = @"
Nom de la machine: $($env:computername)
Le SID de la machine:  $($sid.AccountDomainSid.ToString())"@

and this second code in red of the same pickture 

# this not :(
$body= @"$test = @('localhost:10050','localhost:22','s.code42.fr:10050')Foreach ($t in $test){$source = $t.Split(':')[0]$port = $t.Split(':')[1]Write-Host "- connection au telnet à l'adresse $source sur le port $port ..."try{$socket = New-Object System.Net.Sockets.TcpClient($source, $port)

write-Host "$t est en succès" -ForegroundColor Green}

catch [Exception]{

Write-Host $_.Exception.GetType().FullNameWrite-Host $_.Exception.Messagewrite-Warning "$t est en failed "}}"@


achraf


Problem setting registry permissions using Powershell

$
0
0

I have a couple of scripts that I have put together to change the registry value of a specific key in the registry.  This primarily is being done on our Windows 7 machines as the XP setup is slightly different and this change is not needed.

The first part of the script calls the below segment after it sets folder permissions.

	Write-Host "Executing Registry Changes:" -ForeGroundColor Red
	invoke-command -computername $strComputer -filepath \\PATH\SetMESPermissionsReg.ps1
	Write-Host "Registry Change Script Complete." -ForeGroundColor Red


The contents of SetMESPermissionsReg.ps1 are:

$acl = Get-Acl HKLM:\SOFTWARE\NewMes
		Write-Host "Opening Registry key for write" -ForeGroundColor Cyan
$rule = New-Object System.Security.AccessControl.RegistryAccessRule ("NT Authority\Authenticated Users","FullControl","Allow")
$acl.SetAccessRule($rule)
$acl |Set-Acl -Path HKLM:\SOFTWARE\NewMes
		Write-Host "Permissions have been set!" -ForeGroundColor Green

After running this, everything seems to work fine except the program errors out upon running it.  When I check the permissions of the registry key, I notice that it sets full control but not at the top-level... it only sets it under special permissions as shown in the screenshot below.  If I go into regedit and check the box for full control at the first permissions screen, clearing the special permissions flag, everything works as it should.  How do I set the top-level Full Control option through PowerShell so that someone can do the installs without having to (or know how to) change anything?

a value not being returned

$
0
0

Can someone explain what is going on here.

About half my machines are acting this way. I am probably doing something silly but it seems off.

Adding x500 addresses to multiple user objects using CSV input file

$
0
0

Hello

I need to add an x500 entry containing the legacy DN from our previous mail provider to the proxy address attribute for all our AD users.

I'm using a CSV file with the following format

user,legacy
rlanden,rlandenda3

I used the following powershell line to add the x500 entry:

Import-CSV d:\LegacyDN_input_list.csv | foreach{Set-ADuser -identity $_.user -add @{proxyAddresses = "X500:/o=mex05/ou=Exchange Administrative Group/cn=Recipients/cn=$_.legacy"}}

The X500 record was added to the objects but not as i wanted it, it turned out like this

/o=mex05/ou=Exchange Administrative Group/cn=Recipients/cn=@{user=rlanden; legacy=rlandenda3}.legacy

Could someone help explain why the output has ended up like this and how I can correct it.

Thanks,

Richard

powershell script to change all users proxy address attribute

$
0
0
We are adding an additional domain for email for all users. Using the script below works for one user but, is there a way to change all users at once. The name portion would have to reflect the users name but the domain section would be the same for all users. Also we are not using an exchange server.
$user =Get-ADUserGlenJohn-Properties mail,department,ProxyAddresses
$user.ProxyAddresses="glen@fabrikam.com"Set-ADUser-instance $user 

Get-WmiObject Win32_Service for a list of services

$
0
0

I would like to get the details on services, using a list of services.

This returns all the services on a server: 

Get-WmiObject Win32_Service | Format-Table Name, DisplayName, State, StartMode, StartName


I would like to return only the services defined in a list.  I tried this:

Get-WmiObject Win32_Service -Name (get-content P:\Data\SQLservices.txt) | Format-Table Name, DisplayName, State, StartMode, StartName


But receive this error:

Get-WmiObject : Cannot convert 'System.Object[]' to the type 'System.String' required by parameter 'Namespace'. Specified method is not supported.
At line:1 char:34
+ Get-WmiObject Win32_Service -Name <<<<  (get-content P:\Data\SQLservices.txt) | Format-Table Name, DisplayName, State, StartMode, StartName
    + CategoryInfo          : InvalidArgument: (:) [Get-WmiObject], ParameterBindingException
    + FullyQualifiedErrorId : CannotConvertArgument,Microsoft.PowerShell.Commands.GetWmiObjectCommand

Any suggestions??


-Al H


a PowerShell command that will recursively pull up all the groups that a user is part of

$
0
0

I found a good powershell command that will specifically list all  security groups a member is part of.

For example  John is part of the groupA, GroupB, GroupC.   

I  however was trying to add the recursive command to this because I want it to drill down further and tell me something like

john is part of groupA, GroupB, GroupC, and Group A is part of GroupD, and GroupE, ect...

I thought the -recursive command might work but I tried adding it all over and everywhere I add it I get different errors such as a parameter cannot be found that matches parameter name 'recursive'

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

PS C:\Windows\system32> Get-ADUser user.name -Properties MemberOf | Select -ExpandProperty memberof | Get-ADGroup -Properties name | Where { $_.GroupCategory -eq 'Security'} | Select -ExpandProperty Name

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

awhile back I had some command which listed all the groups inside of other groups but excluded usernames and only did groups such as distributing group or security group, but for the life of me I cannot find that cmdlet or remember what it was.

Anyone know a simple cmdlet that does what I am asking in the general since?


Powershell do while loop that runs unitl I do a CTRL C

$
0
0
All,

I am confused on how to exactly run a while true loop.  Essentially I would like to run this command repeatedly (every second) until I cancel it out.

EX. - > get-WmiObject -class Win32_printer | select name" 

Something like this below

while true ; do (get-WmiObject -class Win32_printer | select name) |start-sleep 5;done  **** I know syntax and layout of this is wrong....I am thoroughly confused.

Thanks for the help.
Rob.

Thank you for your help and time, Robert Jaudon

Filter out Get-WmiObject Win32_service for a list of services

$
0
0

For monitoring purposes I would like to filter out the results of the script below.

I would like to be able to specify a list of exceptions (of services) which I don't want to have in my results. This is my script.  Can anyone help me to filter these services out?

List of services I would like to filter out:

Service Portable Device Enumerator Service
Service Shell Hardware Detection
Service Office Software Protection Platform
Service WinHTTP Web Proxy Auto-Discovery Service
Service Diagnostic System Host
Service Microsoft Software Shadow Copy Provider
Service Volume Shadow Copy

My script:

# First, fetch the list of auto started services
$colItems = Get-WmiObject Win32_Service | where-object { $_.StartMode -ne 'Disabled' }
# Output the JSON header
Write-Host "{";
write-host "`t ""data"":[";
write-host

#temp variable
$temp = 1

# For each object in the list of services, print the output of the JSON message with the object properties that we are interessted in
foreach ($objItem in $colItems) {
$exe_dir = $objItem.PathName
$exe_dir = $exe_dir -replace '"?(.+\\).+exe.*','$1'
$exe_dir = $exe_dir -replace '\\','/'

$desc_val = $objItem.Description
$desc_val = $desc_val -replace '\"','@'

if ($temp -eq 0){
Write-Host ",";
}
else{
$temp = 0;
}
$line = " { `"{#SERVICESTATE}`":`"" + $objItem.State + "`", `"{#SERVICEDISPLAY}`":`"" + $objItem.DisplayName + "`", `"{#SERVICENAME}`":`"" + $objItem.Name+ "`", `"{#SERVICEDESC}`":`"" + $desc_val + "`", `"{#SERVICEDIR}`":`"" + $exe_dir + "`" }"
Write-Host -NoNewline $line
}

# Close the JSON message
write-host
write-host
write-host "`t ]";
write-host "}"

Save the content of a text file on to webpage.

$
0
0

After use $notes = Get-Content D:\Notes.txt, I see that $notes still has multiple-line text in it.

When save it after below, the webpage displays single-line text. I tried add <BR/> but not working. Any idea? Thanks.

$ie.Document.getElementById('work_notes').value = $notes


Configuring DHCP information using Powershell

$
0
0

Hi there

I'm a bit of a newbie at PowerShell, and I wanted to ask if you guys could help me with a query I want to run.

Basically, I want to do the following:

1)Query a whole bunch of remote servers, getting their DHCP scope information.  I seem to be able to do this fine using a loop and the Get-DHCPServer4Scope

The result is something like this:

ScopeId         SubnetMask      Name           State    StartRange      EndRange        LeaseDuration               
-------         ----------      ----           -----    ----------      --------        -------------                
192.168.0.0     255.255.255.0   Clients        Active   192.168.0.11    192.168.0.20    8.00:00:00                   
192.168.2.0     255.255.255.0   clients2       Active   192.168.2.1     192.168.2.50    8.00:00:00 

2)The next bit I want is to get all the scope option parameters from the scopes I found above.  Now if I run this command:

Get-DhcpServerv4OptionValue -ComputerName -ScopeId 192.1.1.0, I get the following information which is good:

OptionId   Name            Type       Value                  
--------   ----            ----       -----                
51         Lease           DWord      {691200}                                                           
15         DNS Domain Name String     {xxx.com}                                                      
6          DNS Servers     IPv4Add... {192.168.0.1}

But how do I specify it that it gets ALL the ScopeIds, considering that I wouldn't know all their IDs if I automate it...

I've looked through examples, and they all seem to specify knowing the ScopeID itself.  There is a -all switch, but it doesn't seem to apply to this.

Any help would be appreciated!

Thanks

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.

Avoid newline without write-host

$
0
0

Hi, Developer,

How to avoid newline without write-host in script as below?

........ | ForEach {  $_.value+"," } | Out-File -FilePath done.csv -Encoding OEM

Or

........ | ForEach { "$_.," } | Out-File -FilePath done.csv -Encoding OEM

Thanks


'System.Management.Automation.Remoting.PSRemotingTransportException' occurred in System.Management.Automation.dll

$
0
0

I am using below code for opening a runspace on server machine.

using (this.impersonator.CreateContext()) // using for impersonation
            {
                string remoteManagementPort = this.TryGetRemotePowershellPort("ServerName");// port is coming fine from server

                    WSManConnectionInfo connectionInfo = new WSManConnectionInfo(http://"ServerName":"PortNumber"/wsman);
                    connectionInfo.AuthenticationMechanism = AuthenticationMechanism.Kerberos;
                    connectionInfo.OperationTimeout = 2 * 60 * 1000;    // 2 minutes.
                    connectionInfo.OpenTimeout = 1 * 60 * 1000;         // 1 minute.

                    this.runSpace= RunspaceFactory.CreateRunspace(connectionInfo); // working fine. Able to create Runspace
                    this.runSpace.ApartmentState = Threading.ApartmentState.STA;
                    this.runSpace.ThreadOptions = PSThreadOptions.UseCurrentThread;
                    this.runSpace.Open();  // Here I am getting this Exception. 
                    this.IsInitialized = true;
                }
            }

Exception:

An unhandled exception of type 'System.Management.Automation.Remoting.PSRemotingTransportException' occurred in System.Management.Automation.dll

Additional information: Processing data from remote server failed with the following error message: Access is denied. For more information, see the about_Remote_Troubleshooting Help topic.

Note: I am getting this exception when My web application sits at windows 2k8  R2 (Powershell Version 2.0) and Remote Server is on windows 2012 server (powershell Version 3.0).

It is working if I update the powershell version 2.0 to version 3.0 on client machine.

I didn't get anything saying that there is an issue with v2.0 to v3.0 connections. 

Can someone please give me any guidance why it is not working with v2 and v3?

Foreach Output to CSV

$
0
0

Hi developer,

I have a written a script but i have no idea how to the foreach output loop to csv file.

Script is below:

$regex = "([A-Za-z])\w+|\d+"
$matchInfo = @((Get-Content \test.txt) |Select-String -Pattern  $regex -AllMatches))

$output = foreach($minfo in $matchInfo)
{
    foreach($match in @($minfo.Matches | Foreach {$_.Groups[0].value}))
    {
        Write-host -NoNewline "$match,"
    }
    Write-Host ""
}$output | ???????

I tried this:
$output | Out-File -FilePath Test.csv -Encoding OEM

So i opened the Test.csv and no data. it is empty.

Any Idea?
Thanks




Powershell script running as Scheduled Task not able to get the Window of a process

$
0
0

Hi all,

I need Powershell to check for the main window opened by an existing process with a given process ID. I used the following command to do so:-

$title = (Get-Process -Id $processId).MainWindowTitle

I tested this by manually invoking it using Powershell and Powershell ISE, and it works great in both.

However when I set this to run as a Scheduled Task using the same parameters, the script is able to detect the presence of the process. However it returns blank for MainWindowTitle. 

The process I'm tracking is NOT the explorer.exe. Clarifying this because I researched that there is some oddities when it comes to detecting windows opened by this process. I'm detecting the process for Windows Photo Editor.

Anyone has any ideas why this is so? Is there any other ways to successfully do this? 

Thanks in advance for any suggestions!

employeenumber behaving strange ? ? ?

$
0
0

I run : get-aduser -filter 'samaccountname -eq "xxx"' -properties employeenumber on different user's

In the Attribute Editor I can see that they both have an employeenumber, nevertheless one user displays the number + a field Enabled : True

The other displays employeenumber as blank/null and does not show the enabled field

Anybody with an idea ?

Diskpart Replacement

$
0
0

We have some disk as part of our provisioning process that needs to have the disk id changed for clustering.  We have a script that was a powershell/diskpart hybrid, but is pretty unreliable.  what i want to change is the Disk ID that shows when you do a detail disk.  the diskpart command is "uniqueid disk id=newid".

i'm looking for the powershell equivalent, but can't seem to find it.  any help is greatly appreciated.

Thanks.

Viewing all 21975 articles
Browse latest View live


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