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

google chrome script for auto refresh/reload for single tab

$
0
0

I am trying to have a powershell in order to automatically refresh google chrome tab , the below script works fine but it refreshes all tab , can you help 

while(1 -eq 1){ 
        $wshell=New-Object -ComObject wscript.shell; 
        $wshell.AppActivate('Google Chrome'); # Activate on Google Chrome 
        Sleep 10; # Interval (in seconds) 
                $wshell.SendKeys('{F5}'); # F5 to refresh active page 
}1

Searching for Duplicate User (duplicate Surname and Firstname)

$
0
0

Hi all,

I am looking for a way to find users with a duplicate SamAccountName/Name/Name/UPN... basically if a user has 2 or more accounts (excluding admin accounts). The way I am checking it now is by creating a CSV file with users filtered on duplicated Surnames (and excluding some OU's which contain Removed Accounts and Administration Accounts).

So that part is fixed, but now I have to manually check the Surnames to see if it has a duplicate Firstname (GivenName). Could you help me find a way to put this in Powershell as well?

I was thinking of a solution like: If Surname and Givenname -eq 1; then show results…

This is my code so far:

$users = Get-ADUser -Filter {(SN -like "a*")} -Properties SN
$filteredOU = $users | Where-Object -FilterScript { ($_.distinguishedname -notlike '*LSA*') -and ($_.distinguishedname -notlike '*Removed*') -and ($_.distinguishedname -notlike '*Disabled*') }
$idLookup = $filteredOU | ForEach-Object { $idLookup = @{} } { if($_.Surname) { $idLookup[$_.Surname] += 1 } } { $idLookup }
$filteredUsers = $filteredOU | Where-Object { if($_.Surname) { $idLookup[$_.Surname] -gt 1 } }
$filteredUsers | Select-Object -Property SN, Givenname, Name, DistinguishedName | Sort-object -property SN |
Export-Csv -Path H:\Test\Duplicate_ADusers4.csv -NoTypeInformation

Feel free to correct me and make the code much better, as i am in an early stage of learning Powershell.

Thanks in advance.

Add text to file

$
0
0

Hi

I am trying to get the content of a file or multiple files, if a pattern exists within the files, i want to start a new line after the pattern, and then add some content. Below is what i have started with, any help or advice would be great. I want to add the line at the bottom after the pattern, but i am stuck.

$IKey = xxxxxx-xxxxxx-xxxxxx-xxxxxx-xxxxxxx
$fileName = "C:\TempPath\ApplicationInsights.config"
$content = "<InstrumentationKey>$IKey</InstrumentationKey>"
$line = <ApplicationInsights xmlns="http://schemas.microsoft.com/ApplicationInsights/2013/Settings">
Get-Content $fileName | 
    Foreach-Object {
        if ($_ -match $line) 
        {
            Add-content $fileName "`n$content"
        }



Thanks

Shane


Random Powershell output files in c:\windows\temp

$
0
0

Hi all.  I am having a weird issue that I do not understand.  I have a 2012 r2 server running Powershell 5.1.  The c drive on this server filled up.  During troubleshooting a bunch of large text files (aaoXXXX where x are random numbers) were discovered that contained output from the powershell console from different scripts that are running on this server.  The strange part is the output in the temp file contains output from a write-host command, start-job output, receive-job output, and string contents of a variable with write-output.  In the script itself, it outputs only the string contents of a variable through write-eventlog.  No other content is written outside of the powershell console.  How does Powershell generate this temp file? Why does powershell generate this temp file and how do I configure powershell not to generate this content.

Thanks in advanced

How can I have my script running in the background continuously?

$
0
0
I have the following powershell script that sends an email whenever a new file is created/copied to a specific folder.
the only problem that I am facing is that whenever I close the powershell window, the script stops working!
I need the script to work in the background, even when I am logged off the server. How can I achieve this.
I am running Windows Server 2012 R2

  

    $folder = "C:\temp"
    $mailserver = "172.33.33.33"
    $recipient = "any@ddress.com"

    $fsw = New-Object System.IO.FileSystemWatcher $folder -Property @{
       IncludeSubdirectories = $true
       NotifyFilter = [IO.NotifyFilters]'FileName'
    }

    $created = Register-ObjectEvent $fsw -EventName Created -Action {
       $item = Get-Item $eventArgs.FullPath
       $s = New-Object System.Security.SecureString
       $anon = New-Object System.Management.Automation.PSCredential ("NT 
        AUTHORITY\ANONYMOUS LOGON", $s)
      Send-MailMessage -To $recipient `
                   -From "ann@ddress.com" `
                    -Subject “KCC File Downloaded” `
                    -Body "Hi Everyone" `
                    -SmtpServer $mailserver `
                    -Credential $anon
      } 

Script to find all groups with nested groups as members

$
0
0

Hello everyone,

I am looking for a script that will only list AD groups with group(s) as members and all the nested groups names within them

Output would be something like:

Group1

     Nested1

Group2

    Nested2

          nested3

etc..

Thank you in advance.

Right click copy from shell

$
0
0

Similar to this article,

https://social.technet.microsoft.com/Forums/en-US/022b57db-02d7-4446-8542-2dc4052f4a9b/windows-context-menu-item-rename-file-with-random-hash-pipeline-expression-error?forum=winserverpowershell

I want to create a right click Backup File shell option.

I have this thus far,

C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe -NoExit -NoProfile -NonInteractive -Command "Get-ChildItem %1 | ForEach-Object {Copy-Item -path $_.fullname -destination ($_.DirectoryName + '\' + $_.Basename + '_' + @(Get-Date -uformat "%Y%m%d-%H%M%S") + $_.Extension)}"

I can run the command in raw Powershell console by changing the %1 to a hard path\file and it works fine.

When I add it to a shell command in HKCR\*\shell\<my command> Powershell complains that my path is wrong on the copy-item

This is the error I get:

Copy-Item : The given path's format is not supported.
At line:1 char:68
+ ... ach-Object {Copy-Item -path $_.fullname -destination ($_.DirectoryNam ...
+                 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : NotSpecified: (:) [Copy-Item], NotSupportedException
    + FullyQualifiedErrorId : System.NotSupportedException,Microsoft.PowerShell.Commands.CopyItemCommand

An example of what it does is copies a file named backup.reg and calls it backup_20190418-162708.reg

Convenient if you want to make a copy of a file and add the date and time to the copy.

Does the shell component get upset with the use of %, ", $ or @?

Not able to Execute Remote PowerShell from Java through Linux server

$
0
0


I have a simple PowerShell script present under remote Window Server at location C:\IAM\Skype\checkPowerShell.ps1

Under the checkPowerShell.ps1, I have written below command:

New-item C:\Users\test_iam\tempfolder -itemType directory

I am using dependent jar : jsch-0.1.55.jar and Wrote below Code: 


import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.Properties;


import com.jcraft.jsch.Channel;
import com.jcraft.jsch.ChannelExec;
import com.jcraft.jsch.JSch;
import com.jcraft.jsch.Session;


public class SkypeProvision {
    public SkypeProvision() {
        super();
    }
        public static void main(String[] args) {

                try
                {

                        String command = "powershell.exe  \"C:\\IAM\\Skype\\checkPowerShell.ps1\" ";

                //      String command =  "Powershell.exe C:/IAM/Skype/checkPowerShell.ps1";

            String host = "*.*.*.*";  

// Hide the hostname, User, Password knowingly 

            String user = "******";
            String password = "*******";

            JSch jsch = new JSch();
            Session session = jsch.getSession(user, host, 22);
            Properties config = new Properties();
            config.put("StrictHostKeyChecking", "no");
            session.setConfig(config);;
            session.setPassword(password);
            session.connect();

            Channel channel = session.openChannel("exec");


            ((ChannelExec)channel).setCommand(command);
            channel.setInputStream(null);
            ((ChannelExec)channel).setErrStream(System.err);

            InputStream input = channel.getInputStream();
            channel.connect();

            System.out.println("Channel Connected to machine " + host + " server with command: " + command );

            try{
                InputStreamReader inputReader = new InputStreamReader(input);
                BufferedReader bufferedReader = new BufferedReader(inputReader);
                String line = null;

                while((line = bufferedReader.readLine()) != null){
                    System.out.println(line);
                }
                bufferedReader.close();
                inputReader.close();
            }catch(IOException ex){
                ex.printStackTrace();
            }

            channel.disconnect();
            session.disconnect();
        }catch(Exception ex){
            ex.printStackTrace();
        }
    }
}

Created the jar file and running using  below command from remote server

#javac -cp jsch-0.1.55.jar SkypeProvision.java

# jar -cvf SkypeProvision.jar SkypeProvision.class

# java -cp SkypeProvision.jar:jsch-0.1.55.jar SkypeProvision

It runs the jar file without any issue and give output:

Channel Connected to machine ****** server with command: powershell.exe  "C:\IAM\Skype\checkPowerShell.ps1"

But it doesn't perform any function on Remote Window server.

Can anyone please help.????


Login script ran as admin

$
0
0

I have created a small powershell script that I have added using GPA to run during login or users. Problem is that it works fine for admin accounts but not for normal users. Is there a way to force this script to run as admin each time?

I've searched and found a few saying to use scheduled task instead but I have a message box that needs to appear as a warning for certain event that seem to make it hang if using as tasks.

disabling password complexity via powershell

$
0
0

hi friends

i spent lots of time searching entire internet to find a command or script (powershell, cmd, VB, registry...) to be able to disable password complexity. there are few solutions which none of them works.

i wonder how what a pity if we can't do such simple thing in Microsoft windows

i really need that because i have created a script which contains many lines which automates windows customization which i always need in my classrooms for testing & teaching purposes

thanks for any help

pipeline error when creating a script to change teams upgrade policy

$
0
0

Hello, 

I am relatively new to creating powershell content, although I have been a user for some time. I have been asked to modify a script that drops a single user into the teams upgrade policy group into one that can do batches of users at one time. 

Here is the original functioning script

Import-Module SkypeOnlineConnector
$sfbSession = New-CsOnlineSession
Import-PSSession $sfbSession
$credential = Get-Credential
$session = New-CsOnlineSession -Credential $credential -Verbose
Import-PSSession $session
Grant-CsTeamsupgradePolicy -Identity mfa.test@domain.com -PolicyName upgradetoteams

here is the modified one as it currently sits

Import-Module SkypeOnlineConnector -scope currentuser

Import-CSv -Path "C:\scriptpath\GlobalProtect_Import.csv" 
| ForEach { $UPN=$_.UserPrincipalName


$sfbSession = New-CsOnlineSession 
Import-PSSession $sfbSession 
$credential = Get-Credential 
$session = New-CsOnlineSession -Credential $credential -Verbose 
Import-PSSession $session 
Grant-CsTeamsupgradePolicy -Identity $UPN -PolicyName upgradetoteams }

this is the error I get when I try to run it. 

At C:\scriptpath\Teams_Upgrade.ps1:6 char:1
+ | ForEach { $UPN=$_.UserPrincipalName
+ ~
An empty pipe element is not allowed.
    + CategoryInfo          : ParserError: (:) [], ParentContainsErrorRecordException
    + FullyQualifiedErrorId : EmptyPipeElement

Can anyone tell me what character seems to be missing or where the issue lies in this script?

Cannot remove acl after disabled inherit

$
0
0

I am trying to remove network folder permission recently, below script is working normally on the most of folders.

Here is my scenario:

1. I was generated a folder report including folder path, object name and permission. (ignore domain pls)

2. I have disabled inherit from parent by using below script and it works:

$acl = Get-Acl -Path $Path
$acl.SetAccessRuleProtection($True,$True)
Set-Acl -Path $Path -AclObject $acl
3. To remove folder access, i will use below script and it is working normally on the most of folders:
$AccessRule = New-Object System.Security.AccessControl.FileSystemAccessRule($Obj,$Access,,,"Allow")
$acl = Get-Acl $Path $acl.RemoveAccessRuleAll($AccessRule)
Set-Acl -Path $Path -AclObject $acl

4. Somehow i cannot remove an access from a folder, after manual checking, the folder has been disabled inherit from parent by using #2 script.

5. After failed to remove access by script, i try to remove it by manual, and it works.

6. There have over than 100,000+ access have to remove but unfortunately above script is not working for those folders, and those folders has been disabled inherit from parent.

7. I was tried to create the same access to the same folder by using below script:

$acl = Get-Acl $Path
$args = "$Obj","ReadAndExecute","ContainerInherit,ObjectInherit","None","Allow"
$AccessRule = New-Object System.Security.AccessControl.FileSystemAccessRule $args 
$acl.SetAccessRule($AccessRule)
$acl | Set-Acl $Path

   After creation, it is showing the two same access in the folder.

8. After that i use the remove script #3 again, and then only 1 access exists now. (The new added access has removed but the same old access still remain)

9. I have checked the folder access by using below script, all the words is exactly same as #7 $AccessRule, i run #7 script again but the access still remain and nothing changed.

$acl = Get-Acl $Path

$acl.Access

Question:

How can i remove folder access in this scenario? Or what should i go to check by using PowerShell?

o365 licenses question

$
0
0

Kinda new to powershell.

I’m trying to get a list of o365 users that have an enterprise pack license.

So I started with this command:

Get-MsolUser -UserPrincipalName <user> | Format-List DisplayName,licenses

And got this back:

DisplayName : <user>

Licenses    : {***:ENTERPRISEPACK}

So all good here.

Next I tried this command:

Get-MsolUser -All | where {$_.licenses -eq '***:ENTERPRISEPACK'}

No results. So I tried these variants:

 Get-MsolUser -All | where {$_.licenses -eq '{***:ENTERPRISEPACK}'}

 Get-MsolUser -All | where {$_.licenses -eq {***:ENTERPRISEPACK}}

 Get-MsolUser -All | where {$_.licenses -eq "{***:ENTERPRISEPACK}"}

 Get-MsolUser -All | where {$_.licenses -eq '{***:ENTERPRISEPACK}'}

 Get-MsolUser -All | where {$_.licenses -eq "***:ENTERPRISEPACK"}

No results. So I know I’m doing something wrong, but why won’t this work?


Matthew Kopf

SCCM Device Collection Members TO AD Security Group - Error Cannot find an object with identity: '$'

$
0
0

Anyone have any idea why I would get this error? This One liner Command Script, works perfectly inside the SCCM Powershell Admin Console. However when i connect in by New-PSDrive i get the error below? 

Even if i add the identity along with Distinguished name or SID, I still get the error. 

Any ideas?

(Get-CMDevice -CollectionName "SCCMDeviceCollectionNameHere").name |ForEach-Object{Add-ADGroupMember "ADDGROUPNAMEHERE" -Members $_$ }

Add-ADGroupMember : Cannot find an object with identity: '$' under: 'DC=sub,DC=domain,DC=com'.
At C:\ADD-ADGroupMember2.ps1:11 char:83+ ... Each-Object{Add-ADGroupMember "ADGROUPNameHere ...+                 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~+ CategoryInfo          : ObjectNotFound: ($:ADPrincipal) [Add-ADGroupMember], ADIdentityNotFoundException+ FullyQualifiedErrorId : SetADGroupMember.ValidateMembersParameter,Microsoft.ActiveDirectory.Management.Commands.AddADGroupMember

problem with format-table cmdlet

$
0
0

Hi

considering the following screenshots i need to know where i am wrong ? why no information is displayed under destination and time columns ?


even using -Autosize didn't have any effect !

Thanks in advanced


Enable PowerShell Remoting problem

$
0
0

Hi!

I installed Evaluation version of Windows 2016 and 2019 Standard. I trying configure PS Remoting and I have problem with it.

System is clear, I installed system and join to domain only. 
After Enable-PSRemoting command I don't have any errors etc. 

When I use winrm command:

PS C:\Windows\system32> winrm quickconfig
WinRM service is already running on this machine.
WinRM is already set up for remote management on this computer.

Firewall is off for all profiles. 

For example bellow command:

PS C:\Windows\system32> Enter-PSSession -ComputerName localhost
Enter-PSSession : Connecting to remote server localhost failed with the following error message : The client cannot con
nect to the destination specified in the request. Verify that the service on the destination is running and is acceptin
g requests. Consult the logs and documentation for the WS-Management service running on the destination, most commonly
IIS or WinRM. If the destination is the WinRM service, run the following command on the destination to analyze and conf
igure the WinRM service: "winrm quickconfig". For more information, see the about_Remote_Troubleshooting Help topic.
At line:1 char:1
+ Enter-PSSession -ComputerName localhost
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : InvalidArgument: (localhost:String) [Enter-PSSession], PSRemotingTransportException
    + FullyQualifiedErrorId : CreateRemoteRunspaceFailed

What I doing wrong?

Thanks for help!

Br,

Paweł




Trouble with Powershell & Named Pipes

$
0
0

I need to get two powershell scripts talking to each other and I'm having trouble.   I have a "Server" script and a "Client" script.  Eventually I will have the server script spawning one or more client scripts and the reading a named pipe for information coming back.

Windows 10, patches and updates are current.

My Server script runs fine and seems to create the named pipe.   For now I'm running the Client script in a separate windows and it too seems to successfully open the pipe and establish a connection - I can see that when the Server script's "WaitForConnection" call returns.

The Client Script seems to run fine although it's hard to tell if anything is really getting written to the pipe.

The Server script hard HANGS on $cmd = $sr.ReadLine();   I have to kill PowerShell ISE to recover. 

Any ideas?   Anything I'm obviously doing wrong?

Server Script

function runCommand {
    param([string]$cmd)
    Write-Host "Command: ", $cmd
}

function runMainServer {

    while (1) {
        Write-Host "Reading pipe...."
        $cmd = $sr.ReadLine();
        if ($cmd -ne 'exit') {
            Write-Host "Processing command...", $cmd;
            runCommand($cmd); 
        } else {break;}
    }

    Write-Host "Exit command received";
}

try {
    $PipeSecurity = new-object System.IO.Pipes.PipeSecurity
    $AccessRule = New-Object System.IO.Pipes.PipeAccessRule( "Everyone", "FullControl", "Allow" )
    $PipeSecurity.AddAccessRule($AccessRule)
    $pipeName = "targetCommands"
    $pipeDir  = [System.IO.Pipes.PipeDirection]::InOut
    $pipeMsg  = [System.IO.Pipes.PipeTransmissionMode]::Message
    $pipeOpti = [System.IO.Pipes.PipeOptions]::Asynchronous
    $pipe = New-Object system.IO.Pipes.NamedPipeServerStream($pipeName, $pipeDir, 1, $pipeMsg, $pipeOpti, 32760, 32760, $PipeSecurity )
    $pipe.WaitForConnection();


#    $pipe=New-Object System.IO.Pipes.NamedPipeServerStream("\\.\pipe\targetCommands");
#    $pipe.WaitForConnection(); 
    Write-Host "Have connection..."
    $sr = new-object System.IO.StreamReader($pipe); 

    $cmd = $sr.ReadLine();
    Write-Host "Processing command", $cmd
}
catch {
    Write-Host "Pipe Creation Failed..."
    $_
    return 0
}

#Start-Process -FilePath "c:\users\shawn\desktop\Thrustmaster Config\Voice\readCommands.ps1"

#runMainServer;
$sr.Dispose();
$pipe.Dispose();

Client Script

function sendCommands {
    begin {
    }
    Process {
        Write-Host "Processing...", $_
        try {
            $sw.WriteLine($_)
            }
        catch {
            Write-Host "Error writing pipe"
            $_
        }
        Write-Host "Done..."
    }
    End {
    }
}

$pipe = new-object System.IO.Pipes.NamedPipeClientStream(".", 'targetCommands', [System.IO.Pipes.PipeDirection]::InOut, [System.IO.Pipes.PipeOptions]::None, [System.Security.Principal.TokenImpersonationLevel]::Impersonation)
$pipe.Connect();  
$sw = new-object System.IO.StreamWriter($pipe);

#$pipe=new-object System.IO.Pipes.NamedPipeClientStream("\\.\pipe\targetCommands");
#$sw = new-object System.IO.StreamWriter($pipe)

$sw.WriteLine("this is a test");
$sw.WriteLine("this is a test");
$sw.WriteLine("this is a test");
$sw.WriteLine("this is a test");
$sw.WriteLine("this is a test");

Get-Content -Path "c:\users\shawn\desktop\speechFile.txt" -tail 0 -Wait | sendCommands


Set ACL

$
0
0

Hello

I have a folder on the server for end-users' archived emails.  Of course each user will only be able to access their own folder.

The foldernames are the same as the SamUserAccount name (first initial, last name).

It appears that all permissions that "were" set on these folders have been destroyed (by copy/move as we were fixing another issue).

So, Now I need to set the permissions on all these folders (approx 400).

The following is needed:

Admins - full controls

Domain Admins - Full Control

Desktop Admins - Full Control

System - Full control

User whose folder it is - Modify

Other domain users - none

Creator Owner - not needed to be listed.

Ex: username: bsmith , foldername: bsmith

Admins -full control, Domain Admins - full control, desktop Admins - full control, System -Full control bsmith - Modify

So far this is what I have:

$EmailArchivePath = "\\Domain\Env\EmailArchive"
$Userlist = Get-ChildItem $EmailArchivePath | Select Name
foreach ($User in $Userlist.name) {
    $Uname = Get-ADUser $User | Select-object -ExpandProperty SamAccountName
    $Userfolder = $user.name
    $ACL1=Get-ACL -path $EmailArchivePath\$UName
            Set-ACL -path $EmailArchivePath\$User.name -AclObject $ACL1
            Add-NTFSAccess -Path $EmailArchivePath\$User.name -Account $Uname -AccessRights Modify
}    

I'm not sure how to add All the access for all the accounts to the Set-ACL

Any suggestions?

Thank You

Terry

O365 Licensing - Export CSV containing licensing information that includes the company field for each user

$
0
0

Has anyone found a way to export O365 licensing to CSV that also includes the 'company' field from AD for each user?  I have been racking my brain on how to get this information solely through Powershell and I am not coming up with anything.  Get-msoluser returns the licensing values that i need, but does not have the company field.  Get-azureaduser/get-aduser has the company field, but i haven't been able to retrieve the licensing data from there.

Any help would be greatly appreciated.

how to give message not helpmessage in $credential heading in params

$
0
0

I want to assign message in credential declaration on very start of cmdlet

for example

param{

[validationNullorEmpty]

[param(mandatory=true, helpmessage="Enter Domain spec cred")]

$credential=[pscredential]::Empty

}

instead of helpmessage I want to add below Message

if ($credential -ne $null){$credential=Get-credential -Message "Add domain cred"}

because when I define function have no $credential then default window it show me the message "enter the credential" that I don't want I want my message "Add domain cred"

Actually this message will appear after first default window, so instead of get-credential default window I want to custom my window with my message, how to do that, instead of help message can I declare -Message in  [param(mandatory=true, -Message="Enter Domain spec cred")] like this

 

 
Viewing all 21975 articles
Browse latest View live


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