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

WinRM MaxMemoryPerShellMB value

$
0
0

Apologies if this is in the wrong Forum; it's related to remote PS sessions so I thought I'd start here.

I am trying to increase the amount of RAM I have for my remote Exchange sessions (new-pssession -configurationName Microsoft.Exchange). When I access the WinRM config on both the client machine as well as the target Exchange server I see that many values are all identical and all obnoxiously high:

    AllowRemoteShellAccess = true
    IdleTimeout = 7200000
    MaxConcurrentUsers = 2147483647
    MaxShellRunTime = 2147483647
    MaxProcessesPerShell = 2147483647MaxMemoryPerShellMB = 2147483647
    MaxShellsPerUser = 2147483647

Those look like a default or undefined value which makes me wonder what the actual memory limit is; I very much doubt it's unlimited and I can't believe it's what is there now. Is there a way to tell what the actual limit is currently? I'm guessing it's buried in some config file somewhere. I'm concerned about just arbitrarily specifying a value and having it be too low.


Merge 2 CSV files

$
0
0

Hello Guys!

I need to merge 2 CSV files into a single CSV file, as an example below using PowerShell

CSV01

Column A           Column B

Name               SamAccountName

Name01            name.01

Name02            name.02

Name03            name.03

CSV02

Column A

Hostname

HostName01

Hostname02

Hostname03

I need column A of CSV02 to be inserted in column C of CSV01 as an example bellow

New Merged CSV

Column A          Column B               Column C

Name               SamAccountName    Hostname

Name01            name.01                 Hostname01

Name02            name.02                 Hostname02

Name03            name.03                Hostname03

can you help me ? I've tried several Scripts but so far without success

FTP Download PowerShell Script

$
0
0

I am attempting to download a file from an ftp site, but am getting an error from the script:

$Username = "User"
$Password = "P@$$w0rd"
$Date = Get-Date
$DateName = $Date.ToString("yyyyMMdd")
$FileName = "voloridge_" + $DateName + ".zip"
$RemoteFile = "ftp://ftp-data.ftp.com/" + $FileName
$LocalFile = "\\server1\data\"+$FileName
$FileName
$FTPRequest = [System.Net.FtpWebRequest]::Create($RemoteFile)
$FTPRequest.Credentials = New-Object System.Net.NetworkCredential($Username,$Password)
$FTPRequest.Method = [System.Net.WebRequestMethods+Ftp]::DownloadFile
$FTPRequest.UseBinary = $true
$FTPRequest.KeepAlive = $false
# Send the ftp request
$FTPResponse = $FTPRequest.GetResponse()
# Get a download stream from the server response
$ResponseStream = $FTPResponse.GetResponseStream()
# Create the target file on the local system and the download buffer
$LocalFileFile = New-Object IO.FileStream ($LocalFile,[IO.FileMode]::Create)
[byte[]]$ReadBuffer = New-Object byte[] 1024
do {
$ReadLength = $ResponseStream.Read($ReadBuffer,0,1024)
$LocalFile.Write($ReadBuffer,0,$ReadLength)
}
while ($ReadLength -ne 0)

The error is:

Exception calling "GetResponse" with "0" argument(s): "The remote server returned an error: (530) Not logged in."

At ps1:15 char:1
+ $FTPResponse = $FTPRequest.GetResponse()
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : NotSpecified: (:) [], MethodInvocationException
    + FullyQualifiedErrorId : WebException

Any help would be greatly appreciated.


David Dye My Blog

Get-WmiObject : The RPC server is unavailable - 0x800706BA

$
0
0
Source:
https://docs.microsoft.com/en-us/archive/blogs/ashleymcglone/powershell-remoting-kerberos-double-hop-solved-securely 
Info:
localhost = Windows 10

ServerA = Server 2012 R2
ServerB = Server 2016

Windows firewall is turned off for all machines.
$user is localadmin on all machines.
TCP 5985 and TCP 5986 is opened up and allowed on ServerA and ServerB from localhost.
WinRM-service is started on ServerA and ServerB.

