[Product update] Infrastructure Analysis Tool is now available with Business Accounts.Learn More

x

Powershell

18K

Solutions

8K

Contributors

Windows PowerShell is a task automation and configuration management framework from Microsoft, consisting of a command-line shell and associated scripting language built on the .NET Framework. PowerShell provides full access to the Component Object Model (COM) and Windows Management Instrumentation (WMI), enabling administrators to perform administrative tasks on both local and remote Windows systems as well as WS-Management and Common Information Model (CIM) enabling management of remote Linux systems and network devices.

Share tech news, updates, or what's on your mind.

Sign up to Post

Hey Experts.  Need a little guidance as I can't seem to figure out why the script isn't using the proper drive letter when launched.  

Rename-Item -Path "%appdata%\microsoft\templates\normal.dotm" -NewName "%appdata%\microsoft\templates\normal.bak"

if ((get-childitem "%appdata%\microsoft\templates\Normal.dotm").LastWriteTime.Date -le (get-date '04/10/2017'))
{ copy-item O:\office2016\Normal.dotm "%appdata%\microsoft\templates" -Force }

Open in new window


When the script runs, the %appdata% variable isn't using the local c:\ drive and related path.  I've tried ' and " with no luck.  I appreciate your help!
0
Problems using Powershell and Active Directory?
LVL 8
Problems using Powershell and Active Directory?

Managing Active Directory does not always have to be complicated.  If you are spending more time trying instead of doing, then it's time to look at something else. For nearly 20 years, AD admins around the world have used one tool for day-to-day AD management: Hyena. Discover why

Hi I have a HTML output for a script. I have used CSS in the script. The output comes very nice. However if I send the file by email to some one else or copy the HTML output to different location the CSS goes away and HTML output does has only a normal text. How do I retain the CSS even if I move the HTML file to other location ?
0
Greeting Experts -  

I need help creating a PowerShell script to pull text document from a list of computers (1000+) using Domain Admin Credentials. The text document in question will have the same name (i.e., pc1.txt, pc2.txt, pc3.txt) as pc located in the C:\drive (i.e., C:\pc1.txt). The script needs remotely pull the text document from each pc "with the same name as the pc" and copy it to a network shared drive....  Can somebody help me with this task.....
0
I need to write and automate a power shell script to identify any users in active directory thay have a duplicate Display Name.  Any help would be appreciated.
0
Hi Experts.  Putting together a small script (preferably PS) and need some help.  I would like to copy file x:\path\A.log from x:\path to y:\path if the modified date of y:\path\A.log is equal to or older than Dec 10,2018.  Thank you!
0
How can I list all the msol roles that a specific user is a member of via powershell?
1
Hello,
I need help in copying files from a network share to many computers....
I have the following script from internet, however I don't see the results...

        $computers=Get-Content C:\scripts\computer.txt

        $source = "IT\Microsoft Powershell\Modules\*"
        $destination = "C$\Windows\system32\WindowsPowerShell\v1.0\Modules\"

ForEach ($COMPUTER in ($computers))
        {if(!(Test-Connection -Cn $computer -BufferSize 16 -Count 1 -ea 0 -quiet))
        {write-host "Cannot reach $computer its offline" -f red}
          
else    {
        if ((Test-Path -Path \\$computer\$destination)){
        TRY{
        Copy-Item $source -Destination \\$computer\$destination -Recurse -Verbose -ErrorAction Stop
        Write-Host "Sucessfully copied on $computer" -BackgroundColor Green
        }
        Catch {$error[0].exception.message}
        }
        }
        }

Open in new window

1
Hi all. Last week the good folks of EE provided me some wonderful support in providing the script below, which works perfectly. I have a request that will extend the script.  Currently, the script looks in the source file c:\temp\servers.txt, and what ever server names are in there the script runs again.

What about this scenario. What if instead of the txt file I had a csv file with 2 columns. column one named VM Name, column two is called Resource Group. So essentially I have two columns with VM names and Resource Group names. Could the script be manipulated so that the script runs only against the VMs if they are in a particular Resource Group?
 Example, I have 3 vm names but I only want the script to run against the vms in RG1?  See below for existing script.


VM Name         Resource Group Name
vm1                           RG1
vm2                           RG1
vm3                           RG2

Param(
	[Parameter(Position=0, Mandatory=$true, HelpMessage="Name of the KeyVault")]
	[string]$KVName,
	[Parameter(Position=1, Mandatory=$true, HelpMessage="Name of the KeyVault Resource Group")]
	[string]$KVResourceGroup,
	[Parameter(Position=3, Mandatory=$true, HelpMessage="Name of the VM Resource Group")]
	[string]$VMResourceGroup
)
$keyVault = Get-AzureRmKeyVault -VaultName $KVName -ResourceGroupName $KVResourceGroup

