Powershell

19K

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

Hello,

This is the current working script right now that I have to pull 2 columns in a existing CSV and create a new Column

$CSV = Import-Csv C:\temp\csvmerge.csv -Header $headers

$CSV | Select EmployeeID, Zipcode, @{n='Password'; e={"9875" + $_.EmployeeID+'#'+ $_.Zipcode}} | Export-CSV C:\temp\fullname.csv

Open in new window


What I want to get is the last 3 digits of the employee ID and the first 5 digits of the Zipcode to create the password in the Password column for each row. Right now it just pulls the full EmployeeID and full Zipcode.

Any way to get the last 3 of EmpID and the first 5 digits of the Zipcode instead?
0
OWASP: Threats Fundamentals
LVL 13
OWASP: Threats Fundamentals

Learn the top ten threats that are present in modern web-application development and how to protect your business from them.

I have attached a PowerShell script that was written to take the 'year' ID3 tag of an mp3 file, create a corresponding folder of the decade to which it belongs (ex: 1960s, 1970s, 1980s) and then move it to that respective folder.

When I attempt to run it, it does nothing. No output, no errors. I have tried running it from PowerShell ISE, Windows PowerShell prompt, and calling it via the command line (powershell c:\scripts\mp3.ps1) all when run as administrator.

Looking in the Event Viewer, there are 8 events produced, but nothing of anything discerning to me that speaks to why it won't run. Here are the events in sequence:

Provider "Registry" is Started.

Details:
      ProviderName=Registry
      NewProviderState=Started

      SequenceNumber=1

      HostName=ConsoleHost
      HostVersion=5.1.18362.145
      HostId=61667b5b-06d4-4f03-a57d-bef692dd47c2
      HostApplication=powershell c:\scripts\mp3.ps1
      EngineVersion=
      RunspaceId=
      PipelineId=
      CommandName=
      CommandType=
      ScriptName=
      CommandPath=
      CommandLine=

Provider "Alias" is Started.

Details:
      ProviderName=Alias
      NewProviderState=Started

      SequenceNumber=3

      HostName=ConsoleHost
      HostVersion=5.1.18362.145
      HostId=61667b5b-06d4-4f03-a57d-bef692dd47c2
      HostApplication=powershell c:\scripts\mp3.ps1
      EngineVersion=
      RunspaceId=
      PipelineId=
      CommandName=
      CommandType=
      ScriptName=
      CommandPath=
      CommandLine=

Provider "Environment" is Started.

Details:
      ProviderName=Environment
      …
0
Hello experts,

I have the following ahk file attached.
I am looking for a procedure that covers the following needs:
-Read ahk file
-Generate an Output-(file-name-of-ahk-file)_yyyymmdd_hhmmss.csv file with headers: Item; Hotkeys and the following
     -Based on information read of ahk file, report the second text line after the following line: ";===================================
      Instructions & Variables information should not be reported in the csv file
     -Based on information read of ahk file, report the right after line which finish & or contains with ::
I attached dummy-file and output-file as I expect that the procedure generate csv file.

Windows Batch & Powershell & VB Script approaches are more than welcome.
If you have questions, please contact me.

Thank you for your help.
Dummy-file.ahk
Output-dummy-file_20190919_025352.csv
0
i have following commands which i run manually on a server by opening command prompt.

tabadmin stop

tabadmin clean up

tabadmin start

Is there any way i can automate this task by task scheduler .

can i save this in txt format file and save in .ps1 script but i am not sure
how to do it.
0
I'd like to search a large text file in Windows and remove the blank line after a line that contains a specific string.

Here's a snippet of the file content which contains the string:

  COMPILE SPECIFICATION
    PLSQL_OPTIMIZE_LEVEL=  2
    PLSQL_CODE_TYPE=  INTERPRETED
    PLSQL_DEBUG=  FALSE    PLSCOPE_SETTINGS=  'IDENTIFIERS:NONE'   <-- this is the string
  <-- this is the blank line.
/

I want the string to be without the blank line before the "/" like below:

  COMPILE SPECIFICATION
    PLSQL_OPTIMIZE_LEVEL=  2
    PLSQL_CODE_TYPE=  INTERPRETED
    PLSQL_DEBUG=  FALSE    PLSCOPE_SETTINGS=  'IDENTIFIERS:NONE'
