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

Create printer of port type Standard TCP/IP

The code below creates printer with port type as local Port. I need the port type to be Standard TCP/IP
Any help will be very appreciated

Thank you

@echo off
setlocal
for /f %%a in (CompPrinterConf.txt) do (
	@echo starting pnpport on %%a
	cscript.exe "C:\windows\system32\Printing_Admin_Scripts\en-US\prnport.vbs" -a  -s %%a -r "printer1" -h hostname -o raw -n 9100
	@echo Waiting 5 seconds
	timeout 5
	@echo starting setting MyPrinter on %%a
	cscript C:\Windows\System32\Printing_Admin_Scripts\en-US\prnmngr.vbs -a  -p "Myprinter" -m "Generic / text only" -r "printer1" -s %%a
	REM Not really needed, because the script will continue with the next machine
	REM timeout 5


)

Open in new window

0
CompTIA Network+
LVL 19
CompTIA Network+

Prepare for the CompTIA Network+ exam by learning how to troubleshoot, configure, and manage both wired and wireless networks.

Hello,

I have a list of Windows 10 machines in a text file that I need to remove a printer named "Prt-lkm" from.

I need Powershell to loop through each machine in the list and remove that printer. I have tried a couple of iterations, but I'm missing something in each.

What is the best way to do this?
0
Is there a way via powershell/scheduled task, or software/app or other solution that we can see if a windows machine lost its trust with the domain?

Since it's a occurring issue at my job, I was hoping to execute something and generate reports to hand off to my Ops team

Thank you.
0
Using Powershell, is there a way to read from a directory all the folder (folder names), save them to an Excel file, in Excel, and in an adjacent column, provide a new Folder name, and then via the script, apply the new name based onto the folder, based on its old name.

Your thoughts are appreciated.
0
Powershell code to explain
I have this powershell code below. I need someone to explain the text in bold put below the Code.

## csv file with machines and user names to process:
$csv = 'c:\Scripts\Computers.csv'
## Absolute local file path on the clients:
$filePath = 'C:\test.txt'

$pattern = '(-username\s+)\S+'
Import-Csv -Path $csv | ForEach-Object {
	$computer = $_.ComputerName.Trim()
	$newUser = $_.NewUsername.Trim()
	$fileUNC = "\\$($computer)\$($filePath.Replace(':', '$'))"
	Write-Host "Processing $($computer), new user '$($newUser)' ..." -NoNewline
	Try {
		$content = Get-Content -Path $fileUNC -ErrorAction Stop
		$content -replace $pattern, "`$1$($newUser)" | Set-Content -Path $fileUNC -Force -ErrorAction Stop
		Write-Host " OK" -ForegroundColor Green
	} Catch {
		Write-Host " FAILED: $($_.Exception.Message)" -ForegroundColor Red
	}
}

Open in new window





$pattern = '(-username\s+)\S+'
Import-Csv -Path $csv | ForEach-Object {
      $computer = $_.ComputerName.Trim()
      $newUser = $_.NewUsername.Trim()
      $fileUNC = "\\$($computer)\$($filePath.Replace(':', '$'))"
      Write-Host "Processing $($computer), new user '$($newUser)' ..." -NoNewline
      Try {
            $content = Get-Content -Path $fileUNC -ErrorAction Stop
            $content -replace $pattern, "`$1$($newUser)" | Set-Content -Path $fileUNC -Force -ErrorAction Stop
            Write-Host " OK" -ForegroundColor Green
      } Catch {
            Write-Host " FAILED: $($_.Exception.Message)" -ForegroundColor Red
      }
}
0
s+ and S+ meaning in Powershell

Can someone explain the usage of  S+ and s+ in powershell, example:
$pattern = '(-username\s+)\S+'

Open in new window


Thank you
0
Hello

I'm having some issues doing a mailbox export:

Unable to open PST file '\\172.16.200.253\Backup\Exchange\something.pst'. Error details: Access to the path
'\\172.16.200.253\Backup\Exchange\something.pst' is denied.
    + CategoryInfo          : NotSpecified: (:) [New-MailboxExportRequest], RemotePermanentException
    + FullyQualifiedErrorId : [Server=EX-SX-01,RequestId=65a2fb01-ab0d-4897-a021-56eddb92b1bd,TimeStamp=12/12/2019 8:4
   1:01 AM] [FailureCategory=Cmdlet-RemotePermanentException] 367B53CE,Microsoft.Exchange.Management.Migration.Mailbo
  xReplication.MailboxExportRequest.NewMailboxExportRequest
    + PSComputerName        : ex-sx-01.domain.local

Open in new window


clearly some authorisation issue... In what "context" does the interactive PowerShell execute? The "launching" user is definitely able to access the \\172.16.200.253\Backup\Exchange UNC path so I guess the command does not run within that context ?
0
I'm looking for a way to delete the first 2 white spaces from the name of folders / files.

Example: AB 123 John Accounting Department, would become AB123John Accounting Department
Appreciate the thoughts.
1
Hi,

In O365, is it possible to give access to Quarantine page to technicians without giving admin access?

I want them to be able to release quarantined emails.
0
Hello experts,