$splat = @{
	ResourceGroupName = $VMResourceGroup
	DiskEncryptionKeyVaultUrl = $keyVault.VaultUri
	DiskEncryptionKeyVaultId = 

Open in new window

1
Hello,
I have to install powershell modules of Exchange Online, SharePoint Online, Azure ....

I can manually download these modules & install them, however the issue is that I need them on more than one server .
I have the servers behind the proxy.

When I run Install-module -name .... I get the following error:
The package provider requires 'PackageManagement' and 'Provider' tags. Please check if the specified package has the tags......

Can someone help me get over this error & let me know how to resolve this issue?
1
Hi Experts, I'm trying to automate an uninstall process for a certain product installed throughout the domain.
Basically, the script works fine right up to the point where I actually call the MSI.

I get the uninstall flag correct and I get the product code from the Registry Value (from the uninstall string itself)

but whenever I get to the uninstall command itself, I get the MSI usage window, as though I have a syntax error.

Here's the script I'm using:

$TARGETDIR = 'C:\logs\'
$LOGFILE = 'C:\logs\script.log'
$uninstallLog = 'C:\logs\uninst.log'

if(!(Test-Path -Path $TARGETDIR )){
    New-Item -ItemType directory -Path $TARGETDIR
}

function WriteLog { #Adds info to log file with time stamp
    Param ([String] $Message)
    $tStamp=Get-Date
    $Day=$($tStamp).Day
    $Month=$($tStamp).Month
    $Year=$($tStamp).Year
    $Hour=$($tStamp).Hour
    $Minute=$($tStamp).Minute
 
    echo "[$Day\$Month\$Year $Hour`:$Minute] $Message" >> $LOGFILE
}

function getUninstallString {
    Get-ChildItem -Path HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall, HKLM:\SOFTWARE\Wow6432Node\Microsoft\Windows\CurrentVersion\Uninstall | Get-ItemProperty | Where-Object {$_.DisplayName -like '*Enterprise Vault Outlook Add-in*' } | Select-Object -Property DisplayName, UninstallString  
}



$evVersion = Get-WmiObject -Class Win32_Product -ComputerName . | Where-Object -FilterScript {$_.Name -like '*Symantec Enterprise Vault Outlook Add-in*'} | select -ExpandProperty 

Open in new window

1
Learn Ruby Fundamentals
LVL 12
Learn Ruby Fundamentals

This course will introduce you to Ruby, as well as teach you about classes, methods, variables, data structures, loops, enumerable methods, and finishing touches.

Hi Experts..

I wonder if you could assist me to polish off my script below.  

The idea is to audit Cisco AMP AV software across all servers in the domain. My 1st draft works OK, and provides the version installed on each server, however it is missing some important info as follows:

1. Some servers may need powered off, or my account may not have rights to query some servers in the domain, therefore is it possible to capture the  PSComputerName and errors created in the output CSV?  

2. Some servers may not have the software installed at all. Is it possble to add ""PsComputerName - Software not found"" in the output for these servers?


Many thanks for any tips, assistance. cheers String

My script so far:
$Output= @()
$DaysAgo=(Get-Date).AddDays(-30)
$servers = (Get-ADComputer -SearchBase "OU=Services,DC=AD,DC=ACME,DC=COM,DC=AU" -filter {(enabled -eq $True) -and (PwdLastSet -gt $DaysAgo) -and (LastLogonTimeSTamp -gt $DaysAgo)} | Where-Object {$_.DistinguishedName -notlike "*ou=Domain Controllers,*" -and $_.DistinguishedName -notlike "*ou=Non-Windows Servers,*" -and $_.DistinguishedName -notlike "*ou=Disabled Server Accounts,*" }).name

$sb = {Get-ItemProperty HKLM:\Software\WOW6432Node\Microsoft\Windows\CurrentVersion\Uninstall\*|
        Where-Object {$_.Publisher -eq 'Cisco Systems, Inc.' }
}
Invoke-Command -ComputerName $servers -ScriptBlock $sb |
      Select-Object PsComputerName, DisplayName, DisplayVersion, Publisher, InstallDate | format-table |…
1
Hi Team,

I'm trying to extract Domain Admins members all all below details, but the lastLogonTimestamp, useraccountcontrol, whenChanged,whenCreated is returning blank values.

Get-ADGroupMember -Identity "Domain Admins" |Select-Object -Property Name,@{name="Description";expression={(Get-ADUser -Identity $_.SamAccountName -Properties Description).Description}},SamAccountName, lastLogonTimestamp,useraccountcontrol,whenChanged,whenCreated

Open in new window


Something small, but can't figure it. Need help.

Thanks.
1
I'm new to PowerShell and am trying to do a search on a mailbox for selected search terms.
My end goal is to read a CSV file with a list of search terms and the result should return True or False for each search term that exists in the mailbox.
For now what would be the command I need to return the status of the search?
The following is a simplified version of my script.

# ***********************************
# Logon
# ***********************************
$UserCredential = Get-Credential

$Session = New-PSSession -ConfigurationName Microsoft.Exchange -ConnectionUri https://outlook.office365.com/powershell-liveid/ -Credential $UserCredential -Authentication Basic -AllowRedirection

Import-PSSession $Session -DisableNameChecking

# ***********************************
# Do Processing
# ***********************************

# Is this the best way to search?
Search-Mailbox -Identity "Dave" -TargetMailbox "C1SearchResults" -TargetFolder "C1" -LogOnly -LogLevel Full -SearchQuery '12345 OR 56789 OR 13579' 

# What to go here to return TRUE/FALSE if string exists.


# ***********************************
# Logoff
# ***********************************
Remove-PSSession $Session

Open in new window

1
Is there a straightforward way to check time of removal of O365 licences for a user either through GUI or Powershell?
1
Each time I Iaunch Powershell it automatically runs a cmdlet. Where could this be coming from? Even if I reboot. Looks like something is set to auto run but not sure where it's coming from. Any ideas?. See pic
ee.GIF
0
I want to detect non-domain computers in my network. Found scripts for this purposes. Which one - detects online workstations via Ip range and next one detects are they joined to domain or not. But i cant join them for properly working ) can anyone help?
$firstThree = "10.20.51"

