Powershell

20K

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

PowerShell Script Request: Need to get disk space report for remote Servers, expecting details in GB format..
Supported OS Windows 2016
Script needs to call text or CSV input file to get disk space report.
Expecting output format HTML or CSV..
0
I have a vbscript that runs correctly on an Exchange Server The goal is to create a mailbox from the command line.

This is the script:

Set objShell = CreateObject("Wscript.Shell")
objShell.Run("powershell.exe -noexit c:\temp\RJRcreatemailbox.ps1 RickRudolph rjr@somedomain.com")


This script runs a powershell script which creates a mailbox for RickRudolph, email address of rjr@somedomain.com

Now what I want to do is to be able to run this script remotely from MSAccess VBA and pass the 2 parameters to the Exchange Server

Any ideas on the best way to do this?

Thank you,

Rick
0
If a csv doesn't have headers I would like to create a row of column headers depending on the number of columns in a csv.

If for example there are 3 columns I would like three column headers to be in the row
e.g. Column1, Column2, Column3

I am counting the number of columns in a csv using the following script

$Count = (Get-Content $File -First 1).Split($Delimiter).Count.

I'm unsure how to create a row of column names from the count.

Any help would be greatly appreciated
0
Started having troubles using remote PowerShell when connecting to Exchange 2016 servers...

I am able to connect initially, but then after about 60 seconds we receive the following error...


Get-ExchangeServer | Select Name,AdminDisplayVersion | Sort Name
Starting a command on the remote server failed with the following error message : Access is denied. For more information, see the about_Remote_Troubleshooting Help topic.


I know I have permissions since I am in the Org Mgmt group and I'm a Domain Admin.

What else could be causing this?
0
One of the teams receives an email that will be forwarded to us. however when we reply we have to rply the original mail sender but not who has forwarded. every time to copy original mail sender and paste it in "to" field is extremely mundane, we do this for thousands of emails. is there a better way to automate this?

the redirect option does not work here the team in interim validates the data and forwards it
0
Hi Experts,

I'm after a PowerShell script that will do the following:

For each folder of the form C:\Users\AnyUserName\CIRCLY7

copy C:\myfolder\myfile.xyz to C:\Users\AnyUserName\CIRCLY7\myfile.xyz

Not sure if it is any help, but I used a Regular Expression editor using C:\Users\AnyUserName\CIRCLY7 as a template.
The result was (C:\\Users\\).*[^\\]+.*(CIRCLY7)

Regards,
Leigh
0
Hello Experts,

I need to find all of the computers within our domain that a particular user has logged into.  Unfortunately we don't have a log server from which I could query domain controller logs.  My thoughts are to query each PC to see if a user profile for the particular users exists on it.  The Powershell code I'm trying to use is as follows:
$User = read-host "Input the username of the individual that you want to search for"  
$SAMAccountName = get-aduser -Identity $user | Select samaccountname
$Computers = Get-AdComputer -filter {(Name -Like "dj*")} | select name | sort name

$Results = foreach ($Computer in $Computers)
{
    $CheckForProfile = "\\" + $Computer + "\c$\Users\" + $SamAccountName.samaccountname + "\"
    if((Test-Path $CheckForProfile))
    {
        $Computer
    }
}
$Results | Out-file "c:\work\Computers_$($SamAccountName.samaccountname)_has_logged_into.txt"

Open in new window

This is not returning any findings.  If I change the $Computers variable to a single PC (line 3) that I know my test account has logged into, it works.  What am I missing here?

Thanks in advance for your help.

Nick
0
I would like to modify the attached Powershell Script to produce the output below from the Source.in file, both attached.
NB:
The Code Qty represents a Total of Code 1 Qty, Code 2 Qty and Code 3 Qty if the fields are populated.

Below is a condensed version displayed removing other columns..


Ref#:  1011
   
Item                    Code Qty   Desc    Full P   ….   Code

10-00000           108            Desc1   1               2020/OC/06  = 3 ,  2020/NO/03 = 105          
10-00000           216            Desc1   2               2020/NO/03 =
11-11111           168            Desc2   2               2020/OC/03
12345                   72             Desc4   1               NOV 03 20


Totals:                  663                         8  ,,,,,,,,
Script.ps1
source.in
0
We have a shared network folder with over 400,000 loose files and need to create a powershell script that will take those files and move them into folders in the same directory based on the last three characters of the filenames.

For example:

[\\servername\fileshare\file001.eps] -> [\\servername\fileshare\001\file001.eps]
[\\servername\fileshare\file002.eps] -> [\\servername\fileshare\002\file002.eps]
[\\servername\fileshare\file400001.eps] -> [\\servername\fileshare\400001\file400001.eps]
[\\servername\fileshare\file12345.eps] -> [\\servername\fileshare\345\file12345.eps]