Most of my EE questions are related to a directory created in my machine.
in order to properly manage this process, I would like to set up and AutoHotkey to cover the following requirement:
Once I select a file, I would like to activate an AutoHotkey to rename the selected file with current directory name.

Example:

If this file is located at Download directory.
20191211_152815-screenshot.pngI select the file and activate the AutoHotkey it should be rename it as following:
20191211_152858-screenshot.png
If you have questions, please contact me.

Thank you for your help.
0
Python 3 Fundamentals
LVL 19
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.

Dear expert

See script code below:
$serverlist = Get-Content -Path 'c:\Scripts\serverlistOP.txt'
try{
foreach ($server in $serverlist) {
$server
query user /server:$server
}
}
catch{
"$Server do not have users"
}

Open in new window


Error return like this:
query : No User exists for *
At line:5 char:1
+ query user /server:$server
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : NotSpecified: (No User exists for *:String) [], RemoteException
    + FullyQualifiedErrorId : NativeCommandError
 
And this:
query : Error 0x000006BA enumerating sessionnames
At line:5 char:1
+ query user /server:$server
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : NotSpecified: (Error 0x000006B...ng sessionnames:String) [], RemoteException
    + FullyQualifiedErrorId : NativeCommandError
 
Error [1722]:The RPC server is unavailable.
the RPC error in catch, I would like to show in catch message, RPC is unavailable, and  query : No User exists for * I want to show text: No users currently login now.

How do I corret show those?

Thanks
1
Hello experts,

I have the following powershell function which allows me to output log file.

$currentDir = Split-Path $script:MyInvocation.MyCommand.Path
$logFile = "$($currentDir)\log-file.log"

Function Write-Log {
	Param([Parameter(ValueFromPipeline=$true)][string]$Message)
	Process {
		 Add-Content -Value "[$(Get-Date -Format 'yyyyMMdd_HHmmss')] $($Message)" -Path $Script:logFile -PassThru |
			Write-Host
	}
}


Write-Log "Example of log function"

Open in new window


I was wondering how to modify :
$logFile = "$($currentDir)\log-file.log"
to $logFile = "$($currentDir)\log+"-filenameofps1withoutextension").log
-File name of ps1 in which is reported the function.

Thank you for your help.
1
Hello Experts,
How to delete files which arebased on modified / created date being less than 01-Jan-2018
I have a working code which delete files which has date beginning 2017 or before., any help will be great.
Get-ChildItem -Path "C:\Temp\*.*" -File -Recurse |
	Where-Object {($_.BaseName -match '^(?<yyyy>\d{4})\.(?<MM>\d\d)\.(?<dd>\d\d)(?<Name>.*?)$') -and ([int]$Matches.yyyy -le 2017)} |
	Remove-Item -Verbose -WhatIf

Open in new window

1
I use this script to register a scheduled Task

$Trigger= New-ScheduledTaskTrigger -At 7:01am -Daily
$User= "NT AUTHORITY\SYSTEM"
$Action= New-ScheduledTaskAction -Execute "PowerShell.exe" -Argument "-File D:\scripts\Get_Stuff_DO_Stuff.ps1"
Register-ScheduledTask -TaskName "TASKXYZ" -Trigger $Trigger -User $User -Action $Action -RunLevel Limited –Force

The business require a second trigger added at 7:01pm, therefore my question how to add a second trigger to this task. Many thanks String
0
I have a Powershell script that works when I run it manually but not when I run it as a Scheduled Task.

I am running the Scheduled Task as the same user (for both Powershell & Task Scheduler) with "Run whether users is logged on or not" selected.

I have setup Group Policy as follows: Windows Settings -> Security Settings -> Local Policies -> User Rights Assignment -> “Access to this computer from the Network” AND “Allow logon locally” ~ Both of those locations contain the User I'm running the Scheduled Task under.

When I run this as a Scheduled Task it immediately bombs out.

What's going on here? Can someone help me figure out what's happening? I would love to get this Powershell script to run as a Scheduled Task.
0
I need to add multiple printers from my print server to a computer which need those printers
The location of printers are
\\S-PRINT001.domainA.local\LAS0001
\\S-PRINT001.domainA.local\LAS0002
\\S-PRINT001.domainA.local\LAS0003
\\S-PRINT001.domainA.local\LAS0004
\\S-PRINT001.domainA.local\LAS0005
\\S-PRINT001.domainA.local\LAS0006
\\S-PRINT001.domainA.local\LAS0007
\\S-PRINT001.domainA.local\LAS0008
\\S-PRINT001.domainA.local\LAS0009

And the Name of the computer S-APP007.domainA.local

Before write a little script, i try this powershell command in remote session
Add-Printer -ConnectionName "\\S-PRINT001\LAS0001" -CimSession S-APP007
The command doesn't work
0
Afternoon all,

Is it possible to pipe in a list of usernames to SCCM and have it pump out the machine they last logged onto? I thought the get-CMUserDeviceAffinity would do it but it appears it won't take the username and give me a machine name.

Thanks
alex
0
1
Hi,
I have this powershell script to rename a file
Please refer to question

