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

I am trying to run a powershell script to list the name and path of all files with the archive and offline attributes set. The problem is a number of our directory paths are very long and causing the script to skip those directories. Any suggestions on the best way to address this?
0
Angular Fundamentals
LVL 12
Angular Fundamentals

Learn the fundamentals of Angular 2, a JavaScript framework for developing dynamic single page applications.

i am new to the powershell scripting and at learnig stage.
i have scripts it works (experts helped me move on further)....it checks for file, upload the file in ftp.
i have written function to send email when process complete and also capture the errors and send email error alert.
i noticed the status email works with sending attacment and failure email alerts just capturing ERROR word but not sending email alert...
Like to request for help..
I want email alerts to come body message to have errors captured ? or if possible the log file context to write in the email body.
Also like to check what more parameters to set so that we get errors alerts in the log...for timeout ,username password wrong etc...Modify_Script.ps1Modify_Script.ps1



#Requires -version 3.0
$WarningPreference="Continue"

#variables
$ScriptPath = $(Split-Path -Parent $MyInvocation.MyCommand.Definition)

# Load WinSCP .NET assembly
[Reflection.Assembly]::LoadFrom( $(Join-Path $ScriptPath "WinSCPnet.dll") ) | Out-Null

#Log Timestamp
$date=Get-Date -Format ddMMMyyyyHHmmss
$logdate=Get-Date -Format ddMMMyyyy_HHmmss
$emaildate=Get-Date -Format dd/MM/yyyy_HH:mm:ss
$Logfile = "E:\INT\Log\Daily_$logdate.txt"

function LogWrite ([string]$logstring)
{  
   Add-content $Logfile -value $logstring
}
LogWrite ("$( Get-Date -Format "yyyy-MM-dd HH:mm:ss" ) START:`t"+"File Processing BEGIN`n")

#Zip Files and move to backup folder
$sourcefolder="E:\INT\PUT"
0
Hello,

I have two files, one xml and one csv file.  The .csv file has two columns, the first column containing the value from the xml and the second column containing a value needed to update the .xml.  The ask - to read the xml file for the specific value, compare that value to the data in the first column of the csv file.  If there is a match, take the value in column B and update the .xml.  If no match, update the xml with a generic value.  The csv file is comma delimited.    There could be multiple xml files in the subdirectories that need to be read.

Example files attached.  

The XML - <testdata TestDataToLookup="test2" random="data" TestDataToInsertFromCSV="" random="data"/>

test2 would be looked up in the csv file and column 2 would be inserted in between "" of TestDataToInsertFromCSV

Assuming the file would start with something like:
$path_search = "c:\test\ReferenceFile.csv"
$path_target = "c:\test\" - there could be multiple xml files in different subdirectories to be scanned.

Get-Content c:\LookupFile.xml

$LookupFile = Import-CSV "C:\ReferenceFile.csv"

Very new to powershell.  Any help in the right direction would be appreciated.

Thank you
test.csv
test.xml
0
We have our computers locked down pretty well and only our more privileged accounts can access desktops via the network - UNC, WMI, pssessions and such.

Is there a way to give a program, such as PowerShell, rights to access through the network?  I thought I could run PowerShell as my elevated account and that would suffice.  However, that is not the case.  

For security reasons, I do not want to add our less privileged accounts to the allow list.  I'm

Thank you
Mike
0
i lost connection to my exchange 2010 server. all the users cant connect to outlook. so i went to the server directly to connect and the EMC and EMC shelll would not connect. I can't do anything. I try to use elevated command on powershell and cmd but i cant. Please HELP!!!
0
Hi,
Any good advice is appreciated.
I am wanting to create a CSV of all accounts created in a particular OU, which have not had a home drive defined.   Account created date would also be useful in this report.

Please could you recommend command to run from AD Powershell and then export to CSV?

Thanks,
Michael
0
I have attached my script below which have an issue with.