I am newbie to powershell scripting and any assistence would be greatly appretiated.

Thanks,
0
I had this question after viewing Change a specific key value in app.config file with another value..


I have a very similar issue but the solution provided to the question above is not working for me. The .xml file that I want to update has entries like the ones below. I need to update some of the entries not all. The values that I will provide need to be stored as variables, not hard coded.


<?xml version="1.0" encoding="utf-8"?>
<parameters>
  <setParameter name= "MachineValidationKey" value="" />
  <setParameter name= "Smart Card Auth URI" value="https://localhost/SmartCardAuthService/" />
  <setParameter name= "MachineDecryptionKey" value="" />
</parameters>


My code (based on the previous answer) is below. Is the "add[@key]" specific to the config file or is that a construct for the SelectSingleNode?  


$filename = 'server1.xml'

$XPath = "parameters/setParameter/add[@key='MachineValidationKey']"

#$XPath = "parameters/setParameter/add[@name='MachineValidationKey']"

$Attribute = "value"
$machinekey = 'SecretString123'

$xml = [xml] (Get-Content -Path $filename)

#$xml.SelectSingleNode($XPath).SetAttribute($Attribute,$machinekey)

$xml.SelectSingleNode("parameters/setParameter/add[@name='MachineValidationKey']").SetAttribute("value", "$machinekey")

$xml.Save($filename)


But is resulting in the …
0
Hi All

I'm trying to copy newly created .jpg files that start with capt and end in numbers, i.e. capt0468.JPG from a network drive \\10.10.1.252\pix using a windows batch file. There are folders within the pix folder ,they look like the below and store jpg files

Snip20200220_8.png
There are other jpg files that end in SM, MD, i.e. capt0430_MD or capt0430_SM within those folders - these are files I want to ignore.

Below is a windows batch file, I'm not sure where to start - hoping to get support here.

@echo off
set source="\\10.10.1.252\pix\*"
set target="C:\inetpub\wwwroot\Images\img"

FOR /F "delims=" %%I IN ('DIR %source%\*.jpg /A:-D /O:-D /B') DO COPY %source%\"%%I" %target% & echo %%I & GOTO :END
:END
TIMEOUT 4

Open in new window


I found the windows batch file does not work and I'm sure I'm doing something wrong here. Any help is greatly appreciated.
0
I have this Powershell script

$U=Get-ADUser -Filter * -SearchBase "OU=comp Users and Computers,DC=comp,DC=ads" -Properties Name,userprincipalname,distinguishedname | select Name,userprincipalname,distinguishedname

The results come back in a 1D array with lots of values separated by a semi colon eg
@{Name=test; userprincipalname=S71@comp.org.uk; distinguishedname=test,OU=Users,OU=FE,OU=Shops,OU=comp Users and Compute
rs,DC=comp,DC=ads}

How do I retrieve the values?
How do I deal with the fact that OU is repeated?
0
Using PowerShell I am looking to copy a column from Excel to a text file. I've scoured everywhere and cannot find what I need to help.
0
Is there an easy way to copy NTFS folder permissions to multiple subdirectories that have the same name?

example: copy NTFS folder permissions of folder "1A" to any existing subdirectories folders that have the same name of "1A"
0
Office365 with 2 seperate domains approved.
Both domain have run aprox a year before being DNS pointet på 365.
One domain works fine and all older folders loaded in via .pst shows correct.
The other domain has 2 emails, one works fine but the other only shows the subfolders context in owa.
I have tried looking at the permissions with powershell and everything seems fine.
Microsoft Exchange Online Powershell Module
I tried creating new profiles and logging the account in, also on different client pc's but still no context on subfolders.

Further the 'Inbox' wont change name according to the language, sent etc folder renames fine when changing timezone on first log-in to owa. Alle the other emails on both domains this has worked fine.

All mailbox in outlook is set to recieve all emails and not just a year back.

There is a Business Premium Licens to the account, so it should have the nessasary permissions and program access.

Both owa and outlook can send and recieve emails.
0
I would like to run a powershell script that has the Active Directory module cmdlt.  But I will like to do it from a workstation that only have the powershell and not aduc install.  
Is there a way to connect to a server that's have the PS Active Directory Module cmdlets so I can run this script?

Can you provide me the correct syntax
0
Guys,
I got the suggested query below from link sql server powershell notification on how to trigger email notification when sql server service is stopped. However this script maybe worked with only one server,  In my company we have approximately 100 sql server and instances, so I would need the query will go and check every server line by line send sending  email when it found any of the sql server associated query  in stopped mode.