/

I opened the file in Notepad++ and can see the CRLF at the end of the lines.  Can't figure out how to get Notepad++ to do this for me.

It seems Powershell should be able to do it.  
But I can only find examples (that I can understand) which remove all carriage returns rather than the carriage return after a specific string.
Or it removes all blank lines, but I don't want to do this for ALL blank lines.  I only want to remove the blank line after that particular string.

Much appreciation for your help.
0
Is there a way to PREVENT users from downloading and installing the Microsoft Teams app on Windows 10?
0
Hi,

Please see https://www.experts-exchange.com/questions/29154913/Powershell-and-jsons-to-a-Mongodb-PS-management-mongodb-itemd.html
I seem to be able to connect to my db, but I can't see if I am connected. Database and collection exist, I can see this via MongoDB gui.
Got error below. Please advise.

$MongoDbServer = 'Myserver:27017
#$Port = '27017'

$DatabaseName = 'TestDB'
$CollectionName = 'TestCollection'
$ConnectionString = "mongodb://$MongoDb/$Databasename"


Connect-Mdbc -ConnectionString $ConnectionString -DatabaseName $DatabaseName -CollectionName $CollectionName
#No error here
Get-MdbcData -Collection $CollectionName
#Then the error
Get-MdbcData : Cannot bind parameter 'Collection' to the target. Exception setting "Collection": "Unexpected type of parameter or variable Collection."
At line:1 char:26
+ Get-MdbcData -Collection $CollectionName
0
Hello,

Looking to filter a .csv file that contains 15 columns, but I'm only focusing on 2.

My issue that I run into is that I have 2 -eq in my script that export the .csv with nothing. If I remove one of the -eq i get results!

Here is my code:

Import-CSV -path "C:\temp\test1.csv" |

? Column1 -eq "Value1" |

? Column1 -eq "Value2" |


? Column2 -notmatch "Value3" | 

? Column2 -notmatch "Value4" |

? Column2 -notmatch "Value5" |

? Column2 -notmatch "Value6" |

? Column2 -notmatch "Value7" |

? Column2 -notmatch "Value8" |

? Column2 -notmatch "Value9" |


export-csv "C:\temp\test2.csv"

Open in new window


Any ideas on how to bring all the info i need into 1 file?
0
export-csv -Append $filename -NoTypeInformation

-Append not working since I'm using PowerShell version 2

Is there any alternative to use -Append in export-csv ?



$filename= "PingLog-"+$env:computernameToPos+"-"+(Get-Date).tostring("yyyy-MM-dd")+".csv"  
while ($true) {
   $info = Get-Content "machineList.txt" | foreach{

       $comp = $_
       If ($result = Test-Connection $comp -Count 1 -ErrorAction SilentlyContinue | Select @{n='TimeStamp';e={Get-Date -format u}},@{n='Destination';e={$comp}},IPV4Address,ResponseTime,Status){
           $result.Status = "Active"
           $result    
       }else{
           "" | Select @{n='TimeStamp';e={Get-Date -format u}},@{n='Destination';e={$comp}},IPV4Address,ResponseTime,@{n='Status';e={"Inactive"}}
       }


   }

   

   $info | export-csv -Append $filename -NoTypeInformation

}
0
I am writing a cmd file to utilize robocopy as an automated backup. I want to create a new log every time it runs that is date stamped as part of the log name. I am using the script below. The log was named Tue09172019-8212265Home. However I want the format to be yyyymmdd-hhmm so in this case 20190917-0821Home.


set tdate=%date: =%
set tdate=%tdate:/=%
set ttime=%time::=%
set ttime=%ttime:.=%
set ttime=%ttime: =%


Robocopy G:\Home F:\Home /e /b /xo /copyall /dcopy:DAT /mt /LOG:F:Logs\%tdate%-%ttime%Home.log /NFL /NDL
0
Announcing the Winners!
LVL 13
Announcing the Winners!