Powershell
$file ="T:\4G\GUJ_Mega_3\$((Get-Date).ToSTring('dd-MM-yyyy'))\Output.zip",
"T:\4G\GUJ_Mega_5\$((Get-Date).ToSTring('dd-MM-yyyy'))\Output.zip",
"T:\3G\RVAL02\$((Get-Date).ToSTring('dd-MM-yyyy'))\Output.zip",
"X:\3G\RHNS01\$((Get-Date).ToSTring('dd-MM-yyyy'))\Output.zip",
"X:\3G\KNL01\$((Get-Date).ToSTring('dd-MM-yyyy'))\Output.zip",
"X:\3G\KNL02\$((Get-Date).ToSTring('dd-MM-yyyy'))\Output.zip",
"X:\3G\RNCPNP\$((Get-Date).ToSTring('dd-MM-yyyy'))\Output.zip",
"X:\3G\RNCRTK\$((Get-Date).ToSTring('dd-MM-yyyy'))\Output.zip",
"X:\4G\HAR_MEGA_1\$((Get-Date).ToSTring('dd-MM-yyyy'))\Output.zip",
"S:\4G\Maha_Mega_1\$((Get-Date).ToSTring('dd-MM-yyyy'))\Output.zip",
"S:\3G\RNAN02\$((Get-Date).ToSTring('dd-MM-yyyy'))\Output.zip",
"W:\3G\RRNJP06\$((Get-Date).ToSTring('dd-MM-yyyy'))\Output.zip",
"W:\3G\RRNJD03\$((Get-Date).ToSTring('dd-MM-yyyy'))\Output.zip",
"V:\3G\RLKO01\$((Get-Date).ToSTring('dd-MM-yyyy'))\Output.zip",
"R:\3G\BAR\$((Get-Date).ToSTring('dd-MM-yyyy'))\Output.zip",
"R:\3G\FRNBA02\$((Get-Date).ToSTring('dd-MM-yyyy'))\Output.zip"
$data = foreach ($content in $file) {
$test = test-path $content
if ($test) {

$fileinfo = get-childitem $content
[pscustomobject]@{
VolumeName = (get-psdrive (($fileinfo -split "\\")[0] -replace ":","")).description
Fullname = ($fileinfo -split "\\")[2]
CreationTime = $fileinfo.CreationTime
Status = $fileinfo.Length -gt 1kb
0
I need to add email address to this script how can I make it where it returns the email in the select -object  when it sends it to the csv file


import-module activedirectory
 $domain = “domain.net”
$DaysInactive = 120
 $time = (Get-Date).Adddays(-($DaysInactive))

 Get-ADUser -Filter {LastLogonTimeStamp -lt $time -and enabled -eq $true} -Properties LastLogonTimeStamp |

 select-object samaccountname,Name,@{Name=”LAST Logon Time”; Expression={[DateTime]::FromFileTime($_.lastLogonTimestamp)}} | export-csv c:\OLD_User.csv -notypeinformation
0
I would like to modify this PS script so that it prompts the person that is running the script to enter how many days ago the report is for.
At the moment the script is set for 1 day ago, however I want it to prompt the user and then they user can enter 1,2,3 or 4 etc.. days back.. and then it will run the script based on whatever the user has input..

Thanks,

###SETUP START###
#-------DO NOT MODIFY-------#
    #Yesterdays Date
        $date = ((Get-Date).AddDays(-1)).ToString("MMM/dd/yyyy")
###SETUP END###

###USER VARIABLES START###
#-------MODIFY AS NEEDED-------#
    #Mail Subject
        $Subject = "Report for: "+$date+" "
    #Body of Email
        $MessageBody = "Attached is the Report for $date. Thank you."
###USER VARIABLES END###

 ###PROGRAM START###
      # Invokes the Send-MailMessage function to send notification email
      $splat = @{
            From =                  'email1@mail.com'
            To =                  Get-Content -Path ( Join-Path $PSScriptRoot 'EmailDist.txt')
            SmtpServer =      'smtp.email.com'
            Subject =            $subject
            body =                  $MessageBody
            BodyAsHtml =      $true
            Attachment =      ( Join-Path $PSScriptRoot 'Attachment.pdf' )
      }
      Send-MailMessage @splat
###PROGRAM END###
1
I need to create an automated process that does the following.

Scenario is based on user being terminated or leave the organization.

1) User account get's disabled in AD as part of the employee termination process
2) User account is part of a specific security group for example SAP-Users
3) We need an e-mail notification that a users account was disabled that belongs to the group "SAP-Users"
Note: This process should only apply if the user account belongs "SAP-Users"
0
Has Powershell sent you back into the Stone Age?
LVL 8
Has Powershell sent you back into the Stone Age?

