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

Overwrite existing file using Out-File

$
0
0

Hi. I am very new to PowerShell scripting. I am trying to overwrite an existing file with date and time in it's file name.

Here is what i'm using.

 $LogName = "Security"
 $EventID = 4725
 $Date = ((get-date).addDays(-1))
 $CurrentDate = Get-Date
 $CurrentDate = $CurrentDate.ToString('MM-dd-yyyy_hh.mm.ss')
 get-eventlog $LogName $EventID -after $Date | Export-CSV $Path -notypeinformation | Out-File -Filepath $Path -Append

However, upon running, it returns with an error that says

Out-File : The process cannot access the file because it is being used by another process

I hope you guys can help me with this. Thanks!


Create SRP Certificate Rules Using PowerShell

$
0
0

I am using Software Restriction Policies (SRP) and want to improve the process of creating certificate rules.  

I've already created a script that can recurse through all the folders on a (safe) computer and extract the x509 certificates (*.cer files) for any signed executables it finds.  However, I still have to manually edit the SRP GPO and add the certificate rules by importing the *.cer files one at a time.  I've looked at the few commandlets in the GroupPolicy module, but none look like they can manipulate individual rules (other the Group Policy Preference registry changes).  Is there a way to create a PowerShell script to import all my *.cer files into a SRP GPO as certificate rules?  Can you point me in the right direction?

Thank you in advance.


--Bill

Password encrypt in powershell

$
0
0

Hi,

How can i encrypt passwords in a powershell script, then call the powershell script and use the encrypted passwords with sqlplus (oracle utilty) to make a connection to the database?

Thanks.

USB devices and USB hub "power management" disabling under device properties.

$
0
0

So the code below works for USB hub and ports, but it does not work for USB Devices.

Can someone help me to modify the code to work on USB devices as well?'

Thank you so much in advance!

$hubs =Get-WmiObjectWin32_USBHub
$powerMgmt =Get-WmiObjectMSPower_DeviceEnable-Namespace root\wmiforeach($p in $powerMgmt){
	$IN = $p.InstanceName.ToUpper()foreach($h in $hubs){
		$PNPDI = $h.PNPDeviceIDif($IN -like "*$PNPDI*"){
                     $p.enable = $False
                     $p.psbase.put()}}}

foreach to check another variable

$
0
0

how to add another check to see if the server "environment = develop" after the role is verified?

foreach ($Package in $Node.Packages)
        {
            $PackageName = "Coresoftware" + $Package.ShortName
            if (($Pack.Role -eq $Node.Role) -or ($Pack.Role -eq $null))
            {
                Write-Verbose "Configure Package $($Package.Name) for roles '$($Pack.Role)' on node with role $($Node.Role)"
                Package $PackageName
                {
                    Name      = $Package.Name
                    Path      = $Package.Path
                    Arguments = $Package.Arguments
                    ProductID = $Package.ProductID
                    Ensure    = "Present"
                }
            }
        }

FileSystemWatcher Crash

$
0
0

I am using System.IO.FileSystemWatcher to monitor a directory on a UNC path.  I have used this quite a bit in other scripts, and never ran into any issues.  However, for the past day or so, I have been getting random crashes.  Today I was running it locally, to try and identify the cause, and was able to reproduce it, and I got the following error.

