Quantcast
Channel: Windows PowerShell forum
Viewing all 21975 articles
Browse latest View live

Rename NICs with ipv4defaultgateway

$
0
0

I am trying to finish the script to rename NICs with ipv4defaultgateway

$prefix = "MLP"
#$netAdapters = Get-NetAdapterHardwareInfo | Sort-Object Bus,Function
$netAdapters = (Get-NetIPConfiguration | foreach ipv4defaultgateway).InterfaceAlias
$i = 1

foreach ($netAdapter in $netAdapters){

cls$interface = $netadapter | Get-NetAdapter
$old = $interface.Name
$newName = $prefix + $i
$interface | Rename-NetAdapter -NewName $newName
$i++
Write-Host "Rename" $old "to:" $newName

}

Getting an error:

Get-NetAdapter : Parameter set cannot be resolved using the specified named parameters.
At C:\MININT\Rename-MLP.ps1:8 char:28
+ $interface = $netadapter | Get-NetAdapter
+                            ~~~~~~~~~~~~~~
    + CategoryInfo          : InvalidArgument: (mlp2:String) [Get-NetAdapter], ParameterBindingException
    + FullyQualifiedErrorId : AmbiguousParameterSet,Get-NetAdapter

IS is because i need to convert whatever i am getting from

$netAdapters=(Get-NetIPConfiguration|foreachipv4defaultgateway).InterfaceAlias

to a string?

What am i missing?

Thank you,


Variable text is blank in emails when using Scheduled Task to email event log notifications

$
0
0

I am trying to use powershell to email notification when a user account gets locked.  I am running the script from a server 2008 domain controller.

I have tried multiple scripts and I have the same issue every time.  The script works fine when I run it directly from the powershell command line window.

However whenever I try running the exact same scripts from an event-triggered scheduled task, the script runs, however any content that generated from a variable is not added to the email.  It is just left blank and ignored.

I have tried adding lots of permissions including domain administrator group membership to the account  runs the task from and it doesn't include all the expected text unless I run it from the built-in domain administrator account.

The task runs and the email is sent, but the email is missing all the content generated by variables.

How can this be fixed?

Here is an example script.