If managing Active Directory using Windows Powershell® is making you feel like you stepped back in time, you are not alone.  For nearly 20 years, AD admins around the world have used one tool for day-to-day AD management: Hyena. Discover why.

Hi I Created some code here to do watermark but its not working anyone can help? Need to know the function and ways of how to control watermark. I'm trying to create a form with watermark

please help us improve. I need to finish this project as soon as possible we are only beginner in terms of powershell.

$TextBox1                        = New-Object system.Windows.Forms.TextBox
$TextBox1.multiline              = $false
$TextBox1.Name = "TextBox1"
$TextBox1.width                  = 100
$TextBox1.height                 = 20
$TextBox1.location               = New-Object System.Drawing.Point(141,170)
$TextBox1.Font                   = 'Microsoft Sans Serif,10'

$WatermarkText = 'Enter Username'
$TextBox1.ForeColor = 'LightGray'
$TextBox1.Text = $WatermarkText

$TextBox1_Enter={
if($TextBox1.Text -eq $WatermarkText)
{
    #Clear the text
   $TextBox1.Text = ""
   $TextBox1.ForeColor = 'WindowText'
}
}

$TextBox1_Leave={
if($TextBox1.Text -eq "")
{
    #Display the watermark
    $TextBox1.Text = $WatermarkText
    $TextBox1.ForeColor = 'LightGray'
}
}


$TextBox1_VisibleChanged={
if($TextBox1.Visible -and $TextBox1.Tag -eq $null)
{
    #Initialize the watermark and save it in the Tag property
    $TextBox1.Tag = $TextBox1.Text;
    $TextBox1.ForeColor = 'LightGray'
    #If we have focus then clear out the text
    if($TextBox1.Focused)
    {
        $TextBox1.Text = ""
        $TextBox1.ForeColor = 'WindowText'
    }
  }
 }
0
Server 2016 RDS  - Trying to remove Start Menu tiles for all users.

Found a powershell script that removes tiles but when I run it does not remove. Is there anyway of forcing this so it removes them? If I run manually within the session it succesfully runs the script but does not remove the tile icons.

Script:

function Pin-App {    param(
        [string]$appname,
        [switch]$unpin
    )
    try{
        if ($unpin.IsPresent){
            ((New-Object -Com Shell.Application).NameSpace('shell:::{4234d49b-0245-4df3-b780-3893943456e1}').Items() | ?{$_.Name -eq $appname}).Verbs() | ?{$_.Name.replace('&','') -match 'Von "Start" lösen|Unpin from Start'} | %{$_.DoIt()}
            return "App '$appname' unpinned from Start"
        }else{
            ((New-Object -Com Shell.Application).NameSpace('shell:::{4234d49b-0245-4df3-b780-3893943456e1}').Items() | ?{$_.Name -eq $appname}).Verbs() | ?{$_.Name.replace('&','') -match 'An "Start" anheften|Pin to Start'} | %{$_.DoIt()}
            return "App '$appname' pinned to Start"
        }
    }catch{
        Write-Error "Error Pinning/Unpinning App! (App-Name correct?)"
    }
}






Pin-App "Server Manager" -unpin
Pin-App "Windows Powershell" -unpin
Pin-App "Windows Administrative Tools" -unpin
Pin-App "Windows Powershell ISE" -unpin
Pin-App "Task Manager" -unpin
Pin-App "Control Panel" -unpin
Pin-App "Remote Desktop Connection" -unpin
Pin-App "File Explorer" -unpin
0
Need to Use Set-WinUserLanguageList en-US to Change Language  for specific user