Try
{
    While(1 -eq 1)
    {
        Invoke-Sqlcmd -ServerInstance "YourSqlInstance" -Query "DECLARE @ConnectionTest int;"
        sleep 5
    }
}
Catch
{

    $smtpServer = "yourcompany.com"
    $msg = new-object Net.Mail.MailMessage
    $smtp = new-object Net.Mail.SmtpClient($smtpServer)

    $msg.From = "windowsServer@yourcompany.com"
    $msg.ReplyTo = "windowsServer@yourcompany.com"
    $msg.To.Add("dbaTeam@yourcompany.com")
    $msg.subject = "Connection to SQL Server Failed"
    $msg.body = "Connection to SQL Server Failed"
    $smtp.Send($msg)

}

Open in new window

0
I need to create a script that does multiple actions pulling input from a CSV file that contains the Active Directory Account

Here are the things needed to accomplish:

Disable Account - User

Change PWD

End Date User Account

Append Description in AD User account

Move to OU

Remove From Groups

Remove any Meetings that user is Organizer

Removing 0365 licenses from user account



I have bits and pieces of some of the items that need to be done - I just don't know how to tie them all together

Location of csv
C:\scripts\ xxxx.csv

End Date:
#set account expiration date
Import-Csv "c:\scripts\contractors.csv" | foreach {set-adaccountexpiration -identity $_.UserID -datetime $_.EndDate}


Append Description in AD User account
get-aduser XXXXAD -Properties Description | ForEach-Object { Set-ADUser $_ -Description "$($_.Description) Some more stuff" }

Remove From Groups:

#removes from all distribution groups $dlists =(Get-ADUser $termuser -Properties memberof | select -expand memberof) foreach($dlist in $dlists){Remove-ADGroupMember $termuser -Identity $dlist -Confirm:$False} write-host "* Removed from all distribution and security groups"

Disable Account:
#disable user Disable-ADAccount -Identity $termuser

Change Password:
Set-ADAccountPassword $userinput –NewPassword $newpwd -Reset

Move to OU:
Get-ADUser -Filter { samAccountName -like $userinput } | Move-ADObject –TargetPath "OU=Disabled Users,OU=User …
0
I need to find a script that will delete folders in the C:\users folder, but keep some. I also need to run two commands on a set of folders and then delete them also in the c:\users folder.

for example I would need to get a listing of the folders and then delete c:\users\bob and c:\users\alice but keep c:\users\jane and c:\john.

Then I would need to run:

takeown /f c:\users\local_tiffany /r /d y

icacls c:\users\local_tiffany /grant kr\administrator:F /T

and then delete c:\users\local_tiffany

The folders I need to keep will always be the same (about 10) but the folders to delete and run the command on will always be different.
0
I have two scheduled tasks set to trigger on security event IDs, 4767 and 4740 that fire on two of my domain controllers.  They run a short powershell script like this:

$eventcontent = wevtutil qe security "/q:*[System [(EventID=4767)]]" /f:text /rd:true /c:1
$SmtpClient = new-object system.net.mail.smtpClient
$MailMessage = New-Object system.net.mail.mailmessage
$SmtpClient.Host = "[smtp server]"
$mailmessage.from = ("[DC1@domainname]")
$mailmessage.To.add("[alert@domainname]")
$mailmessage.Subject = $eventcontent
$mailmessage.Body = $eventcontent
$smtpclient.Send($mailmessage)

Open in new window


The script works, as every time we have a lock or unlock we receive the email.  The problem is that every morning between 2 and 6AM we get a set of three email, one of which is blank, the other two continuously reference the same old pair of logs.

Interesting details:
It was the case that all three of them were blank emails for a while, until I expanded the size of the security event log.  At that time two of them started to contain event information.  The event information they contain are one user account lock and the corresponding unlock for that user account (4767 and 4740).  These two emails come from two different domain controllers, the lock event coming from the PDC.  The third (which is blank) comes also comes from the PDC.

I don't have any idea how to approach this, there is nothing special about the logs that are getting resent every day, so if anyone has any ideas I'm all ears.  Thanks!
0
Dear All,

Exchange Management Shell does not connect to server. I am getting below erorr on exchnage 2016 server

I restart winrm service ,disabled firewall and antivirus. still getting below erorr . pplease suggest me how can i trouble shoot

Show quick reference guide: QuickRef
VERBOSE: Connecting to exch01.text.local.
New-PSSession : [exch01.text.local] Connecting to remote server exch01.text.local failed with the following
error message : WinRM cannot complete the operation. Verify that the specified computer name is valid, that the
computer is accessible over the network, and that a firewall exception for the WinRM service is enabled and allows
access from this computer. By default, the WinRM firewall exception for public profiles limits access to remote
computers within the same local subnet. For more information, see the about_Remote_Troubleshooting Help topic.
At line:1 char:1
+ New-PSSession -ConnectionURI "$connectionUri" -ConfigurationName Micr ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : OpenError: (System.Manageme....RemoteRunspace:RemoteRunspace) [New-PSSession], PSRemotin
   gTransportException
    + FullyQualifiedErrorId : WinRMOperationTimeout,PSSessionOpenFailed
