Still celebrating National IT Professionals Day with 3 months of free Premium Membership. Use Code ITDAY17

x

Powershell

15K

Solutions

7K

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

Hello Folks,
i have created this script below, but I need to out this into a CSV file, what modification should I do to it, or i could accept different aproach  on the script

thanks, for looking
 
$client = get-content "c:\temp\pcs.txt"

foreach ($ComputerName in $CLIENT) {

 Write-Host $ComputerName (Get-WmiObject Win32_OperatingSystem -computername $computername).OSArchitecture -ForegroundColor green -BackgroundColor Black
 }

Open in new window

0
Industry Leaders: We Want Your Opinion!
Industry Leaders: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

I modified a script I found on another forum for this purpose. It works great for any PC with 2+ monitors but for a PC with only one monitor it returns no values.
What should be changed to fix this?

$LogFile = "C:\monitors.txt"
"ComputerName,Manufacturer,Serial" | Out-File $LogFile
echo "ComputerName,Monitor,Serial"


foreach ($computername in (Get-Content -Path C:\comptest.txt))
{$MonitorsCMD = Get-WmiObject WmiMonitorID -Namespace root\wmi -ComputerName $computername

$Monitors = $MonitorsCMD
$LogFile = "C:\monitors.txt"

For($i=0; $i -le ($Monitors.Count - 1); $i++)
{
    $nm = $Monitors[$i].UserFriendlyName -notmatch 0
    $Name = ""
    If ($nm -is [System.Array]) {
    For($j=0; $j -le ($nm.Count - 1); $j++)
    {
        $Name = $Name + [char]$nm[$j]
    }
    }
    $sr = $Monitors[$i].SerialNumberID -notmatch 0
    If ($sr -is [System.Array]) {
    $Serial = ""
        For($j=0; $j -le ($sr.Count - 1); $j++)
    {
        $Serial = $Serial + [char]$sr[$j]
    }
    }
	
	"$ComputerName,$Name,$Serial" | Out-File $LogFile -append
    echo "$ComputerName,$Name,$Serial"
}
}

import-csv $LogFile -delimiter "`t" | export-csv monitors.csv

Open in new window

0
I have a file that contains the following data:
key,value
FILE_SRC_TGT_PATH.0,TargetrServer|SourceFilename|TargetFilename|TargetPath\
FILE_SRC_TGT_PATH.1,localhost|xxxx.xml||C:\temp\test\MyTestDir\Dir1\
FILE_SRC_TGT_PATH.2,localhost|Setup.ktr||C:\temp\test\MyTestDir\Dir2\
FILE_SRC_TGT_PATH.3,localhost|Loading.kjb||C:\temp\test\MyTestDir\Dir2\
FILE_SRC_TGT_PATH.4,localhost|Mapping.kjb||C:\temp\test\MyTestDir\Dir2\
FILE_SRC_TGT_PATH.5,localhost|download.properties||C:\temp\test\MyTestDir\Dir1\
FILE_SRC_TGT_PATH.6,
FILE_SRC_TGT_PATH.7,
FILE_SRC_TGT_PATH.8,
FILE_SRC_TGT_PATH.9,
FILE_SRC_TGT_PATH.10,

Open in new window


It is processed within a PowerShell script using the following code:
$FileInfo = "FILE_SRC_TGT_PATH.1","FILE_SRC_TGT_PATH.2","FILE_SRC_TGT_PATH.3","FILE_SRC_TGT_PATH.4","FILE_SRC_TGT_PATH.5","FILE_SRC_TGT_PATH.6","FILE_SRC_TGT_PATH.7","FILE_SRC_TGT_PATH.8","FILE_SRC_TGT_PATH.9","FILE_SRC_TGT_PATH.10" | ForEach { GetParameterValue $PARMS $_ }

Open in new window


where GetParameterValue is a function that accepts a parameter list name ($PARAMS) and parameter name (key) and returns the value (value) of that parameter.

$PARMS is populated using "$PARMS = import-csv $PropertiesFileName" where $PropertiesFileName is the name of the file that contains the above information.

As can be seen from the above code, the list is limited to 10 items. Is there a way to make it variable, so if there were 18 items (FILE_SRC_TGT_PATH.1..FILE_SRC_TGT_PATH.18) the PowerShell code would take that into account and properly populate the variable $FileInfo? $FileInfo is subsequently used in a ForEach loop [ForEach($file in $FileInfo)]