https://www.experts-exchange.com/questions/29166314/Loop-in-all-folders-and-subfolders-to-rename-a-file-given-a-directory-path.html?anchor=a42993161¬ificationFollowed=242183186#a42993161

The script at the moment cannot handle  file name :
Filename DD-MM-YYYY

Result expected:

YYYY.MM.DDFilename

It should also handle filenames with no date at all example:
Scenerio1 : Filenamefirstname, filenamelastname- filenamenotes 23.11.94.pdf
Scenerio2 : Filenamefirstname, filenamelastname- filenamenotes 23-11-94.pdf
Scenerio3 : Filenamefirstname, filenamelastname- filenamenotes




Get-ChildItem -Path "C:\Temp\*.*" -File -Recurse |
	Where-Object {$_.BaseName -match '^(?<Head>.*?)\s*(?<dd>\d\d)\.(?<MM>\d\d)\.(?<yyyy>\d{4})$'} |
	Rename-Item -NewName {"$($Matches.yyyy).$($Matches.MM).$($Matches.dd)$($Matches.Head)$($_.Extension)"} -WhatIf

Open in new window


Any suggestions?
0
Angular Fundamentals
LVL 19
Angular Fundamentals

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

Hi all i dont know if there is a way but i khave a site i have just taken over and it is still running windows 8.1 and i need to upgrade them all to 10, the issues is its over two offices and i cant be bothered driving out to them all, is there a script, powershell, batch, pythen, that i can run to get the pc to do it
0
Morning

$HRusers = import-csv 'C:\temp\HR Datanew.csv'
Foreach ($HRUser in $HRusers){Get-ADUser -Filter {(GivenName -eq $HRuser.Firstname) -and (Surname -eq $HRuser.surname)} | select-object Samaccountname, DisplayName, Surname, Firstname | Export-csv c:\temp\HRrestructured.csv -Append}

Open in new window


So, what this is meant to do is pair both the first name and surname and then pump out all the other details for me. For some reason I'm getting the following error

Get-ADUser : Property: 'Firstname' not found in object of type: 'System.Management.Automation.PSCustomObject'.
At line:2 char:31
+ ... n $HRusers){Get-ADUser -Filter {(GivenName -eq $HRuser.Firstname) -an ...
+                 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : InvalidArgument: (:) [Get-ADUser], ArgumentException
    + FullyQualifiedErrorId : ActiveDirectoryCmdlet:System.ArgumentException,Microsoft.ActiveDirectory.Management.Commands.GetADUser

I'm wondering if I need to pull all users and then do a

Where-object {(GivenName -eq $HRuser.Firstname) -and (Surname -eq $HRuser.surname)}" after the get-aduser -filter *

Open in new window


Any help would be great.

Thanks,
Alex
1
Morning,

So I have an excel sheet, it's got the "lastname, firstname middle name"  exactly like that, I need to remove the middle name for all in this list.

I'm thinking some sort of excel macro, could someone help out with this one? I'd take a powershell script as well. Anything that works pretty much ;-)

Thanks
Alex
0
Hello experts,

I have more than 90 AutoHotkey/Hotstring scripts reported in my AutoHotkey/Hotstring file that I use on a daily basis.
Sometimes I forgot the ones's that I don't use frequently. I was wondering how do you manage this and if there is an approach to display the various AutoHotkey/Hotstring reported in the file. The idea will be to relate to another AutoHotkey so when I call it, it reads and displays in the clipboard or a combobox the various AutoHotkey/Hotstring reported in the file so I can swiftly access to the one that I forgot and call it. My various AutoHotkey/Hotstring have a comment above of each of them with the following structure:
Example:

;====================================
;Run Excel 
;====================================

#!e::
If (FileExist(Excel32))
  Run,%Excel32%
Else
If (FileExist(Excel64))
  Run,%Excel64%
Else
  MsgBox,4112,Error,Neither 32-bit nor 64-bit Excel exists on this system
Return

Open in new window


Therefore I was thinking to read the AutoHotkey/Hotstring file and select just the comment and the next line which contains "::" which is the AutoHotkey/Hotstring. Then if I have it in a clipboard I can paste it notepad++ and launch the search of the AutoHotkey/Hotstring that I am looking for.
Let me know what do you think or if you have another proposal.

Thank you for your help.
0
We have ADFS 2012r2

I need to run power shell command
Enabling alternate ID for users logging

Right now they use email address

Can they use Sam account name

Like domain\ username
0
Read from Text File and Replace String using Powershell

For now , I have this command below that works fine when I run it against one remote computer named Windows7 and Replacing one string "username" with "white"
but when I have many computers, then it  does not help

((Get-Content -Path '\\Windows7\c$\test.txt' -Raw) -replace ' username', ' white') | Set-Content -Path '\\Windows7\C$\test.txt'

Open in new window


I will have to put in a separate  Text file like this:

Windows7    White
PCNT34    JDOck
FRANKIST  Ballon
...

Open in new window


the first column is the remote computer name and the second column is the string that will replace the second username.

As I stated , the command I pasted above works just fine, it needs to read from a separate text file so that the command will apply to several computers listed on the text file.

Thank you
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.