Part of script (the end-result is to do a kerberos double-hop securely without using CredSSP):

# Set up variables for reuse            
$ServerA = $env:COMPUTERNAME            
$ServerB = Get-ADComputer -Identity ServerA    
$ServerC = Get-ADComputer -Identity ServerB  

# Capture a credential  
$user = whoami          
$usercred = Get-Credential $user          
# Notice the StartName property of the WinRM Service: NT AUTHORITY\NetworkService            
# This looks like the ServerB computer account when accessing other servers over the network.            
$test = Get-WmiObject -Class Win32_Service -Filter 'Name="winrm"' -ComputerName "$($ServerB.name).domain.local" | fl *

also tried this

$test = Get-WmiObject -Class Win32_Service -Filter 'Name="winrm"' -ComputerName $ServerB.name | fl *

Still get this error though:
Get-WmiObject : The RPC server is unavailable. (Exception from HRESULT: 0x800706BA)

Any ideas?

Best Regards

Remove characters from array output

$
0
0

Hi I am fairly new to Powershell and I'm trying to get some automation going, I have built the below array to capture all software installed in the environment, which will be converted to HTML to upload to a confluence page. The capture itself works fine but always happy to hear better ways of doing this. However, because of certain characters, the automation bit to confluence fails does and I cant for the life of me understand how to remove these characters from the output of the below. ",""()" , "+" Please note I have taken bits from others code to achieve the below so far. The properties that contain the characters are display name and publisher.

$computers = Get-ADComputer -Filter 'operatingsystem -like "*server*" -and enabled -eq "true"' | Select-Object name

$array = @()

foreach($pc in $computers){

    $computername=$pc.name

    #Define the variable to hold the location of Currently Installed Programs

    $UninstallKey=”SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Uninstall” 

    #Create an instance of the Registry Object and open the HKLM base key

    $reg=[microsoft.win32.registrykey]::OpenRemoteBaseKey(‘LocalMachine’,$computername) 

    #Drill down into the Uninstall key using the OpenSubKey Method

    $regkey=$reg.OpenSubKey($UninstallKey) 

    #Retrieve an array of string that contain all the subkey names

    $subkeys=$regkey.GetSubKeyNames() 

    #Open each Subkey and use GetValue Method to return the required values for each

    foreach($key in $subkeys){

        $thisKey=$UninstallKey+”\\”+$key 

        $thisSubKey=$reg.OpenSubKey($thisKey) 

        $obj = New-Object PSObject

        $obj | Add-Member -MemberType NoteProperty -Name “ComputerName” -Value $computername

        $obj | Add-Member -MemberType NoteProperty -Name “DisplayName” -Value $($thisSubKey.GetValue(“DisplayName”)) -remo

        $obj | Add-Member -MemberType NoteProperty -Name “DisplayVersion” -Value $($thisSubKey.GetValue(“DisplayVersion”))

        #$obj | Add-Member -MemberType NoteProperty -Name “InstallLocation” -Value $($thisSubKey.GetValue(“InstallLocation”))

        $obj | Add-Member -MemberType NoteProperty -Name “Publisher” -Value $($thisSubKey.GetValue(“Publisher”))

        $array += $obj

    } 

}

$array |Where-Object{ $_.DisplayName}| select ComputerName,DisplayName,DisplayVersion,Publisher

PS Remoting Invoke-Command ResourceUnavailable Errors

$
0
0

Hi,

Within the domain, PS remoting is enabled and is working fine for non-administrative users. I can successfully login to other servers in the domain. But when I try to run some of the commands with Invoke-Command, scripts fail with the following error.

 

Cannot connect to CIM server. Access denied 
    + CategoryInfo          : ResourceUnavailable: (MSFT_NetAdapter:String) [Get-NetAdapter], CimJobException
    + FullyQualifiedErrorId : CimJob_BrokenCimSession,Get-NetAdapter
    + PSComputerName        : <HOSTNAME2>