The results are in for the 15th Annual Expert Awards! Congratulations to the winners, and thank you to everyone who participated in the nominations. We are so grateful for the valuable contributions experts make on a daily basis. Click to read more about this year’s recipients!

Hi,

Im trying to put a script together that imports from a CSV to create a user in AD,
the script creates the user but I can't get the UPN correct, I have:

$dnsroot = '@' + (Get-ADdomain).dnsroot

$UPN = ("$_.samaccountname + $dnsroot")

Open in new window


How would I just use the field samaccountname from the CSV?

Thanks,
0
Hello,

I search to write a script powershell for create a task on windows 2008 or 2012 :
  #Creates Scheduled Task Actions
    $TaskAction1 = New-ScheduledTaskAction -Execute 'PowerShell.exe' -Argument "-ExecutionPolicy Bypass -File ""e:\temp\wind_v2.ps1"" `-WriteLogOnly $true"

    #Creates Triggers
    $TaskTrigger  = New-ScheduledTaskTrigger -AtStartup
           
    #Assigns UserName
    $TaskUserName = New-ScheduledTaskPrincipal -UserID "NT AUTHORITY\SYSTEM" -LogonType ServiceAccount -RunLevel Highest

    #Creates Scheduled Task Settings
    $TaskSettings = New-ScheduledTaskSettingsSet -AllowStartIfOnBatteries

    #Creates Triggers
    $TaskTrigger  = New-ScheduledTaskTrigger -AtStartup
           
     #Create Scheduled Task
     $Task = New-ScheduledTask -Action $TaskAction1 -Principal $TaskUserName -Trigger $TaskTrigger -Settings $TaskSettings
           
     #Register Scheduled Task
     Register-ScheduledTask "DBA_Daily_Schedule_Cmdb" -InputObject $Task -Force

     #Configure Scheduled Task
     $Task = Get-ScheduledTask -TaskName "schedule"
     $Task.Triggers.Repetition.Interval = "P1D"

     #Update Scheduled Task
     $Task | Set-ScheduledTask -User "NT AUTHORITY\SYSTEM"
}

New-ScheduledTaskAction : The term 'New-ScheduledTaskAction' 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 …
0
I have setup a custom curfew rule in Office 365 to turn off email based on membership of email group. Basically in the evening it turns on a mail transport rule that passes any new email to the Office 365 Quarantine. Then in the morning it disable that rule and releases everything in Quarantine with a -Type TransportRule

Whilst this works fairly well some email doesn't get released (I think due to the page size 100 default).

I would like to delete everything in the Quarantine that has a Released Status of Yes using the Delete-QuarantineMessage cmdlet but unfortunately it doesn't seem to have a Released Status switch :(

Any thoughts on to how I could achive this?
0
Hello experts,
I am looking for a script to replace single space or multiple spaces at files and folders located in a root folder by "-" characters
The idea is to have as variables:
      The character that is going to replace single or multiple spaces
      Drill down mode flag
Powershell & VB Script & Windows Batch approaches are more than welcome.
Thank you for your help.
0
I am trying to convert a csv file into a xls through a powershell script so that it will be viewable on sharepoint 365, without users having to convert the file, or open it in a thick client.

Any help is greatly apprenticed.

thanks

I am attaching a copy of one of the csv files i am working with.
SCORECARD-G3-MATH-RS.csv
0
Via Powershell, how can i enable or disable only the Exchange feature of the O365 product license?  For example, in the screenshot, i want to disable sway.  Is this possible?e3.JPG
0
Morning all,

So, this script run absolutely perfectly.

$HTMLHead = @"
<style>
  BODY {background-color: white; font-family: Arial; font-size: 10px }
  TABLE { border-width: 1px; border-style: solid; border-color: black; border-collapse: collapse; }
  TH { text-align: left; border-width: 1px; padding: 5px; border-style: solid; border-color: black; background-color: CornflowerBlue ; color: white }
  TD { border-width: 1px; padding: 5px; border-style: solid; border-color: black; }
  TR:nth-child(odd) { background-color: aliceblue; }
  TR:nth-child(even) { background-color: white; }
  h1 { color: red; font-size: 18px }
  h2 { color: red; font-size: 18px }
  h3 { color: black; font-size: 12px }