---------------------------
System.AppDomain
---------------------------
Illegal characters in path.
   at System.IO.Path.CheckInvalidPathChars(String path, Boolean checkAdditional)
   at System.IO.Path.GetFileName(String path)
   at System.IO.FileSystemWatcher.MatchPattern(String relativePath)
   at System.IO.FileSystemWatcher.NotifyFileSystemEventArgs(Int32 action, String name)
   at System.IO.FileSystemWatcher.CompletionStatusChanged(UInt32 errorCode, UInt32 numBytes, NativeOverlapped* overlappedPointer)
   at System.Threading.ExecutionContext.RunInternal(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
   at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
   at System.Threading._IOCompletionCallback.PerformIOCompletionCallback(UInt32 errorCode, UInt32 numBytes, NativeOverlapped* pOVERLAP)

However, the error appears to be happening internal to the Notify event, and I am unable to catch the error with my code to handle it.

Any advice?

Justin


Justin


Re-check the result

$
0
0

Hi,

 Task: get service for each computer, if service stopped, start. Then I would like to recheck and echo the services. How would I recheck? Sorry I am new to powershell. Thank you!

$computersList  = gc computers.txt
$serviceList = gc services.txt

ForEach ($computer in $computersList)
{
    ForEach ($service in $serviceList)
    {
       $result = Get-Service -Name $service -ComputerName $computer
       echo $result
       if ($result.Status -eq "Stopped") {
        $start = $result.Start()
       }
       elseIf ($result.status -eq "Running") {Write-Host -ForegroundColor Yellow $A.name "is running"}
    }
  
}


Tuan

Uninstall all versions of Java (except specified safe versions)

$
0
0

Hi, all - 

I'm struggling with what would appear to be a simple script. All I am trying to do is: 

1: Find all currently installed versions of JRE

2: Loop through that list and compare the Identifyingnumber (GUID) to an array to make sure it isn't contained. The array we are checking in contains GUIDs that we do not want uninstalled.

3: If the GUID is not found, proceed with the uninstall.

Script so far:

#Safe Versions GUIDs
$KeepVersions = @("{26A24AE4-039D-4CA4-87B4-2F83218077F0}"
)

#Detect currently installed JRE versions
$JREVersions = Get-WmiObject -Class Win32_Product -Filter "name like 'Java%'" | select Name, Version, Identifyingnumber


foreach ($version in $JREVersions) {

	if ($KeepVersions -notcontains $JREVersions.Identifyingnumber)
	{
		#Perform Uninstall
	}
	else {
		"Uh oh, this version is protected and cannot be uninstalled. Skipping:"
		$JREVersions.Name
	}
}

Thanks in advance!


Unable to detect whether logged-on user is part of 'local administrator' group

$
0
0

I have the following powershell script that would detect whether a logged-on domain user is part of the 'Local Administrator' group or not. If the user is NOT a local admin, perform additional steps to add the user to the group, else display a message and exit.

#requires -version 4.0
#requires –runasadministrator

function Is-Admin
{
	([Security.Principal.WindowsPrincipal] [Security.Principal.WindowsIdentity]::GetCurrent()).IsInRole([Security.Principal.WindowsBuiltInRole] "Administrator")
}

$CHECK = Is-Admin

if ($CHECK -eq $false)
{
	#User is not Admin

	#perform tasks to add user to local admin group

}
else
{
	#User is already administrator

	#Display message and exit

}

While executing the script with 'Elevated Rights' (i.e. 'Run As Administrator'), the function Is-Adminalways returns TRUE. Even though the logged-on user is not a part of the local administrator group.

What changes do I need to make to the script to achieve this.

Please help.

Thanks


Importing Information and then Changing it

$
0
0

So I am pretty new to Powershell but I've gotten a decent handle on most of it but I do have a question. 

I am attempting to get rid of the scriptpath on all users and have managed to find all Users with the scriptpath "time" and another cmdlet to remove it. My question here is how can I merge the two and have them pull all users and remove what I need to remove?

Would it be piping into each other?

It's a bit confusing on how to get them to merge. Any help would be appreciated to understand that aspect.

 

RPC service restart

$
0
0

Hello every one

i tried to run the command :

Restart-Service rpcSs -force
but it didnt work , in addition i lost my internet connection and the wifi connection !!!

suggestions ??

Duplicate certificate template, edit and publish it

$
0
0
Hi,

I'm trying to duplicate a certificate template using PowerShell, edit it and publish it.
On my Active Directory Server, I added the Certificate Services role and ran the commnadcerttmpl.msc command (View the displayed window).



I need to duplicate the Worstation Authentication certificate template, edit it (Set a name ofSystem Health Authentication and change some other properties) and then publish it by running the commnadcertsrv.msc and add it under Certificate Templates.

I looked alot on the internet about duplicating certificate template / create a new one but I didn't find any thing that could help.

Please, I need your help in order to scipt the above task using PowerShell.
It is very appreciated to send me a sample script.

Regards,
Bader

Using true or false as answer to variable

$
0
0

I have this (part of) a script:
$DName = Read-Host "Please Enter logon initials of the new user "
$HiddenUser = Read-Host "Should user be hidden in mail address lists? Write True or False"
Set-Mailbox -Identity $DName -HiddenFromAddressListsEnabled $$HiddenUser

But the $$hiddenuser does not work, and i guess i cannot have 2 $ standing together. I need to answer $True or $False to -HiddenFromAddressListsEnabled.

Any suggestions to solve this, or can I solve this in another way?

WinRM continues to work after Certificate Renewal ?

$
0
0

I’ve enabled WinRM over HTTPS in an Enterprise environment with an internal CA by using the following command

winrm create winrm/config/Listener?Address=*+Transport=HTTPS  @{Hostname="Computer.Domain.local";CertificateThumbprint="AAA756BA8FAAA1AD1FAAA6ECC8C81877BE31EEEE"}

I check the listen using the command below and all looks fine. Thumbprint matches as expected and I can enter a pssession remotely

winrm enumerate winrm/config/listener

However, if I then renew this certificate (I’m trying to simulate what will happen when the certificate expires – I tried this with new key and same key) and check to see if I can still open a remote session using

Enter-PSSession –Computer Computer.Domain.local –UseSSL

I can create and use the remote session. A reboot of the remote computer doesn’t change anything and checking the current certificate thumbprint against the  winrm/config/listener shows that they are different.

(I've performed a recursive search for any certificate for LocalMachine that matches the old Thumbprint and that comes up empty. )

Is this the expected behaviour? I would have thought not… Why does it work despite the fact the certificate is not present?


Hakabo.com

Copy-Item with file exclusions using -Exclude parameter

$
0
0

I am writing a PowerShell task using psake to copy over a directory structure and I am having some problems with the copy task:

$ExclusionFiles = @("packages.config", "connectionStrings.config")

    Copy-Item -Path $SourcePath -Destination $DestinationPath -Exclude $ExclusionFiles -Recurse -Force

When I run this command, it works properly but does not exclude the files that I specified in the $ExclusionFiles array parameter.

How can I get the Copy-Item to properly exclude my specified files (they exist at the root of my source path directory)?

Please advise.

Thanks.  



Powershell ISE produces output during the second run/execution

$
0
0

Hi Team,

I am new to powershell and i wrote a powershell script to send out an email with html table. Whenever i run for the first time i am just getting the mail but no content in it. When i run tat second time i am getting the output. Not sure where i am missing.

Any body has faced this issue before. Please let me know how i can sort this out.

Used Powershell_ise (V1.0).

Import-PSSession imported objects not available in an invoke-command scriptblock - Office 365

$
0
0
$Session = New-PSSession -ComputerName localhost

# The connection to O365 needs to invoked from a server that has Azure powershell installed - otherwise connect-msolservice command fails with an error

# The next block of commands (ending connect-msolService) is the standard connection syntax for connecting to Office365 from an on premise server with Azure powershell installed.  Note that the $SessionO365 is imported into the local $Session
Import-Module MSOnline
$LivePassword=ConvertTo-SecureString "password" -AsPlainText -Force
$LiveCred = New-Object System.Management.Automation.PsCredential ("admin@domain.onmicrosoft.com",$LivePassword)
$SessionO365 = New-PSSession -ConfigurationName Microsoft.Exchange -ConnectionUri https://ps.outlook.com/powershell/ -Credential $LiveCred -Authentication Basic -AllowRedirection
Import-PSSession $SessionO365
#Access msolservice
connect-msolService -Credential  $LiveCred
get-ummailbox username@domain.com
# Invoke-Command used to start the script in the external session. Variables returned by script are then stored in the $ReturnArray variable
$ReturnArray = Invoke-Command -Session $Session -Argumentlist $argsArray -ScriptBlock {
$result=get-ummailbox username@domain.com *>&1
return $result
}
write $ReturnArray

Output below shows that imported exchange commands work in $Session but not in the script block.  We definitely want to use a script block

Thanks

David

Name                 UMEnabled Extensions UMMailboxPolicy PrimarySMTPAddress                                                                                                                                                                                    
----                 --------- ---------- --------------- ------------------                                                                                                                                                                                    
User name         True      {1001}     Standard... useremailaddress

The term 'get-ummailbox' is not recognized as the name of a cmdlet, function, script file, or operable program. Check the spelling of the name, or if a path was included, verify that the path is correct and try again.
    + CategoryInfo          : ObjectNotFound: (get-ummailbox:String) [], CommandNotFoundException
    + FullyQualifiedErrorId : CommandNotFoundException
    + PSComputerName        : localhost



Get-ADPrincipalGroupMembership assistance required

$
0
0

Hi everyone,

New to Powershell and apologies if this has already been posted before.

This is what I am trying to do in my AD environment:

  1. Obtain an spesific role
  2. Ensure that X-Group or Groups has been mapped to this role
  3. If X-Groups are mapped then write an output saying so and if not write an output saying it is not

Here is my script:

$Role = Get-ADPrincipalGroupMembership -identity Role1 | Select-Object SamAccountName | Where-Object {($_.SamAccountName -match 'SecurityGroup1') -or ($_.SamAccountName -match 'SecurityGroup2')}
IF ($Role -eq 'True') {write-host 'Good Job' -Foreground Green}
ELSE {write-host 'Try Again' -Foreground Red}


The issue I am facing is that no matter what, it will return the False condition (printing our 'Try again' in Red).

There is something wrong in my logic (that is my assumption anyway).

If I run by itself:

Get-ADPrincipalGroupMembership -identity Role1 | Select-Object SamAccountName | Where-Object {($_.SamAccountName -match 'SecurityGroup1') -or ($_.SamAccountName -match 'SecurityGroup2')}

It will return the filtered security groups correctly.

Your assitance would be greatly appriciated.


Create PSDrive with If and Elseifs

$
0
0

Hi

I'm trying to create a script that will take the text entered and use it to create a PSdrive to the required domain and then change to that PSdrive.    I'm trying to use If and Elseif commands but instead of going to the next if statement it just hits the first statement and thats it, a PSDrive to Domain1 is always created regardless of the input.  Can anybody help?

$domain = Read-Host "What domain do you want to change groups in?"
$drivename = Read-Host "What do you want to call the drive?"
if ($domain = "domain1")

New-PSDrive -Name $drivename -PSProvider ActiveDirectory -Server "$domain" -Credential (Get-Credential "$domain\administrator") -Root "//RootDSE/" -Scope Global
}
    elseif ($domain = "domain2")
{
New-PSDrive -Name $drivename -PSProvider ActiveDirectory -Server "$domain" -Credential (Get-Credential "$domain\administrator") -Root "//RootDSE/" -Scope Global
}
cd ("$drivename" +":" )

Powershell remoting - Invoke-Command

$
0
0

Hi! I am trying to run the Invoke-Command on a few servers in various domains and subnets, and this is what I get... I need a bit of help to find out why. It works on two servers, not listed here.
The script looks like this so far, as a test in SCOM.

# Get disk alerts that are new and not handled yet
$GetNewDiskAlerts = Get-SCOMAlert -ResolutionState 0,14 | Where-Object { $_.Name -eq "Logical Disk Free Space is low"}

foreach ($Alert in $GetNewDiskAlerts)
{
    Write-Host
    Write-Host (("-")*100)
    Write-Host "ALERT ID:" $Alert.Id
    Write-Host "DESCRIPTION:" $Alert.Description
    Write-Host "RESOLUTION STATE:" $Alert.ResolutionState
    Write-Host "CREATED:" $Alert.TimeRaised.AddHours(2)
    Write-Host "SEVERITY:" $Alert.Severity
    Write-host "HOSTNAME:" $Alert.NetbiosComputerName
    Write-Host "PARAMETERS:" $Alert.Parameters

    # Run the commands/script on the computer with disk alerts
    Invoke-Command -ComputerName ($Alert).Parameters[1] -Credential ADM\SCOM_Script_Admin -ScriptBlock {New-Item -Path C:\temp\DiskFull.txt -ItemType File -Force}

    ping ($Alert).Parameters[1]
}

I have added ADM\SCOM_Script_Admin as a local administrator account on all these servers.
I can also ping all servers from the server I run the script from, except nhs45wts016 (the first one)
I've ran winrm quickconfig on all servers, which say
WinRM service is already running on this machine.
WinRM is already set up for remote management on this computer.

These are the result:

[nhs45wts016.domain] Connecting to remote server nhs45wts016.domain failed with the following error message : WinRM cannot process the request. The following error occurred while using Kerberos authentication: Cannot find the computer nhs45wts016.domain. Verify that the computer exists on the network and that the name provided is spelled correctly. For more information, see the about_Remote_Troubleshooting Help topic.
    + CategoryInfo          : OpenError: (nhs45wts016.domain:String) [], PSRemotingTransportException
    + FullyQualifiedErrorId : NetworkPathNotFound,PSSessionStateBroken



[VSWFIL002.domain2] Connecting to remote server VSWFIL002.domain2 failed with the following error message : The client cannot connect to the destination specified in the request. Verify that the service on the destination is running and is accepting 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 config
ure the WinRM service: "winrm quickconfig". For more information, see the about_Remote_Troubleshooting Help topic.
    + CategoryInfo          : OpenError: (VSWFIL002.domain2:String) [], PSRemotingTransportException
    + FullyQualifiedErrorId : CannotConnect,PSSessionStateBroken



[SOFWEB007.domain3] Connecting to remote server SOFWEB007.domain3 failed with the following error message : WinRM cannot process the request. The following error occurred while using Kerberos authentication: Cannot find the computer SOFWEB007.domain3. Verify that the computer exists on the network and that the name provided is spelled correctly. For more information, see the about_Remote_Troubleshooting Help topic.
    + CategoryInfo          : OpenError: (SOFWEB007.domain3:String) [], PSRemotingTransportException
    + FullyQualifiedErrorId : NetworkPathNotFound,PSSessionStateBroken



[comsql004.domain4] Connecting to remote server comsql004.domain4 failed with the following error message : WinRM cannot process the request. The following error occurred while using Kerberos authentication: Cannot find the computer comsql004.domain4. Verify that the computer exists on the network and that the name provided is spelled correctly. For more information, see the about_Remote_Troubleshooting Help topic.
    + CategoryInfo          : OpenError: (comsql004.domain4:String) [], PSRemotingTransportException
    + FullyQualifiedErrorId : NetworkPathNotFound,PSSessionStateBroken



[VUQKOMCTX021.domain5] Connecting to remote server VUQKOMCTX021.domain5 failed with the following error message : WinRM cannot process the request. The following error occurred while using Kerberos authentication: Cannot find the computer VUQKOMCTX021.domain5. Verify that the computer exists on the network and that the name provided is spelled correctly. For more information, see the about_Remote_Troubleshooting Help topic.
    + CategoryInfo          : OpenError: (VUQKOMCTX021.domain5:String) [], PSRemotingTransportException
    + FullyQualifiedErrorId : NetworkPathNotFound,PSSessionStateBroken



Freddy

Viewing all 21975 articles
Browse latest View live


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