Here is the full powershell script I am trying to run on <HOSTNAME1> with remote session on <HOSTNAME2>.

$password = ConvertTo-SecureString "<PASSWORD>" -AsPlainText -Force
$cred = New-Object System.Management.Automation.PSCredential("<USERNAME>",$password);
$targetServers=@("<HOSTNAME2>")
ForEach($server in $targetServers) {
  $session = New-PSSession $server -Credential $cred
  Invoke-Command -Session $session -ScriptBlock { Get-NetAdapter -Name *eth0* }
}

But the same command (Get-NetAdapter -Name *eth0*) works if I run it on local powershell on <HOSTNAME2>. So my user <USERNAME> has access to run this command.

Similarly if I just try to run the Invoke-Command with another ScriptBlock (e.g. just hostname command) it works. So only some of the commands don't work. Do we need to configure another setting to allow execution of specific commands with Invoke-Command ?

Here is the working version of this script with "hostname" ScriptBlock.

$password = ConvertTo-SecureString "<PASSWORD>" -AsPlainText -Force
$cred = New-Object System.Management.Automation.PSCredential("<USERNAME>",$password);
$targetServers=@("<HOSTNAME2>")
ForEach($server in $targetServers) {
  $session = New-PSSession $server -Credential $cred
  Invoke-Command -Session $session -ScriptBlock { hostname }
}

Thank you.

Exchange Relay Log - Match up FROM and TO based on Sequence Number

$
0
0

Hi,

This is a sample from an Exchange Relay log:

#Fields: date-time,connector-id,session-id,sequence-number,local-endpoint,remote-endpoint,event,data,context
2020-02-10T00:05:03.076Z,EXSRV1\Relay,08D7AAB2E8D53B5B,14,10.103.242.116:25,10.103.241.30:64989,<,MAIL FROM:<email1@domain.com> SIZE=4039,
2020-02-10T00:05:03.076Z,EXSRV1\Relay,08D7AAB2E8D53B5B,16,10.103.242.116:25,10.103.241.30:64989,<,RCPT TO:<email2@domain.com> ORCPT=rfc822;email2@domain.com


The output I would like is this:

FROM: email1@domain.com | TO: email2@domain.com

This is what I have at the moment - this captures EITHER the FROM or RCPT TO values per line, only where the domain matches the one specified in the (mandatory) parameter

param (

    [Parameter(Mandatory=$true)][string[]]$Domain
    
)

$regex = "(MAIL FROM|RCPT TO)\s*:\s*<[A-Za-z0-9._%-]+@$Domain>"

Remove-Item "$env:TEMP\results.txt" -ErrorAction SilentlyContinue

$files = Get-ChildItem -Path "$env:ExchangeInstallPath" -File -Recurse | ? {$_.Extension -Match ".log"}
$files | % {

    Select-String -Path $_.FullName -Pattern $regex -AllMatches | % { $_.Matches } | % { $_.Value } | Out-File "$env:TEMP\results.txt" -Append
}

Get-Content -Path "$env:TEMP\results.txt" | Sort-Object -Unique | Out-File ("{0}_$Domain.csv" -f (Get-Date -Format "yyyy-MM-dd"))


And this currently end with an Excel file, with each email address per row:

email1@domain.com
email2@domain.com

Is this possible natively in PowerShell?

Thanks




How to Search Everyone group & stop at first find then export?

$
0
0

I have the below script to try and get list of folder with everyone group under a certain path.  THis takes forever so I wanted to see if anyone can help me with getting it to stop two folders deep with the everyone group and then export. I just need to know if the everyone group exists at the first and second folder levels and that's it. THanks in advance.