Can we push it remotely for specific local users on servers not in domain in silent mode

When we run it locally steps are  >Command Prompt -Type PowerShell  and hit Enter-Then Run Command -Set-WinUserLanguageList en-US -Will Ask for Y to Press

Can we get this in some script to push on remote computers in one go or if changes can be reflectedd in first login -as it is asking to log off and login again ?
1
Hello Powershell Experts,

I think I have asked a similar question in the past, but I can't find it.  I have been tasked with finding all of the distribution groups in our domain and then getting a list of all the user in each group.  The following Powershell code gets the results I want and displays them to the screen in the format that I want:

$DistributionGroups = get-adgroup -filter 'GroupCategory -eq "distribution"' | sort samaccountname

foreach ($DistributionGroup in $DistributionGroups)
{
        Write-host $DistributionGroup.name
    Write-Host "---------------------------------------"
    Get-ADGroupMember -Identity $DistributionGroup.SamAccountName | select name | sort name
    Write-Host ""
}

My question is how can I get this information into a text or CSV file?
0
I am attempting to search all mailboxes using powershell in exchange 2013 for a attachment or subject would probably work also. I can seem to get it to run
Get-Mailbox | Search-Mailbox -SearchQuery 'subject or attachment name' -TargetMailbox "Discovery Search Mailbox" -TargetFolder "AllMailboxes-Election" -LogLevel Full

It breaks on "discovery search mailbox" I have tried it like this also "DiscoverySearchMailbox"
0
Hi,

Is there a powershell script for downloading the latest security update for an OS. We have windows 2012 R2, windows 2008 R2, depending on the OS type and architecture, I want to download the latest security update, I already have a script for installing the updates by copying the patch on the server then install using psexec.

Thank you in advance,

kay
0
Hello,

We have the below script in place that's reminds staff to complete their timesheets. This is run from scheduled tasks on each machine. Does anyone know how we can do the following.

1. Stop the blue powershell console from flashing up before the message box appears.  I've tried -windowstyle hidden but that doesn't appear to work.
2. Change the options in the message box that appears. It would be good if the Yes button text could be changed to Complete (or Review) and the No button to Ignore

Code below, thanks

$currentUser = [System.Environment]::UserName
$IE = New-Object -ComObject internetexplorer.application

$strFilter = $("(&(objectCategory=user)(SAMAccountName={0}))" -f $currentUser)

$objDomain = New-Object System.DirectoryServices.DirectoryEntry

$objSearcher = New-Object System.DirectoryServices.DirectorySearcher
    $objSearcher.SearchRoot = $objDomain
    $objSearcher.PageSize = 1
    $objSearcher.SearchScope = "SubTree"
    $objSearcher.Filter = $strFilter

$colResults = $objSearcher.FindOne() 