</style>
"@ 

$Ous = "OU=01.DN",
       "OU=02.Non-Employees,DN"

$ObjectFilter        = "^\d{4}$"
$RetrievalProperties = @("distinguishedName","EmployeeID","Name","AccountExpirationDate","LastLogonDate","Manager","Office","C","Company")

$AllEmployeeAccounts = Foreach ($ou in $Ous) {get-aduser -filter {(EmployeeID -notlike "*" -or employeeID -like "NE*")}  -SearchBase $OU -SearchScope Subtree -Properties $RetrievalProperties}
$NonEmployeeAccounts = $AllEmployeeAccounts | Where-Object {$_.employeeid -notmatch $ObjectFilter} 

$OutputList = @()

foreach ($NonEmployeeAccount in $NonEmployeeAccounts)
{
    $ManagerName = "<empty>"
    $ManagerName = ($AllEmployeeAccounts | Where-Object{$_.distinguishedName -like $NonEmployeeAccount.Manager}).Name 

    $OutputObject = New-Object 

Open in new window

0
So there are a few dozen inbox rules for a mailbox that have the right user (such as John.Doe, but the wrong domain (@wrongdomain.com).
So I'm trying to get John.Doe@wrongdomain.com set to JohnDoe@correctdomain.com in the inbox rule.

I can get all the rules:
$AllFwdRules = Get-InboxRule -Mailbox "Mailbox" | ? {$_.ForwardTo -like "wrongdomain.com"}.
If I do: $AllFwdRules | select -first 1 | select ForwardTo
I see a couple addresses there in this output:

ForwardTo : {"John Doe" [SMTP:john.doe@wrongdomain.com], "Pat Doe" [SMTP:Pat.Doe@wrongdomain.com]}

For the Set-InboxRule paramters, it tells -ForwardTo can take an e-mail address.
So what I'm trying to do is just get the wrong address, replace the domain with @correctdomain.com, then set it (or multiple if so) for the ForwardTo property back on the rule.
Does anyone know how this can be done?
0
Hi,

I just a tool from MS gallery site: Download Office365-Exchange-Tool.exe

https://gallery.technet.microsoft.com/office/Office-365-Exchange-Online-4ceee521

And realized that this from AdminDroid

I'm confused now:

1- Is it a free tool or we will finish to paid at the end of trial period?

2- Because it is from MS site I'm suppose it's a trusted tool

3- Are all tool or script provided by MS in their gallery site have been tested by MS team?
0
Python 3 Fundamentals
LVL 13
Python 3 Fundamentals

This course will teach participants about installing and configuring Python, syntax, importing, statements, types, strings, booleans, files, lists, tuples, comprehensions, functions, and classes.

Hi,
We need to export members of a SharePoint user group to a text file on a schedule. I found below sites with a script that can do that.
(http://sharepoint-works.blogspot.com/2013/01/export-sharepoint-group-to-excel-using.html)
(https://chaddtalks.wordpress.com/2015/10/05/export-a-list-of-users-from-a-specific-sharepoint-group/)

$SiteUrl="https://portal.site.com";
$GroupName="Site Members";
$Output = @("GroupName|Name|Login|Email|Department|Title")
$web = Get-SPWeb $siteUrl
$site = $web.Site
$rootWeb = $site.RootWeb
$UserList = $rootWeb.Lists["User Information List"]
$web.SiteGroups[$groupName].Users|%{$user = $UserList.GetItemById($_.ID)
if($user -ne $null)
{
$JobTitle = $user["JobTitle"]
$Department = $user["Department"]
}
$Output += ($groupName+"|"+$_.Name+"|"+$_.UserLogin+"|"+$_.Email+"|"+$Department +"|"+$JobTitle)
}
$rootWeb.Dispose()
$web.Dispose()
$site.Dispose()
$Output > "GroupMembers.csv"


When I run the script , it dumps the users to csv file but I'm getting a bunch of below errors. Is there a way to fix the script so it won't have these errors?

You cannot call a method on a null-valued expression.
At C:\export.ps1:9 char:37
+ $web.SiteGroups[$groupName].Users|%{$user = $UserList.GetItemById($_.ID)
+                                     ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : InvalidOperation: (:) [], RuntimeException
    + FullyQualifiedErrorId : InvokeMethodOnNull

Thank you.
0
hello,

i have a powershells cipt to create shared folder and apply ntfs right on the file server, but now i have error:

the script:

$csvFile = "D:\test.csv"

$create = Import-CSV $csvFile

function DoPermissions
{
    param( $permissionGroup, $folder, $level, [switch] $NoInheritance)
    $toAdd = $permissionGroup -split ";"
    $InheritFlags = if ($NoInheritance) { 'None' } else { 'ContainerInherit,ObjectInherit' }
    Write-Host $folder
    foreach ($item in $toAdd)
    {
        $acl = (Get-Item $folder).GetAccessControl('Access')
        $ar = New-Object System.Security.AccessControl.FileSystemAccessRule($item, $level, $InheritFlags,'None','Allow')
        $acl.SetAccessRule($ar)
        Set-ACL -path $folder -AclObject $acl
    }
}

foreach ($folder in $create)
{
    $fullPath = $folder.folder #$path + $folder.folder
    if (!(Test-Path $fullPath)) {
      New-Item -ItemType Directory -Path $fullPath
      $fAcl = Get-Acl -Path $fullPath
      $fAcl.SetAccessRuleProtection($true, $true)
      Set-Acl -Path $fullPath -AclObject $fAcl
    }

    if ($folder.full_control) {DoPermissions $folder.full_control $fullPath "FullControl"}
    if ($folder.modify) {DoPermissions $folder.modify $fullPath "Modify"}
    if ($folder.read_execute) {DoPermissions $folder.read_execute $fullPath "ExecuteFile"}
    if ($folder.list_folder_content) {DoPermissions $folder.list_folder_content $fullPath "read,ExecuteFile" -NoInheritance}
    if ($folder.read) {DoPermissions 

Open in new window

0
I'm attempting to produce a cim query or filter that will allow me to narrow my search results.
Currently I can use this
get-ciminstance win32_service | where {$psitem.name -in @($svcs)}
but I believe there should be a similar way using filter or even a query, yet I've been unable to find anything that works...
0
I am looking for a solution to search and replace environment variables, either to run locally on each machine, or remotely to achieve the following:-

Each machine may have a number of the following entries in either the system, or user environment variables :
xxx_LM_LICENSE_FILE: 1660@server1
yyy_LICENSE_FILE: 2101@server1
zzz_LICENSE_FILE: C:\LIC\LICENSE.TXT;2100@server1;1655@server1

I need to replace "server1" to licsvr.domain.com, and the xxx, yyy, zzz could be any text
Each machine may have none, some, or all of the above examples
Also as shown there could be multiple entries per line that would need replacing

Therefore the resulting output would be
xxx_LM_LICENSE_FILE: 1660@licsvr.domain.com
yyy_LICENSE_FILE: 2100@licsvr.domain.com
zzz_LICENSE_FILE: C:\LIC\LICENSE.TXT;2100@licsvr.domain.com;1655@licsvr.domain.com

Can someone offer some scripts that might be suitable
Thanks in advance
0
I had this question after viewing tool to generate passwords for active directory users.

I usually use this cmdlets to create users in AD using powershell:
import-csv C:\temp\ADUsers.csv | 
foreach {New-ADUser -name $_.name -displayName $_.displayname 
-OtherAttributes @{'company'= $_.company;'department'= $_.Department;'pager'= $_.pager;'mobile'= $_.mobile;'UserPrincipalName'= (“{0}@{1}” -f $_.name,”test.net”)} 
-Enabled $true }

Open in new window


My issue is, I couldn't use the password generation cmdlets from the solution in this post tool to generate passwords for active directory users  in my script, I don't know how to make it work with my script, I'm not that professional in powershell.

any other cmdlets are welcomed :)

keep in mind that the password policy in my company is 9 characters at least, 1 capital letter at least, 1 small letter at least, and 1 number at least
0
I am looking for a PowerShell script that should snap a picture from the computers camera and send me an email alert, can anyone help?

I have no knowledge with powershell scripting (I should but did not get there)
0

Powershell

19K

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.