$FolderPath = Get-ChildItem -Directory -Path "\\?\UNC\ehs-pnz-qny-001\MRC\Boston_600_Washington_St" -Recurse -Force
$Output = @()
ForEach ($Folder in $FolderPath) {
    $Acl = Get-Acl -Path $Folder.FullName
    ForEach ($Access in $Acl.Access) {
$Properties = [ordered]@{'Folder Name'=$Folder.FullName;'Identity'=$Access.IdentityReference;'Permissions'=$Access.FileSystemRights}
$Output += New-Object -TypeName PSObject -Property $Properties}}
$Output | Where-Object {$_.Identity -like "Everyone"} | Export-Csv -Path C:\users\svc_robocopy\desktop\MRC-WashST.csv


POWERSHELL


Get-EtwTraceProvider fails on Win10 1909

$
0
0

Hi,I am trying to run the following command as an Administrator on Win10 64-bit 1909. What am I doing wrong?Thanks in advance for your help.

PS C:\WINDOWS\system32> Get-EtwTraceProvider

Get-EtwTraceProvider : Failed to open autologger configuration in the registry.RegOpenKeyEx failed with error 0x5.

At line:1 char:1

+ Get-EtwTraceProvider

+ ~~~~~~~~~~~~~~~~~~~~

    + CategoryInfo          : NotSpecified: (MSFT_EtwTraceProvider:ROOT\Microsoft\...twTraceProvider) [Get-EtwTracePro

   vider], CimException

    + FullyQualifiedErrorId : MI RESULT 1,Get-EtwTraceProvider

PS C:\WINDOWS\system32> $PSVersionTable

Name                           Value

----                           -----

PSVersion                      5.1.18362.752

PSEdition                      Desktop

PSCompatibleVersions           {1.0, 2.0, 3.0, 4.0...}

BuildVersion                   10.0.18362.752

CLRVersion                     4.0.30319.42000

WSManStackVersion              3.0

PSRemotingProtocolVersion      2.3

SerializationVersion           1.1.0.1

PS C:\WINDOWS\system32> ([Security.Principal.WindowsPrincipal] [Security.Principal.WindowsIdentity]::GetCurrent()).IsInRole([Security.Principal.WindowsBuiltInRole]"Administrator")

True

Targetting Get-ACL to a specific domain controller

$
0
0

Hi,

I have a script that creates various OU, security groups, GPO’s and then ties them together by linking the GPO’s and doing some access right delegation on the OU’s and GPO’s.

My problem is (I think) with AD replication.

I create a new OU using this command:

$NewOUDN  = "OU=Security Groups,OU=Region,DC=domain,DC=com"

$FirstDNPart = $NewOUDN.Split(",")[0].substring(3)

$LastDNPart = $NewOUDN.Split(",",2)[1]

New-ADOrganizationalUnit -Name "$FirstDNPart" -Path "$LastDNPart" -ProtectedFromAccidentalDeletion $True -Server $TargetDC -Description "$NewOUDescription"

So far, so good. Then I want to configure some ACE’s. That starts with getting the current ACL list so I run:

$acl = Get-ACL -Path $NewOUDN

The $TargetDC variable will usually not be the same as the logon server my workstation is connected to, so 'usually' (<> always) I get this error message:

Get-ACL : Cannot find path 'OU=Security Groups, OU=Region,DC=domain,DC=com' because it does not exist.

Ideally I would use -Server $TargetDC with the Get-ACL cmdlet, but that switch is not supported.

How do I know which domain controller the Get-ACL cmdlet is using?

How can I make sure the Get-ACL cmdlet is using a specific domain controller?

Any help/suggestions is appreciated.

Thanks!

Ashley.

not able to display array output in color code.

$
0
0

This is small script to get events after last reboot and color code the output depending on it’s error event or not

Function getlastreboottime{
(get-eventlog -LogName System | where {$_.EventID -eq ‘1074’} | select -First 1).TimeGenerated
}

Function GetEventsAfterLastReboot($time){
get-eventlog -LogName System -After $time
}

$LastRebootime = getlastreboottime
Write-host The system was last reboot on $LastRebootime -ForegroundColor Green
$events = GetEventsAfterLastReboot($LastRebootime)
Write-Host Following events after last reboot. The error evens are marked in RED -ForegroundColor Green