VERBOSE: Connecting to exch01.text.local.
New-PSSession : [exch01.text.local] Connecting to remote server exch01.text.local failed with the following
error message : WinRM cannot complete the operation. Verify that the…
0
Sorry but I am not a Powershell expert. And I want to modify a PowerShell script which executes a command for each line of a variable containing a list.

To make it all understandable, I will simplify my example  (in the reality, that's for vmware scripting, but my problem concerns the Powershell syntax )

Imagine a list of computers, stored in a variable, result of another powershell command.
It might look like this.:
SERVERA
SERVERB
SERVERC
SERVERD

And It's stored in a variable "list_computers" ($list_computers)
I want for each computer some (powershell) commands to be executed.
For example

display the computername
ping the computername

How to do that?
How to read each line of the variable ?
Should I use Foreach of Foreach-Object?
How to execute several commands ?

NB:
command "write $list_computers" give:

SERVERA
SERVERB
SERVERC
SERVERD

Could the following syntax be correct?

$list_computers | foreach-object {
$computer = $_
write $computer
command1 $computer
command2 $computer
}

Thanks

Jm
0
I'm taking over a backup system that was managed by what appears to be SOMEWHAT trained monkey who didn't think that servers that weren't in the main domain needed domain credentials (Our company has several AD Domains - main, prod, dmz and etc.) He also didn't use any logic when creating jobs = the same job would be backing up machines from various domains at the same time regardless of the VM type... in general it's a mass.

For starters, I'd like to use power shell to get all vms in all the jobs that use .\Administrator as the backup credential... but when I use Get-VBRJobObject, even with the FL flag, I can't see the credentialss used:

PS C:\Users\davidsadm> Get-VBRJob |Get-VBRJobObject -Name "CTRACK" |fl


Id                  : 32584000-6a3c-4042-9540-8ebfaec4e0c9
ObjectId            : 42d7e0ed-f0f1-48ac-96ff-3eded31ee9a1
Object              : Name: CTRACK
TypeDisplayName     : Virtual Machine
Filter              :
Role                : EInclude
Name                : CTRACK
Type                : Include
Location            : <redacted>\<redacted>\Prod-Cluster\CTRACK
OrderNo             : 23
ApproxSizeString    : 20.7 GB
Info                : Veeam.Backup.Model.CDbObjectInJobInfo
JobId               : 7e1d7c34-8f92-4e1a-a806-93ba2868fc10
IsFolder            : False
IsIncluded          : True
IsVssChild          : False
IsExcludeDisksChild : False
IsExcluded          : False
IsExtended          : False
PolicyType          : None
VssOptions          : 

Open in new window

0
Hi,
I need help with trying to figure out how to find a replace multiple values in csv file.

So for example, this worked for one item - (get-content $testcasesCSV) | foreach {$_ -replace '1153', '1344'}

 I need to do it for multiple items in the excel. Could you please advise



thank you so much.

$sharedStepsCSV = "SharedStepsReady.csv"
$sharedSteps = import-csv $sharedStepsCSV

$testcasesCSV = "Test Cases with Steps IDs Column.csv"
$TestCases = import-csv $testcasesCSV
$SharedStepsHash = @{}

Foreach ($sharedstep in $sharedSteps)

{
$newID = $sharedStep.id
$oldID = $SharedStep.description
$SharedStepsHash.add($oldID,$newID)
$Replaced = (get-content $testcasesCSV) | foreach {$_ -replace $SharedStepsHash[$oldID], $SharedStepsHash[$NewID]} | Set-Content replace.csv

}


(get-content $testcasesCSV) | foreach {$_ -replace $SharedStepsHash[$oldID], $SharedStepsHash[$NewID]}
(get-content $testcasesCSV) | foreach {$_ -replace '1153', '1344'}

#$newtestcase = $testcase.steps.replace('$oldID','$newID')
#$TestCase.'work item type',$testcase.title,$Testcase.State,$testcase.newtestcase | out-file newtestcases.csv -Append

Open in new window

0
Hi

I have a notepad called "AllUser" containing 1000 users. I have created a Universal security group in the active directory called "AllMkt" and would like to import all the 1000 users into this universal security group.

Is there any Powershell command  and let me know the best way of doing this.

If it is Powershell please post me the exact syntax that i need to run.

Any tutorials and help much appreciated.
0

Powershell

20K

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.