1..254 | ForEach-Object {

    $address = "$($firstThree).$_"

    If (Test-Connection -ComputerName $address -Count 1 -Quiet) {

        Write-Host "$address is up" -ForegroundColor Green

    } Else {

        Write-Host "$address is down" -ForegroundColor Red

    }

}

Open in new window






if (Test-Connection -ComputerName $computer -Count 1 -Quiet)
{
  if ((gwmi win32_computersystem).partofdomain)
  {
    write-host -fore green "I am domain joined!"
  }
  else
  {
    write-host -fore red "Ooops, workgroup!"
  }
}

Open in new window

1
Looking to delete computer accounts and user accounts in Active Directory

Got below script for computer accounts previously

Import-Csv -Path C:\Temp\DisableComputer.csv | ForEach-Object {Remove-ADComputer -Identity $_.Name -WhatIf}

It ran fine above then I changed it to below to run it properly

Import-Csv -Path C:\Temp\DisableComputer.csv | ForEach-Object {Remove-ADComputer -Identity $_.Name}

Problem is it doesnt perform deletion of computer accounts in a batch, have to do it one by one and see below error

Remove-ADComputer : The directory service can perform the requested operation only on a leaf object

Looking for a way to bulk delete and also modification required to bulk delete AD user accounts also
1
Wondering how to combine output from get-vm and get-adcomputer into the same CSV.

I am doing a project where I need to update VMWare Tools, but only dev domain joined Windows servers.

I am hoping to combine the outputs from get-vm and get-adcomputer into a master list, and matches records based on "Name".

For example:

$ADServers = Get-ADComputer -Filter {(OperatingSystem -like "*windows*server*") -and (Enabled -eq "True")}
$VMs = get-vm

CSV includes $VMs.Name, $ADServers.Name, $ADServers.DistinguishedName, $VMs.PowerState

$ADServers.Name and $VMs.Name should match in theory, however not all VMS will be joined to the domain so $ADServers.Name and  $ADServers.DistinguishedName may be empty on some records.

Is this possible?.

Cheers
String :-)
0
I am trying to dump application data from Azure into their own file, however, when i reference the DisplayName attribute for the application to save as the file name I get a weird naming convention. The code below imports the csv with the DisplayName and Object ID. Attached is sample file as well

import-csv .\AzureApplications.csv | ForEach {Get-AzureADApplication -objectID $_.ObjectID |export-csv .\$_.DisplayName.csv}

Open in new window

The output file name is as follows:
@{DisplayName=Test Application; ObjectId=10f3cd35-bf7e-468d-bdbb-298fa456b3c5; AppId=440ba5b1-0372-4b62-9379-edf7096c8cb5}.DisplayName.csv
Any help would be appreciated
1
Creating Active Directory Users from a Text File
LVL 8
Creating Active Directory Users from a Text File

If your organization has a need to mass-create AD user accounts, watch this video to see how its done without the need for scripting or other unnecessary complexities.

Hi, Does anyone have a Powershell script to get a list of all security groups in a particular OU?
0
I have a PS Script that works just fine for pulling lastlogondate from AD for users that have not logged on in 30 days.  What I need to figure out is my boss wants a date differential to show the number of days since that last log on (e.g. if the date of last logon was 11/21/2018, he wants a another column which would output 17 days -no idea why he wants what I see as redundant).  He also wants to be able to see their domain account in either username@domain.com or domain\username format in it's own column.   Here is the script I am currently using.  In addition to the requests, if anyone recommends additional changes or cleanup to the script, that would be fine as well:

import-module activedirectory
$30Days = (get-date).adddays(-30)
Get-ADUser -properties * -filter {(LastLogonDate -notlike "*" -OR LastLogonDate -le $30days) -AND (passwordlastset -le $30days)
-AND (enabled -eq $True) -and (PasswordNeverExpires -eq $false)
-and (whencreated -le $30days)} | select-object Name, SAMaccountname, DistinguishedName, LastLogonDate | export-csv "c:\Scripts\ADLastLogon.csv"

$properties = @{
    to          = 'user@company.com'
    from        = 'email@company.com'
    attachments = 'c:\Scripts\ADLastLogon.csv'
    subject     = "30 Day Report"
    smtpserver  = 'mail.company.com'
}

Send-MailMessage @properties
1
I am setting up a new Exchange Server 2010.
OWA and ActiveSync work fine; new mail coming in; users can send out email without problems.

Outlook Anywhere has been a problem from the start. Following several posted guides, used Exchange Powershell to set External URLs to mail.MYDOMAIN.com.  Ran MS Remote Connectivity (RCA) test to determine why I could not setup my copy of Outlook Anywhere 2010. Had DNS host setup SRV record and RCA Outlook connectivity and Autodiscovery test passed. I setup up my copy of Outlook Anywhere without problem.

Not so with the next 3 users. Ran RCA again using their email addresses and they all failed. Turns out that my email address is the only one that passes RCA. Setting up Outlook manually and bypassing Autodiscover does not seem to work either. (other than my email address) Either it keeps repeating the request for credentials or tells me that the person cannot be matched to an address on the address list.
0
Hello,

So I have an XLSX file (I would attach it, but it has sensitive data) that has inconsistent US date formatting. The data comes out of salesforce. Some dates are written as 08/30/2018, others are 8/30/2018.  

The user that gets this information is in the UK and thus needs to convert these to  DD/MM/YYYY. Usually the "Text to column" method would work, but it doesn't. The dates in the cells are text, not numerical.

I think the main problem though is that I need to standardize the US dates with leading zeroes before I can continue to figure out my US>UK date conversion problem.

Looking for a way to do this in powershell, I also assume this will need to be a CSV file now, not xlsx. I tried to create a macro to add the leading zeroes to the dates, but there's alot of wrong dates and it seems like it would take forever to create a proper macro that I can use.


Thoughts?
1
Hey all,
Im a newbie with Powershell but giving it a go.
I put together this script to stop a service, copy some files and start the service again on remote computers.

foreach ($server in (Get-Content .\servers.txt)){
$session = New-PSSession $server
Invoke-Command -Session $session -ScriptBlock { Get-Service SplunkForwarder | Stop-Service }
Copy-Item ".\Fix\*" -Destination "C:\Program Files\SplunkUniversalForwarder\etc\system\local\" -Force -ToSession $session
Invoke-Command -Session $session -ScriptBlock { Get-Service SplunkForwarder | Start-Service }
}

Question:
The service I am stopping takes a while to stop, is there a way to add a wait and check service is stopped before I copy the files?

Cheers
String
1
I am not sure how to make this clear so hopefully I ask this correctly. I have programmed in a few different languages but I am new to PowerShell. I am trying to find out if there is a way to have a PowerShell script running in the background waiting for some variables from another application which it will process. Nothing needs to be returned to the application calling the PowerShell script.

So what I am doing right now is I have a program that when a certain event occurs it will trigger a script. The program will pass the same 5 fields to the script every time. The script then runs a SQL query and loads every row from a database which contains a list of possible matches for the event that occurred based off all 5 fields. It then processes each row eliminating the rows that don't match the criteria.

So for example say an event occurs, it will trigger a script as follows:
script1.ps1 data1 data2 data3 data4 data5

The important part of why I am asking is script1 starts by accessing our database and loading 1,000 rows of data with 5 fields for each row. This is important because this is the same data almost every time and it seems like it would be more efficient if I could just keep it in memory.

The script then begins to step through each row discarding each row that does not match.

So if data1=field1 then keep it else discard it. At the end of this we may have 100 rows left and then it will process the next set of data the same way. If data2=field2 then keep …
1

Powershell

18K

Solutions

8K

Contributors

Windows PowerShell is a task automation and configuration management framework from Microsoft, consisting of a command-line shell and associated scripting language built on the .NET Framework. PowerShell provides full access to the Component Object Model (COM) and Windows Management Instrumentation (WMI), enabling administrators to perform administrative tasks on both local and remote Windows systems as well as WS-Management and Common Information Model (CIM) enabling management of remote Linux systems and network devices.