$AccountLockOutEvent = Get-EventLog -LogName "Security" -InstanceID 4740 -Newest 1
$LockedAccount = $($AccountLockOutEvent.ReplacementStrings[0])
$AccountLockOutEventTime = $AccountLockOutEvent.TimeGenerated
$AccountLockOutEventMessage = $AccountLockOutEvent.Message
$messageParameters = @{ 
Subject = "Account Locked Out: $LockedAccount" 
Body = "Account $LockedAccount was locked out on $AccountLockOutEventTime.`n`nEvent Details:`n`n$AccountLockOutEventMessage"
From = "lockout@domain.com" 
To = "user1@domain.local" 
SmtpServer = "exch2010.domain.local" 

Send-MailMessage @messageParameters

------------------------------------------------------------------------------------

------------------------------------------------------------------------------------

=================================================

Here is an example of task settings.

<?xml version="1.0" encoding="UTF-16"?>
<Task version="1.2" xmlns="http://schemas.microsoft.com/windows/2004/02/mit/task">
  <RegistrationInfo>
    <Date>2015-03-25T21:40:28.8095226</Date>
    <Author>DOMAIN\administrator</Author>
  </RegistrationInfo>
  <Triggers>
    <EventTrigger>
      <Enabled>true</Enabled>
      <Subscription>&lt;QueryList&gt;&lt;Query Id="0" Path="Security"&gt;&lt;Select Path="Security"&gt;*[System[Provider[@Name='Microsoft-Windows-Security-Auditing'] and EventID=4740]]&lt;/Select&gt;&lt;/Query&gt;&lt;/QueryList&gt;</Subscription>
    </EventTrigger>
  </Triggers>
  <Principals>
    <Principal id="Author">
      <UserId>DOMAIN\WilliamsD</UserId>
      <LogonType>Password</LogonType>
      <RunLevel>LeastPrivilege</RunLevel>
    </Principal>
  </Principals>
  <Settings>
    <MultipleInstancesPolicy>IgnoreNew</MultipleInstancesPolicy>
    <DisallowStartIfOnBatteries>true</DisallowStartIfOnBatteries>
    <StopIfGoingOnBatteries>true</StopIfGoingOnBatteries>
    <AllowHardTerminate>true</AllowHardTerminate>
    <StartWhenAvailable>false</StartWhenAvailable>
    <RunOnlyIfNetworkAvailable>false</RunOnlyIfNetworkAvailable>
    <IdleSettings>
      <StopOnIdleEnd>true</StopOnIdleEnd>
      <RestartOnIdle>false</RestartOnIdle>
    </IdleSettings>
    <AllowStartOnDemand>true</AllowStartOnDemand>
    <Enabled>true</Enabled>
    <Hidden>false</Hidden>
    <RunOnlyIfIdle>false</RunOnlyIfIdle>
    <WakeToRun>false</WakeToRun>
    <ExecutionTimeLimit>P3D</ExecutionTimeLimit>
    <Priority>7</Priority>
  </Settings>
  <Actions Context="Author">
    <Exec>
      <Command>powershell.exe</Command>
      <Arguments>-nologo -File "C:\powershell\l2.ps1"</Arguments>
    </Exec>
  </Actions>
</Task>




Searching Get-Help output without -ShowWindow or -Online

$
0
0

Is there a way to search the output (given to you via the more command) in the same way one would when using the man (more or less) command on a unix server?

I'm a unix guy learning powershell and I am having a hard time not being able to hit '/' and start typing for something I am looking for when using Get-Help -full. I see that I can use the -ShowWindow and -Online switches to search the text but I would really like to be able to search when using more.

Someone know how to do this?


Replacing registry substring

$
0
0

Hi,

I am trying finding all value v1 by v2 in the registry.

1. Running

$x=Get-ChildItem Registry::HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall | foreach { Get-ItemProperty $_.PSPath } | Sort-Object Pschildname | Where-object pschildname -like "!test_ANv1*"

2. And I get

DisplayName     : !test_ANv1
DisplayVersion  : 2005 (v1)
InstallDate     : 2015-03-17
Language        : Fr
Publisher       : xxx
UninstallString : C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe -executionPolicy bypass -noexit -file "C:\Program
                  Files\xxx\test_ANv1\test_ANv1_DesInstMan.ps1"
UninstallPath   : C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe -executionPolicy bypass -noexit -file "C:\Program
                  Files\xxx\test_ANv1\test_ANv1_DesInstMan.ps1"
PSPath          : Microsoft.PowerShell.Core\Registry::HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall\test_ANv1
PSParentPath    : Microsoft.PowerShell.Core\Registry::HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall
PSChildName     : !test_ANv1
PSProvider      : Microsoft.PowerShell.Core\Registry


Not I need to replace all v1 by v2. Not the whole string just the v1 to v2 part.

3. I did try

$newValue = $x -replace "v1", "v2"

The replacement has worked. But I lost the format.

@{DisplayName=!test_ANv2; DisplayVersion=2005 (v2); InstallDate=2015-03-17; Language=Fr; Publisher=xxx; UninstallString=C:\Windows\System
32\WindowsPowerShell\v2.0\powershell.exe -executionPolicy bypass -noexit -file "C:\Program Files\xxx\test_ANv2\test_ANv2
_DesInstMan.ps1"; UninstallPath=C:\Windows\System32\WindowsPowerShell\v2.0\powershell.exe -executionPolicy bypass -noexit -file "C:\Program Files\xxx
\test_ANv2\test_ANv2_DesInstMan.ps1"; NoModify=1; NoRepair=0; NoRemove=0; InstalledConf=CARRA; PSPath=Microsoft.Po
werShell.Core\Registry::HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall\!test_ANv2; PSParentPath=Microsoft.PowerShell.Core
\Registry::HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall; PSChildName=!test_ANv2; PSProvider=Microsoft.PowerShell.Core\R
egistry}

How may I overwrite the actuals registry key by using those values?

Executing Remove-ClusterNode using WinRM

$
0
0

I am trying to remove a node from a cluster created in SCVMM Windows 2012R2. I am using Powershell "Remove-ClusterNode -Name <Node name> -Cluster <ClusterName> -Force" to remove the node.

Command works fine when it is executed from the powershell on the SCVMM server, but the same command fails when executed from using WinRM with error "Remove-ClusterNode : You do not have administrative privileges on the cluster"

I tried all the options of pass just name and FQDN for the host name and the cluster name without any success.

Same domain account is used for connecting to the SCVMM Server and WinRM. Other operations like creating cluster, adding cluster, removing cluster works fine using WinRM, except removing node from the cluster.

Invoke-Command RemoteException "Your session has expired, please login again."

$
0
0

I am calling a series of Invoke-Command with script blocks, and keep getting a RemoteException of the following:

The running command stopped because the preference variable "ErrorActionPreference" or common parameter is set to Stop: Your session has expired, please login again.
Your session has expired, please login again.

I have set $ErrorActionPreference = "Stop" to catch errors; however, this also seems to be catching some session time-out problem.

I tried executing the invoke-commands with the following session switch:

$PS_Session_Options = New-PSSessionOption
$PS_Session_Options.IdleTimeout = (New-TimeSpan -Minutes 180)
$PS_Session = New-PSSession -ComputerName myServer -SessionOption $PS_Session_Options

such as:

Invoke-Command -Session $PS_Session -ScriptBlock {program -info}

While in either a remote powershell session or powershell ISE, I have no problem calling these invoke-commands and "not" getting any session time-out problems.  It's only when the script has been setup via Task Schedular (using appropriate credentials).

What PSSession Option do I need to configure for this?  I've tried extending IdleTimeout, but doesn't work.  Would CancelTimeout or OpenTimeout set to zero (0) do the trick?

Call a batch from another batch files are not copied

$
0
0

Hi Guys, i'm trying to call a batch file from a batch file. The call is working but the commands inside the batch files are not working but the commands are working when i launch the batch file individually.

Batch1 to call Batch2

Batch1:

set clean==false

IF /I "%continue%"=="standalone"gotoStandAlone:StandAloneCall"DoNotEnterHere\Batch2.bat"goto again

Batch2:

@echo off
cls
echo press any key to continue
pause

xcopy  /s /q PT6\Tingoo*.xml "C:\Pixel \Res\" /Y
xcopy  /s /q Tomo\Fw_Settings*.xml C:\SLAB\\Res\ /Y

echo files copied
pause
I'm getting a message 0 files copied.

How can i fix this?

Thank you

split excel into different files based on row value in file

$
0
0

Hi All,

I am new to PowerShell. i would like to split the Excel file (.xlsx) into different based on row values.


My requirement is, need to group Application rows should be in one file, Application2 rows should be in another file, and Application3 values in another file..! could any please help me to write Powershell script based on this requirement..!!

 


=

How to change size for pop-up history window

$
0
0

Hello!

I work with PoSH and like use shortcut F7 for access to history powershell commands. But it is very small for my purposes.

Powershell popup history window

Are there way to change size (increase) this window?


Truly, Valery Tyurin

PowerShell runs on Windows 8.1 PS v4.0, but fails on 2008R2 PS v2.0

$
0
0

I developed a PS script to run on my server to discover if certain files exist*. I developed the code on Win 8.1 64-bit which has PS version 4.0 installed. It works perfectly. I copied the files to my Win 2008R2 SP1 64-bit server with PS version 2.0 (script is called from a .bat file which just loads the script and allows it run).

Both computers use Comcast as the ISP, but are in different locations. The code fails on the server with an Invalid HELO name from the mail server coming from the very last line of code below. This mail server does require SMTP_AUTH, but as noted above it works just fine from the Win 8 machine.

I believe the code is all PS v2.0, but could be wrong about that.

*I replaced the lookup logic for testing so my configuration is irrelevant (code shown just gets today's date instead of looking up specific data).

Any suggestions for a fix?

$todaysDate = (Get-Date -UFormat "%m-%d-%Y")
#irrelevant code removed/modified
$content = $todaysDate $emailFrom = "server@mydomain.com" $emailTo = "name1@mydomain.com, name2@mydomain.com" $subject = "Batch Files for " + $todaysDate $body = "Found the following Batch files dated: " + $todaysDate + "`n" + $content $smtpServer = "smtp.mydomain.com" $mypass = "password" # use a SecureString for $mypass which you can save to disk via Export-Clixml or ConvertFrom-SecureString $SMTPMessage = New-Object System.Net.Mail.MailMessage($EmailFrom,$EmailTo,$Subject,$Body) $SMTPClient = New-Object Net.Mail.SmtpClient($SmtpServer, 587) $SMTPClient.EnableSsl = $false $SMTPClient.Credentials = New-Object System.Net.NetworkCredential($emailFrom, $mypass) $SMTPClient.Send($SMTPMessage)

The failure error msg (line 22 is the last line of code with lookup logic in place):

C:\rmwin\BATCHES>REM marks comments

C:\rmwin\BATCHES>REM NO ECHO

C:\rmwin\BATCHES>cd c:\rmwin\BATCHES\

C:\rmwin\BATCHES>PowerShell.exe -NoProfile -ExecutionPolicy Bypass -Command "& '

C:\rmwin\BATCHES\BatchesSent.ps1'"

Exception calling "Send" with "1" argument(s): "Mailbox unavailable. The server

 response was: Access denied - Invalid HELO name (See RFC2821 4.1.1.1)"

At C:\rmwin\BATCHES\BatchesSent.ps1:22 char:17

+ $SMTPClient.Send <<<< ($SMTPMessage)

   + CategoryInfo         : NotSpecified: (:) [], MethodInvocationException

   + FullyQualifiedErrorId : DotNetMethodException

Get-WMIObject from within script run via PowerShell Remoting

$
0
0
I have a script that sits on a server in another location (ScriptingHost). The server is geographically more ideal for running scripts against remote hosts than my desktop's location. The ScriptingHost server is running '12core. The script I am trying to run attempts to collect data via Get-WMIObject. When I Enter-PSSession to the ScriptingHost server and then try to run the script I get  'Get-WmiObject : Access is denied. (Exception from HRESULT: 0x80070005 (E_ACCESSDENIED))'. If I RDP to the ScriptingHost server, launch PowerShell and run the script it works fine. I have tried defining a credential and passing it to the -Credential parameter of Get-WMIObject with no success. I figured whatever creds I'm using with Enter-PSSession would be used to run the script (i.e. Get-WMIObject). Thoughts?

Get-hotfix / wmic qfe commands do not give Microsoft related application patches.

$
0
0

Hi All,

We need to Run an audit on all our servers to see if a specific application related patch is installed on the servers or not.

I used Get-hotfix & wmic qfe these give the output, But only list the Windows patches like in the below screenshot.

But it does not list the installed Microsoft application Patches like in the below screenshot.

Is there any way from powershell we can query these KB Numbers as well ?


Gautam.75801

Enter Username and Password using powershell

$
0
0

How do you enter the ADDS credentials using powershell.

Before I used

-Credential (Get-Credential)

I want to enter Username and Password using powershell:

-Credential $PSCredential

How do you enter username and password using the same script: $PSCredential?

This is what I have so far:

$Username = "Administrator" $SecurePassword = convertto-securestring "PaSsWorD$" -asplaintext -force $credentials = New-Object System.Management.Automation.PSCredential -ArgumentList $Username, $SecurePassword

Install-ADDSForest `

...

-Credential $credentials

...





Text box AppendText

$
0
0

Its late in the afternoon and I am refreshing my myself in PowerShell GUI.  I have my GUI built and sort of functioning getting ready to add the meat of the script in.  I am attempting to use AppendText  and cannot figure out the format for the escape character. When I run the script it word wraps instead of creating a new line and appending the output to my Text Window.

Below is my function for what I want to send to my Text Window.  I have tried using plus signs, 'r, differing quote marks.  I have been staring at this to long.

Chris

function SelectWork {

if ($RadioButton1.Checked -eq $true) {$Action="UnManage"}
if ($RadioButton2.Checked -eq $true) {$Action="Manage"}
$group = $DropDownBox.SelectedItem.ToString()


$ActionResult= $Action
$outputBox.Text = $ActionResult, $group
$server = get-adgroupmember wsusdev1-gg | select name
foreach ($computer In $server.name)
	{
		$nodeid = Get-SwisData $swis "SELECT NodeID FROM Orion.Nodes WHERE SysName like '%$computer%'"
		$outputBox.AppendText("$computer  'n")
		$outputBox.AppendText("$NodeId   'n")
		$outputBox.AppendText(""==============="  'n")
	}


                     } #end SelectWork


-confirm:$false doesn't work in Orchestrator

$
0
0

This may be an Orchestrator issue, but I've decided to post here first. I'm working primarily with DFSN cmdlets but have come across this issue with others as well (like remove-ADGroupMember).

When attempting to run the command "Remove-DfsnFolder $path -confirm:$false" I receive the error:

 "A command that prompts the user failed because the host program or the command type does not support user interaction. The host was attempting to request confirmation with the following message: Perfoming operation "Delete DFS Namespace folder" on Target "\\DOMAIN.NET\Users\!test"

I've tried this via the Run .NET Script activity calling Powershell.exe. I've tried running inside of Invoke-Command. I've tried using the Execute PS Script activity as well. I've tried setting $ConfirmPreference="None".

Any thoughts on why Orchestrator will not recognize the non-use of user interaction?


Quering Event Logs on Servers

$
0
0

I have problem when quering event logs on remote servers (DC most often). The command just take to long to finish or dont finish at all. Often is the case that I get few lines and than just stops (like its processing but never finish).

Get-EventLog -cn server1 -LogName Security -Newest 20 -EntryType SuccessAudit

I'm constantly using PowerShell and I dont have problems like this with other cmdlets.


Update pasword on a service account for a scheduled task.

$
0
0

On a remote server, I am trying to change the password of the service account for scheduled task but gives "ERROR: The parameter is incorrect."
On the net saw it is because of the difference in the format created by command line and the scheduled task created by GUI. Not sure how to overcome this problem. I want to do it in powershell.

C:\>schtasks.exe /change /s Server1 /RU Domain\serviceaccount /RP password /TN "\servicename\packagename"
ERROR: The parameter is incorrect.


Using Get-ADGroup Member recursively across multiple domains in a Forest

$
0
0

Quick question for the gurus around here....

We are using a script that is querying the Local Administrators group on a Server.   It will pull the Users as well as the Groups that are a member of the Local Admins group on a server/system and using the recursive parameter with Get-ADGroupMembers, it will also list the members of any groups.  However, we seem to hit a snag when a Group is a member of another domain or even if the group is a member of the parent domain/forest.

For example...One of the Members of the Local Admin group on a server is the "Enterprise Admins".  This group lives in "Corp.Fabrikam.com" yet the server is one level deeper in "ChildDomain.Corp.Fabrikam.com".  So of course, when looking in the Child Domain there is no Enterprise Admins group for it to find and it gives us an error that it can not be found.  Samething for Groups that live in other child domains of the forest (ChildDomain2.corp.Fabrikam.com)

I am trying to figure out how to get the command to distinguish between these differences of the Group accounts and return the results from the domain those accounts live in.   Any ideas if this is normal behavior or if there is a work around?


Thanks!

Verification of user credential permissions failed

$
0
0

I successfully installed this forest:

Install-ADDSForest `
-DomainName "mysite.com" `
...
-NoRebootOnCompletion

I tried to install this domaincontroller:

Import-Module ADDSDeployment
Install-ADDSDomainController `
-DomainName "mysite.com" `
-CreateDnsDelegation `
-AllowDomainControllerReinstall `
-InstallDns `
-NoRebootOnCompletion

I got this error code:

Verification of user credential permissions failed. An Active Directory domain controller for the domain "mysite.com" could not be contacted. Ensure that you supplied the correct DNS domain name.

I tried adding -Credential $credentials with :

$Username  = "Administrator"
$SecurePassword  = ConvertTo-SecureString "@#PaSsWoRd" -Asplaintext -Force
$credentials = New-Object System.Management.Automation.PSCredential($Username, $SecurePassword)
Still the same error.

Viewing all 21975 articles
Browse latest View live


<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>