Please do not suggest an alternate way of creating $PARMS, or divert from the key/value format of the file, as this is a standard way we process our property files and can't be deviated from.

Basically, I just need to replace the line:
$FileInfo = "FILE_SRC_TGT_PATH.1","FILE_SRC_TGT_PATH.2","FILE_SRC_TGT_PATH.3","FILE_SRC_TGT_PATH.4","FILE_SRC_TGT_PATH.5","FILE_SRC_TGT_PATH.6","FILE_SRC_TGT_PATH.7","FILE_SRC_TGT_PATH.8","FILE_SRC_TGT_PATH.9","FILE_SRC_TGT_PATH.10" | ForEach { GetParameterValue $PARMS $_ }

with code that can handle an unknown number of items, that could exceed 10.
0
Hello Team,

Can someone please provide me with a nice PowerSHell cmdlet to pull out information from AD?
 Please, see below information needed

All users. Include username, name, description, create date, last login date, last password change date, account disabled, and user password configuration.
0
Below script is working fine. when script executes by added | export-csv getting error "empty pipe element is not allowed"

Thanks in advance

Import-Module ActiveDirectory
$users = Get-Content "C:\input.txt"

foreach ($SamAccountName in $users)
	{ Get-ADPrincipalGroupMembership -Identity $SamAccountName |
		Select-Object -Property name, distinguishedname, @{n='samaccountname'; e={$SamAccountName}}} | Export-Csv -NoTypeInformation c:\1.csv

Open in new window

0
How to concatenate $_ and "Test"
$y="$_" + "Test"

Currently it returns as Test and I want output as $_Test as an output.
0
I had this question after viewing Open successive arrays of URLs in IE.

I am using this code to determine whether to use an existing or new instance of IE:
$newInstance = $false
if (Get-Process iexplore -ea silentlycontinue | Where-Object {$_.MainWindowTitle -ne ""}) {
    $ie = (New-Object -COM "Shell.Application").Windows() | ? { $_.Name -eq "Internet Explorer" } | Select-Object -First 1
    $newInstance = $false
} else {
    $ie = New-Object -COM "InternetExplorer.Application"
    $newInstance = $true
}

# Elsewhere, I open an array of sites depending on what tabs are already open
foreach ($tab in (New-Object -COM "Shell.Application").Windows() | ? { $_.Name -eq "Internet Explorer" }) {
    if ($tab.LocationURL.Contains("~"))
    { $search = $true; break }
}

Open in new window

If a tab is open that has specified text in its title, how can I ignore that instance of IE, and use a second instance to open an array of sites in? I have tried this:
$ie = (New-Object -COM "Shell.Application").Windows() | ? { $_.Name -eq "Internet Explorer" -and $_.LocationName -like ""}
if ($null -ne $ie) {
    $ie = (New-Object -COM "Shell.Application").Windows() | ? { $_.Name -eq "Internet Explorer" } | Select-Object -First 1
    $newInstance = $false
} else {
    $ie = New-Object -COM "InternetExplorer.Application"
    $newInstance = $true
}

Open in new window

0
Please see below:

$(
$ServerArr = @()
$ServerArr = get-content servlist-sample.txt
ForEach ($item in $ServerArr){
$maxActive = $null
$driverClassName = $null
$rules_schema = $null
$data_schema = $null
$urlresult = $null
$servn = $item
cmd /C PsExec.exe -u domain\user -p somepassword \\$servn -accepteula -c -f tclogsprint.bat > tclogs.pth
$tchome = Get-Content tclogs.pth
write-host $tchome
$pspassword = ConvertTo-SecureString “somepassword” -AsPlainText -Force
$Cred = New-Object System.Management.Automation.PSCredential (“domain\user”, $pspassword)
remove-item tclogs.pth
if ($tchome -like 'C:\*'){
New-PSDrive -Name Mo -PSProvider FileSystem -Root \\$servn\c$ -Credential $Cred
$xmldata = [xml](Get-Content "Mo:$($tchome.Replace('C:\', '\'))\conf\context.xml")
}
if ($tchome -like 'D:\*'){
New-PSDrive -Name Mo -PSProvider FileSystem -Root \\$servn\d$ -Credential $Cred
$xmldata = [xml](Get-Content "Mo:$($tchome.Replace('D:\', '\'))\conf\context.xml")
}
if ($tchome -like 'E:\*'){
New-PSDrive -Name Mo -PSProvider FileSystem -Root \\$servn\e$ -Credential $Cred
$xmldata = [xml](Get-Content "Mo:$($tchome.Replace('E:\', '\'))\conf\context.xml")
}
Remove-PSDrive -Name Mo
$XPath = "Context/Resource"
$NodeResource = $xmldata.SelectSingleNode($XPath)
$urlresult = $NodeResource.GetAttribute("url")
$rules_schema = ($xmldata.SelectSingleNode("//Environment[@name='prconfig/database/databases/PegaRULES/defaultSchema']")).value
$data_schema = 

Open in new window

0
I have a CSV FILE as shown below and would like to convert Quantity column from scientific notation to Decimal format.

"Rate Set Date","Trader","Name","clear_agent","Tid","Quantity","Fund"
"12/20/17","test","USD FRA 3.31875 3MLIB 2017-12-20 2018-03-21 LCH","CSOTCLR",423665,2.0E9,"SYN"
"12/18/17","test11","USD FRA 3.31875 3MLIB 2017-12-20 2018-03-21","SYNGRN",365331,2.0E9,"SYN"
"12/18/17","test","USD FRA 1.453 3MLIB 2017-12-20 2018-03-21 LCH","CITOTCLR",726073,1.8E9,"TT2"

Is it possible in PowerShell?
0
Hi urgent query looking to get this done

Found below script at http://www.morgantechspace.com/2014/04/Create-Bulk-AD-Users-from-CSV-using-Powershell-Script.html

Have a test csv attached, I want to add exchange mailboxes and also 3 more security groups "Test members" "Test 2017" and "Test Wifi" what is the best way to do this?

Would it be just Add-ADgroup member "Domain Admins" "Test members" Test 2017" Test Wifi" $_."samAccountName";

Import-Module ActiveDirectory
Import-Csv "C:\Scripts\NewUsers.csv" | ForEach-Object {
 $userPrincinpal = $_."samAccountName" + "@TestDomain.Local"
New-ADUser -Name $_.Name `
 -Path $_."ParentOU" `
 -SamAccountName  $_."samAccountName" `
 -UserPrincipalName  $userPrincinpal `
 -AccountPassword (ConvertTo-SecureString "MyPassword123" -AsPlainText -Force) `
 -ChangePasswordAtLogon $true  `
 -Enabled $true `
 -EmailAddress $_."EmailAddress"
Add-ADGroupMember "Domain Admins" $_."samAccountName";
}

Test.csv
0
Has Powershell sent you back into the Stone Age?
LVL 6
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.

I am using this function to open successive arrays of URLs in IE each time the script is run.
  1. If $site is the first or only URL in the array, and IE is not open, then the URL opens in the first tab. On the next run, the next array is opened if $search = $true.
  2. If $site is the first or only URL in the array, and IE is open, then the URL opens in a new tab. QUESTION: On the next run, why is the same array opened?
  3. If $site is not the first or only URL in the array, then the URL opens in a background tab.

function OpenSites($sites) {
    $isFirstSite = $true
    foreach ($site in $sites) {
        if ($isFirstSite -eq $true) {
            if ($newInstance) {
                $ie.Navigate2($site)
            } else {
                $ie.Navigate2($site, $navOpenInNewTab)
            }
        } else {
            $ie.Navigate2($site, $navOpenInBackgroundTab)
        }
        $isFirstSite = $false
    }
}

$today = (get-date).DayOfWeek
switch ($today) { 
    "Someday" {
        $search = $false
        # Check if Google open
        foreach ($tab in $ie) {
            if ($tab.LocationURL.Contains("http://www.google.com/"))
            { $search = $true; break }
        }
        # If Google open on 2nd run, open Yahoo
        if ($search) {
            OpenSites -sites "http://www.yahoo.com/"
        } else {
            # 1st run
            OpenSites -sites "http://www.google.com/ncr","http://www.bing.com/"
        }
    }
}

Open in new window

0
I have a powershell script running on my Windows Server 2016. I have repeatedly changed the execution policy several times with the command below.

set-executionpolicy unrestricted -scope LocalMachine -Force

After I change policy
        Scope ExecutionPolicy
        ----- ---------------
MachinePolicy    Unrestricted
   UserPolicy    Unrestricted
      Process    Unrestricted
  CurrentUser    Unrestricted
 LocalMachine    Unrestricted

Open in new window


Here is the script I would like to run
Script I would like to run

After I try running it I get a popup letting me that the execution policy will be changed

Here is the error I get.
Set-ExecutionPolicy : Windows PowerShell updated your execution policy successfully, but the setting is overridden by a policy defined at a more specific scope.  Due to 
the override, your shell will retain its current effective execution policy of Unrestricted. Type "Get-ExecutionPolicy -List" to view your execution policy settings. 
For more information please see "Get-Help Set-ExecutionPolicy".
At line:5 char:1
+ Set-ExecutionPolicy RemoteSigned
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : PermissionDenied: (:) [Set-ExecutionPolicy], SecurityException
    + FullyQualifiedErrorId : ExecutionPolicyOverride,Microsoft.PowerShell.Commands.SetExecutionPolicyCommand

Open in new window




Now my my policies look like this after attempting to run script and getting error
        Scope ExecutionPolicy
        ----- ---------------
MachinePolicy    Unrestricted
   UserPolicy    Unrestricted
      Process    Unrestricted
  CurrentUser    Unrestricted
 LocalMachine    RemoteSigned

Open in new window



Also went into Local Group Policy editor and set "Turn on Script Execution" to "Enabled" and "All Scripts"
here is the link to change policy I already did this.

Change policy



Not sure what to do next
1
Hi

Need power shell script to check whether Operating system version is 2008 or 2012 and also need to check whether the firewall port is open for a particular port for a server

for example...160.254.210.xx  TCP port 1234

want to check firewalls port are open
0
Hi EE

Can someone help me modify this so it also counts the nested groups in the user object ?

GC Users.txt|GET-ADUSER –Properties name,MemberOf | Select-Object SamAccountname,@{n='GroupCount';e={ ($_.memberof).count }}
0
Hi

How to write a powershell script to check the account that was being disable in the AD .
0
Hi Experts

I have a PowerShell script that I currently run manually each month on a number of our office's servers which runs a MSSQL query and outputs to an .xlsx file using the PSExcel module.  After each run, I email the Excel report to the office manager for review before our marketing campaigns are run.

To try to automate the entire process to run on the first of each month, I've just tweaked the sql query and the PowerShell script to filter the query results for the previous month and output to the Excel file using the previous month's name.
I've started creating a batch file that I can use with Windows Task Scheduler to send the Excel file in an email via the old faithful blat.exe after calling the PS script.  

And here's my batch file so far:

@ECHO OFF
SETLOCAL

REM -- Setup date, time and logging --
Set day=%DATE:~7,2%
Set mm=%DATE:~4,2%
Set dd=%DATE:~7,2%
Set yyyy=%DATE:~10,4%

REM -- Setup email parameters --
Set EmailLogFile=C:\scripts-and-reports\logs\%yyyy%-%mm%-%dd%_-_Monthly_Report_Email_Log.txt
set EmailServer=mailserver.com
set EmailFrom=user@email.com
set EmailTo=recipient@email.com
set EmailSubject=Monthly PE new client report
set EmailBody=Please see attached new client report from your PE instance for review before forwarding to Person with any comments or changes.
set EmailAttachment=C:\scripts-and-reports\%yyyy%-%mm%-%dd% PE new clients.xlsx
REM Optional; leave empty if the user running the task can send directly to the smtp server:

Open in new window

1
Hello,

I am using the below commands to remove send as, send on behalf, and full access to user mailboxes:

remove-mailboxpermission, remove-recipientpermission, and set-mailbox

Instead of typing three commands, if there a way I can remove the delegate's all permissions in oneshot

Thanks.
0
Hello,

using below command line I can clear AD ID home folder path and set it to local path. I tried this script to execute on multiple users using import-csv with some variable , but its giving an error $importusers = get-content "C:\Users\Administrator\Desktop\new requriment\input.csv" |Set-ADUser $importusers -Clear HomeDirectory
Set-ADUser : Cannot validate argument on parameter 'Identity'. The argument is null. Supply a non-null argument and try the command again

Thanks in advance

Set-ADUser testuser -Clear HomeDirectory

Open in new window

0
i have a situation where i need to delete a specefic email sent from a particular user from all the mailboxes in exchange 2013 .but the subject name of this email is in arabic and exchange power shell is not accepting that subject name,

please tell me the way to delete it
0
Looking for the Wi-Fi vendor that's right for you?
Looking for the Wi-Fi vendor that's right for you?

We know how difficult it can be to evaluate Wi-Fi vendors, so we created this helpful Wi-Fi Buyer's Guide to help you find the Wi-Fi vendor that's right for your business! Download the guide and get started on our checklist today!

Hi all,

I would like to know if it is possible too check if an e-mail alias is being used?

Situation:
- 100x Office 365 E3 licenses
- Exchange Online
- Domain A
- Domain B

E.g.:
A user with name "Testuser" uses our default e-mail adres with our "Domain A" so his e-mail adress is "Testuser@domainA.com".
"Testuser" also has an e-mail alias setup with our "Domain B" so his e-mail alias is "Testuser@domainB.com".

We are pashing out our "Domain B" but to do so I would like to inventorise if there are e-mails being send to users with a "Domain B" alias.

I would like to know if anyone can help me achieve this?

I already found a Powershell command to see which mailboxes are using "Domain B" alias - maybe it can help you so:  

Get-Recipient -ResultSize unlimited| Where {$_.EmailAddresses -like "*@DomainB.com"} | FL DisplayName,EmailAddresses

Open in new window


I would like to thank you in advance!

Kind Regards,
1
I'm a newbie in PS. I'm trying to convert the following  test.tmp into a CSV file.
Note that there aren't any " " for the values like @{Caption = "Name1"..} . Instead I got @{Caption = Name1..} from a loop that runs:
Get-WmiObject -class win32_computersystem | select Model, Username, PSComputerName | Add-Content -path test.tmp

test.tmp:
@{Model=VMware Virtual Platform; Username=; PSComputerName=Name1}
@{Model=VMware Virtual Platform; Username=user2; PSComputerName=Name2}
@{Model=VMware Virtual Platform; Username=user1; PSComputerName=Name3}

The more simple solution, the better ;-)
Thanks!
0
Hello,

I'm setting up a test RDS server in our environment for testing before I deploy one in production. I would like to create a GPO for the start menu and all the guides I've read reference the "Export-SatrtLayout" cmdlet in powershell. Every time I run the command I get a COM error. I'm running powershell with elevated permissions but still no luck. It does create the xml file but the file is defiantly not complete.


Screenshot_2017-09-12_12-14-00.png
OS: Windows Server 2016
Build 14393.rs1
Release 170731-1934

Any suggestions would be appreciated.
0
Using below script I am to move single ADuser to OU, when i tried to move multiple users by adding get-content with variable its giving an error. Thanks in advance

Get-ADUser -Identity testuser| Move-ADObject -TargetPath "OU=disabledounew,DC=test,DC=com"

Open in new window

0
We are running "VMware VirtualCenter Server" Service with specific Service Account. The problem is that the service is getting stopped because of logon failure error and we have to re-enter the Service Account username and password to start the service.

I am looking for a PowerShell script that will do the following-

1. Check the service status.

2. If the service is "Stopped", the script will set the Service Account username and password in Log On account TAB.

Log On
3. Start the service.

Need your help to achieve the same.
0
Below script is working fine, script will remove member off groups in AD account , expect Domain users group.

Can we able to remove domain users group as well , when script executes? Thanks in advance



Foreach ($user in Get-Content "C:\Users\Administrator\Desktop\input1.txt") {
    $report = "C:\Users\Administrator\Desktop\groups_$((Get-ADUser $user -properties SamAccountName).SamAccountName)_$(Get-date -f dd-MM-yyyy).txt"
    "=============== UserName $user ===============" >> $report
    $Groups = (Get-ADUser $user -Properties memberof).memberof
    $Groups | Get-ADGroup | Select -ExpandProperty Name >> $report
    $Groups | Get-ADGroup | Remove-ADGroupMember -member $user -Confirm:$false
}A

Open in new window

0

Powershell

15K

Solutions

7K

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.