foreach ($event in $events){
if ($event.entrytype -eq ‘Error’){
write-host $event -ForegroundColor red
}
else {(write-host $a -ForegroundColor Green)
}
}

But this is the output.. It is not displaying the the event details

please help me.

The system was last reboot on 13-05-2020 18:20:31
Following events after last reboot. The error evens are marked in RED
System.Diagnostics.EventLogEntry
System.Diagnostics.EventLogEntry
System.Diagnostics.EventLogEntry

How to get all the computer names under a child OU via powershell

$
0
0

Hi guys,

Get-ADComputer -SearchBase "OU=One,dc=test,dc=com" -Filter *| Select-Object name >D:\One.csv

Using the above command, I can get all the computer names under OU=One and the child OUs, but actually I only need to get all the computer names under One\computers\office

I refer to the below links 

https://docs.microsoft.com/en-us/powershell/module/addsadministration/get-adcomputer?view=win10-ps

https://adamtheautomator.com/get-adcomputer-powershell/

Still can't got it

Can anyone tell me what I missed

Thank you in advance


Watch path and run command if changed

$
0
0

Below script will watch path and run command for if rename event occurred on path. This script is working, however on random mode, not picking file to run as per sequential order (should pick oldest files to newest renamed time stamp). Tried googling gone through some scripts, was able to achieve until this, final part is to pick a file according to oldest to newest order. Please help to organize it accordingly. 

### SET FOLDER TO WATCH + FILES TO WATCH + SUBFOLDERS YES/NO
    $watcher = New-Object System.IO.FileSystemWatcher
    $watcher.Path = "C:\test"
    $watcher.Filter = "*.host1.txt"
    $watcher.IncludeSubdirectories = $false
    $watcher.EnableRaisingEvents = $true  

    ### DEFINE ACTIONS AFTER AN EVENT IS DETECTED
    $action = { $path = $Event.SourceEventArgs.FullPath
$filename = [io.path]::GetFileNameWithoutExtension($path)
$length = $filename.length
$filename=$filename.substring(0,$length-6)
                ###$changeType = $Event.SourceEventArgs.ChangeType
                ###$logline = "$(Get-Date), $changeType, $path, $filename"
                ###Add-content "D:\log.txt" -value $logline
                $proc=start-process ""C:\test\$filename.bat" -Wait

Remove-Item -Path ""C:\test\$filename.host1.txt"
              }    
### DECIDE WHICH EVENTS SHOULD BE WATCHED 
  ###  Register-ObjectEvent $watcher "Created" -Action $action
 ###  Register-ObjectEvent $watcher "Changed" -Action $action
 ###   Register-ObjectEvent $watcher "Deleted" -Action $action
   Register-ObjectEvent $watcher "Renamed" -Action $action
    while ($true) {sleep 5}

  

Anil Suthar

new user, completely lost

$
0
0

Powershell Invoke-Command -ScriptBlock {$OBJ = ""C:\Users\USR\Documents\Ancestry"" $SDDL = Get-Acl "$OBJ" $SDDL.GetSecurityDescriptorSddlForm('All') > ""C:\Users\USR\Desktop\SSDL.txt"" } 

I am building a powershell script from lua 5.1

what I want is the Sddl when I send in a Directory, File, ... whatever.