if ($colResults.Length -eq 1)
{

    $employeeID = $null
    [int32]::TryParse($colResults[0].Properties["EmployeeID"], [ref]$employeeID) | Out-Null

    if ($employeeID -gt 0)
    {

        $svc = New-WebServiceProxy -Uri "http://pods.intranet.company.com/timesheets.asmx?wsdl"

        $hasOutstanding = $svc.hasOutstandingTS($employeeID)
        $hasToApprove = $svc.hasToApproveTS($employeeID)

        if ($hasOutstanding -or $hasToApprove)
     

Open in new window

0
I want to create a standard menu of options as it were, so that by clicking on a specific area, number, phrase on the menu, that it will trigger a .bat or powershell script to run.
I was hoping for something simple I could copy and paste on any computer, with the expectation that the paths to run the .bat or powershell scripts will have standard locations.
Perhaps and html file (like a web page file), where I could run each script would work, where I could manually add any new scripts etc..
0
I am, at best, a novice user when it comes to writing Powershell scripts, so any simplified explanation to this question would be appreciated.
I am accessing one of our vendors API services. In order to access it, I need to generate an authentication token. I have the url to send the request to, and I have the username and password. What I am not sure of, is how to write the script to retrieve the token. Is there a "generic" method to do this?

Again, feel free to break it down to the most basic of terms. I won't be offended. :)

Thank you in advance.
0
Making Bulk Changes to Active Directory
LVL 8
Making Bulk Changes to Active Directory

Watch this video to see how easy it is to make mass changes to Active Directory from an external text file without using complicated scripts.

looking for power shell Script to Compare Disk Space ,Patches and service status before and after reboot  of windows servers
or if there is any other better solution to do pre-post checks during ms patching
0
Please help to share power shell  script To check last reboot for windows servers (mentioned in server list ) with user id used for reboot
0
I have large csv file 150 MB file with 5 columns and I would like to sort using Io.streamreader rather than using below command as it very slow on larger files.
import -csv  "c:\temp\test.csv"| sort col1,col2,col3 ,col4,col5 | export-csv "c:\temp\test1.csv"
Is there way to read csv file using  System.IO.StreamReader and sort and write to a new file.
0
There is one good srcipt available at Microsoft portal..

URL is - https://gallery.technet.microsoft.com/scriptcenter/Vmware-VM-Inventory-report-2eca257c

when running given script saying powercli not installed [snap attached]? while its already there -how can we fix this? any path? version to be updated?

Or if nay better script we can use as tool is not allowed here,looking for some script as an alternate of rv tools

Here is script...
<#

=============================================
FileName						: 		VM_Inventory.ps1
=============================================
Created [DD/MMM/YYYY]			:		[ 18.APR.2016 ]
Updated [DD/MMM/YYYY]			:  		[ 05.JAN.2017 ]
Author							: 		Amol Patil
Email							: 		amolsp777@live.com; pscriptsasp@gmail.com
Web								: 		[]
Requirements					:		[PowerCli v2.0 and above, no restriction policy ]
OS								: 		[Windows machine with PowerShell]
Version History					: 		[0.6]
=============================================
|> Purpose:
|					To get VM inventory.

DESCRIPTION:
					This script will connect to vSphere client and get the VMs from connected VC. 
					It will gather all the VM information which needs for every Admin to have as a VM inventory to check quickly or refer in future if something goes wrong.
					Script may takes time to fetch the information as it is gathering deep information of the VM to so you can schedule the script to fetch the information.

					VM inventory output will be store in CSV format so 

Open in new window

0
We are on Office 365 and I have found this article at the following link regarding email attacks that use display names matching someone in the company.
https://gcits.com/knowledge-base/warn-users-external-email-arrives-display-name-someone-organisation/

This is not an SPF or DMARC or spam filter issue, it's just the display name that matches a company user. The email addresses is not being spoofed. The email address is gmail or something else like that.  But because email clients don't show the email address without hovering, most users can easily be fooled by a bad actor simply creating an gmail account with the CEO's display name.

The scenario addressed here perfectly matches what I was experiencing and looking for, and I am very grateful to Elliot Munro for sharing this with us.  
 
I implemented this Transport Rule based on all the company users’ display names as found in this cmdlet: (Get-Mailbox -ResultSize Unlimited).DisplayName
Upon reviewing the Transport Rule in the Exchange Admin Center, it added all the company user's display names to a nice list.
 
However quite a few users started to get emails with the added disclaimer when hit by this rule, but the “From” header didn’t match a company display name in the list.  I double checked everything in the rule, and each display name is inside single quotes and is separated by “or”, in the Exchange Admin Center.  Looks perfect to me.
 
I am carefully tracking the display names of messages that get flagged …
0
I'm creating a form using power shell. What I need is user will upload Files from computer (email, xml, notepad, image, word, excel document)  and save it from specific folder
After saving the power shell can also display the uploaded files (like list view or data grid view, any display can do)

Hoping for your assistance.
respect. I'm just starting to learn power shell.
0

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.