eventually (and the only way I can get it to run at all using luacom (nothing else to use...) is:

Shell:Run('CMD /C ' .. cmd, 0, true)

where cmd is equal to the powershell invoke....

this is my output file. 

You cannot call a method on a null-valued expression.
At line:1 char:30
+ ... criptBlock {$OBJ = C:\Users\USR\Documents\Ancestry $SDDL = Get-Acl $O ...
+                 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : InvalidOperation: (:) [], RuntimeException
    + FullyQualifiedErrorId : InvokeMethodOnNull
 

I see that there is a PSobject discussion that indicates that is my error (I have to objectify it), and I have read those documents for days and cannot make heads nor tails of them.

So that is either my problem, or it isnt.  But in the end, everything needs to be in the script bock, anyone got a fix so that I can go back and read the docs on what the fix means? LOL.   Ron


Access to the path is denied

$
0
0
In both windows and developer powershell it says I don't have access to the path even when I run as administrator.

Select-String -Path C:\Users\user\Downloads\temp  -Pattern 'Really'
Select-String : The file C:\Users\user\Downloads\temp cannot be read: Access to the path
'C:\Users\user\Downloads\temp' is denied.
At line:1 char:1
+ Select-String -Path C:\Users\user\Downloads\temp  -Pattern 'Really'
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : InvalidArgument: (:) [Select-String], ArgumentException
    + FullyQualifiedErrorId : ProcessingFile,Microsoft.PowerShell.Commands.SelectStringCommand

ComObject fails, Access Denied, saving Outlook message

$
0
0

Not sure this forum is the best place for this, but it does start in PowerShell...

My script does some stuff with Oultook and at the point of this issue, I have an Outlook message object, mailItem.

When I invoke the .SaveAs method I get an error that the output fails, Access Denied, implying the target folder has insufficient permissions.  The error is clear/verbose and even includes instructions to resolve:

Cannot write to file: C:\PS\Outlook\MessagesByAge\MsgArchive. Right-click the folder that contains the file you want to write to, and then click Properties on the shortcut menu to check your permissions for the folder.

The target folder exists and Everyone and Authenticated Users have full NTFS permissions.

Any thoughts?

BTW, calling .SaveAs with the path and Type = 3, olMSG.

take input from JSON file store value and perform action

$
0
0

i Have JSON file where all configration value store, Value Like 

  • package version 
  • Download like of package 
  • Install Folder 
  • Prerequisite for package 

like these kind of value or more

Which we need to perform further action of script, Now how can i read value 

we have ConvertFrom-Json and Convertto-Json these to method, but using powershell how can i call value and perform action 

like if i need to check package version how can i, or if i need to download package how can i



Biren

Disable password never expire and password reset

$
0
0

Hi,

I want to disable password never expire on list of users and reset their password. i am unable to find the command for this. can any one guide me for this?

regards

Kashan Nawaz

Installed PowerShell version

$
0
0

Hi All , 

I was trying to learn more about the new PowerShell 7 and it's features , Then i realized that my laptop which was recently imaged have version 5.1 although the Windows build is the latest.

I'm just confused , why Windows doesn't have at least PowerShell 6 by default since it was released a while back ? 

I'm asking that because if i want write a script that will run on other windows machines I need to worry about the PS version on those machines 

Thoughts ?

PowerShell remoting - Remoting Management Users

$
0
0

Hi, I have created a script to generate HTML report of all certificates expiring within next 30 days on all servers in our forest (2 domains) - it uses PowerShell remoting. That script will run as PowerShell scheduled task - now it is a question which account scheduled task will run under. It should have some delegated rights on machine scheduled task will run on but also on all target servers in the forest including 10 domain controllers. I have tried to avoid account being member of local admin group on member servers and domain admin group as well - instead I put it in Remote Management Usersgroups (local group on test server & domain local group in AD) and gave it a try. From both test member server & test DC I was able to pull expiring certificates.

My questions are:

  1. By default, which rights/permissions on given member server/DC do members of Remote Management Users have - obviously they can connect via Invoke-Command ... but I hope they can not do some major system-wide changes (both on member servers and let alone in Active Directory)?
  2. To make this even more secure Group Managed Service Account should be good candidate for account scheduled task will run under (being member ofRemote Management Users group on all member servers/DCs)? Since its password is centrally managed all target systems should have permission to retrieve it so I would need to create domain local group and put groups containing all servers in the forest and then give permission to that group with Set-ADServiceAccount by using it as value for PrincipalsAllowedToRetrieveManagedPasswordparameter?

Thank you very much in advance.

Viewing all 21975 articles
Browse latest View live


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