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

Question on get-eventslog/replacementstrings index

$
0
0

Hi All,

Is there different indexing for the ReplacementStrings array in the various Security eventids? Or am I seeing/doing things incorrectly. I'm looking at inserting the specific values into a sql table, but it looks as if I'll have to have different associations depending on the Security EventIDs.

The index differs between Event IDs 4738, 4724 (4723 and 4725) and 4728.

For EventID = 4738 (A user account was changed.)

RS0: -
RS1: Target Account/Account Name
RS2: Target Account/Account Domain
RS3: Target Account/Security ID
RS4: Subject/Security ID
RS5: Subject/Account Name
RS6: Subject/Account Domain
RS7: Subject/Logon ID

For EventID = 4724 (An attempt was made to reset an account's password.)(same indexing for 4723 and 4725

RS0: Target Account/Account Name
RS1: Target Account/Account Domain
RS2: Target Account/Security ID
RS3: Subject/Security ID
RS4: Subject/Account Name
RS5: Subject/Account Domain
RS6: Subject/Logon ID
RS7:

ForEventID - 4728 (A member was added to a security-enabled global group.)

RS0: Target Account/Account Name
RS1: Target Account/Security ID
RS2: Group/Group Name
RS3: Group/Group Domain
RS4: Group/Security ID
RS5: Subject/Security ID
RS6: Subject/Account Name
RS7: Subject/Account Domain
RS8: Subject/Logon ID

Also, is there some sort of "cheat sheet" that has the index numbering for Security Events (ReplacementStrings) laid out?

Thank you.

gdr


Onward through the fog......


Remotely keep machines awake

$
0
0

Hi all so I have a few labs I need to keep awake while running some tasks. I would change the power policy but I do not have rights to, as it is set through group policy. I have a script that I think should keep them awake but they still seem to fall asleep. My question is am I doing anything wrong or is there a better way to keep them awake?

$computers = Get-Content 'C:\Users\cody-horton\Desktop\complist.txt'
$computers = $computers | Sort-Object
Write-Host $computers

$minutes = 999

for ($i = 0; $i -lt $minutes; $i++) {
    Start-Sleep -Seconds 60
    foreach($computer in $computers){
        Invoke-Command -ComputerName $computer -ScriptBlock {
        $myshell = New-Object -com "Wscript.Shell"
        $myshell.sendkeys(".")}
    }

}

Thanks for any help!

Rename locks file?

$
0
0

I have a shortcut in the start menu that I want to rename with a powershell script, and that is working fine, but the shortcut then no longer works for regular users because the file is "locked." Not sure why launching a shortcut would care, but this is a shortcut to an Autodesk product and they tend to do funny things. So, is there some trick to force the Rename-Item cmdlet to not lock this file? Or a way to force an unlock after the fact?

Thanks!
Gordon

Remote use of pnputil results in Invalid INF passed as parameter

$
0
0

What I'm trying to accomplish: Remotely update enic & fnic drivers on multiple 2008r2 machines.

The current command I'm trying is:

$servers = Get-Content servers.txt
Invoke-Command -ComputerName $servers -ScriptBlock {pnputil.exe -a \\myserver\h$\enic6x64.inf}

This results in the error: 

Microsoft PnP Utility

Adding the driver package failed : Invalid INF passed as parameter.

Total attempted:              0
Number successfully imported: 0

If I copy & past that scriptblock onto the remote machine it runs no problem. If I change the script block to be {pnputil.exe -e} it will return results for all drivers currently installed on that remote machine. I've tried enclosing the scriptblock in quotes, running it from a filepath, no go. I tried pushing the actual .inf file to the remote machine & changing the path to a local C:\temp directory to which it told me:

Processing inf :            enic6x64.inf
Adding the driver package failed : The system cannot find the file specified.

Is there a better way with powershell that I am able to remotely install drivers or is there a problem with my syntax?

SQL Job not failing when Powershell script runs and Fails

$
0
0

I have a sql job step that runs a powershell script using XP_cmdshell as follows

EXEC xp_cmdshell 'powershell.exe %Deployment_root%apps\Systems\sql\DR\ScriptSQLServerObjects.ps1 "gssqlbackup"'

However, if the script fails the job finishes successfully. I want the SQL Job to fail when the powershell script fails and also update the code below so that it outputs the error to a log file

The code in my script "ScriptSQLServerObjects.ps1" is as follows. The first part loads the SQLPS provider (obtained from MSDN) and the second part scripts every Job on the SQL Server for Backup purposes 

# Pass the Backup Share Location into the script i.e ScriptsSQLServerObjects "$BackupShare"param ([string]$BackupShare)# Add the SQL Server Provider.$ErrorActionPreference="Stop"$sqlpsreg="HKLM:\SOFTWARE\Microsoft\PowerShell\1\ShellIds\Microsoft.SqlServer.Management.PowerShell.sqlps"if (Get-ChildItem $sqlpsreg-ErrorAction "SilentlyContinue")
{throw"SQL Server Provider for Windows PowerShell is not installed."
}else
{$item= Get-ItemProperty $sqlpsreg$sqlpsPath=[System.IO.Path]::GetDirectoryName($item.Path)
}## Set mandatory variables for the SQL Server provider#

Set-Variable -scope Global -name SqlServerMaximumChildItems -Value 0
Set-Variable -scope Global -name SqlServerConnectionTimeout -Value 30
Set-Variable -scope Global -name SqlServerIncludeSystemObjects -Value $false
Set-Variable -scope Global -name SqlServerMaximumTabCompletion -Value 1000## Load the snapins, type data, format data#
Push-Location

cd $sqlpsPath
Add-PSSnapin SqlServerCmdletSnapin100
Add-PSSnapin SqlServerProviderSnapin100
Update-TypeData -PrependPath SQLProvider.Types.ps1xml 
update-FormatData -prependpath SQLProvider.Format.ps1xml 

Pop-Location# Set the Server Name and Default starting location$SName='L3PSQL71'
Set-Location C:# Load the Dot Net Assembly For SQL Server SMO. Out-Null indicates no output of the GAC and Version[reflection.assembly]::LoadWithPartialName("Microsoft.SqlServer.Smo") | Out-Null# Assign the Scripting Options to a variable$so= new-object Microsoft.SqlServer.Management.Smo.ScriptingOptions# Set the Input and Output Location Variables$JobsOutputLocation='\\' + $BackupShare + '\' + $SName + 'Failover\OtherBits\' + $SName + '_SQLJob - '$SQLServerJobsPath='SQLSERVER:\sql\' + $SName + '\default\JobServer\Jobs'# Script the Jobs$so.IncludeDatabaseContext = 1
gci -path $SQLServerJobsPath | %{$Job=$_.Name; $_.script($so) | out-file -filepath $JobsOutputLocation$Job.sql}

The $ErrorActionPreference is set to stop. So even though I can get it to fail, this failure does not cause the SQL job to fail. How can I trap the failure and also outut the failure details to a log file?

Thanks in advance

Bulk create and mail enable distribution lists

$
0
0

Does anyone know of a decent script to mass create and mail enable distribution lists?  Either by excel or csv?  Thank you.

invoke wmi method to send remote command

$
0
0

Hi guys, i am trying to create a log entry by using inoke-wmimethod not invoke-command

this is what i am using but no luck

foreach($server in $servers){
$error.Clear()
$ping = New-Object System.Net.NetworkInformation.Ping
if($ping.send($server,1000).Status -like "success"){
sleep -Milliseconds 100"Running FlushDNS cmd on $server"
New-EventLog -ComputerName $server –LogName System –Source “Script” -ErrorAction SilentlyContinue
Invoke-WmiMethod -Path Win32_Process -ComputerName $server Create -ArgumentList "cmd /c ipconfig /flushdns" -AsJob -ThrottleLimit 200 >> $null
Invoke-WmiMethod -Path Win32_Process -ComputerName $server Create -ArgumentList "powershell /c Write-EventLog -LogName System -Source `"Script`" -EntryType Information -EventId 1 -Message `"Received FlushDns Command`"""$(get-date) Sent ipconfig /flushdns to $server" >> "\\localhost\c$\PSScripts\test\CTX flushdns\flushdns other.log"
}

I am guessing its something to do with my format since flushdns appears to be working? Any ideas?

Windows Update script - Percentage progress help

$
0
0

I'm using a powershell script to do windows update on my VM/Server builds.  The script works fine, however it just tells me that it's "Downloading Updates" and then "Installing Updates" and I added some logic so it tells me the percentage progress.  The problem I'm having is that since I made my changes the updated script takes way longer than the other one.  Can someone tell me what I'm doing wrong and correct me.  Thanks

This is the original Function:

Function Add-WindowsUpdate

{param ($Criteria="IsInstalled=0 and Type='Software'" , [switch]$AutoRestart, [Switch]$ShutdownAfterUpdate) 

 $resultcode= @{0="Not Started"; 1="In Progress"; 2="Succeeded"; 3="Succeeded With Errors"; 4="Failed" ; 5="Aborted" }

 $updateSession = new-object -com "Microsoft.Update.Session"
 write-progress -Activity "Updating" -Status "Checking available updates"  
 $updates=$updateSession.CreateupdateSearcher().Search($criteria).Updates

 if ($Updates.Count -eq 0)  { "There are no applicable updates."}   
 else { 

       $downloader = $updateSession.CreateUpdateDownloader()   
       $downloader.Updates = $Updates  

        $date = get-date
	write-progress -Activity 'Updating' -Status "Downloading $($downloader.Updates.count) updates started at $date"
       $Result= $downloader.Download()  

       if (($Result.Hresult -eq 0) –and (($result.resultCode –eq 2) -or ($result.resultCode –eq 3)) ) {

       $updatesToInstall = New-object -com "Microsoft.Update.UpdateColl"

       $Updates | where {$_.isdownloaded -and $_.title -notlike "*Internet Explorer 9*" -and $_.title -notlike "*Internet Explorer 10*"} | foreach-Object {$updatesToInstall.Add($_) | out-null }
       $installer = $updateSession.CreateUpdateInstaller()
       $installer.Updates = $updatesToInstall


       write-progress -Activity 'Updating' -Status "Installing $($Installer.Updates.count) updates started at $date"
        $installationResult = $installer.Install()
        $Global:counter=-1
        $installer.updates | select Title,EulaAccepted,@{label='Result';
                               expression={$ResultCode[$installationResult.GetUpdateResult($Global:Counter++).resultCode ] }}  
} 
}
}

Add-WindowsUpdate -Auto

Here's the modified version to give me a percentage progress

Function Add-WindowsUpdate

{param ($Criteria="IsInstalled=0 and Type='Software'" , [switch]$AutoRestart, [Switch]$ShutdownAfterUpdate) 

 $resultcode= @{0="Not Started"; 1="In Progress"; 2="Succeeded"; 3="Succeeded With Errors"; 4="Failed" ; 5="Aborted" }

 $updateSession = new-object -com "Microsoft.Update.Session"
 write-progress -Activity "Updating" -Status "Checking available updates"  
 $updates=$updateSession.CreateupdateSearcher().Search($criteria).Updates

 if ($Updates.Count -eq 0)  { "There are no applicable updates."}   
 else { 

       $downloader = $updateSession.CreateUpdateDownloader()   
       $downloader.Updates = $Updates  

        $date = get-date
	for ($a=1; $a -lt 100; $a++){
	write-progress -Activity 'Downloading...' -PercentComplete $a -CurrentOperation "$a% Complete" -Status "Downloading 

$($downloader.Updates.count) updates started at $date"
        $Result= $downloader.Download()  
	}
        if (($Result.Hresult -eq 0) –and (($result.resultCode –eq 2) -or ($result.resultCode –eq 3)) ) {

       $updatesToInstall = New-object -com "Microsoft.Update.UpdateColl"

       $Updates | where {$_.isdownloaded -and $_.title -notlike "*Internet Explorer 9*" -and $_.title -notlike "*Internet Explorer 

10*"} | foreach-Object {$updatesToInstall.Add($_) | out-null }
       $installer = $updateSession.CreateUpdateInstaller()
       $installer.Updates = $updatesToInstall


        for ($a=1; $a -lt 100; $a++){
	write-progress -Activity 'Updating...' -PercentComplete $a -CurrentOperation "$a% Complete" -Status "Installing 

$($Installer.Updates.count) updates started at $date"
        $installationResult = $installer.Install()
	}
        $Global:counter=-1
        $installer.updates | select Title,EulaAccepted,@{label='Result';
                               expression={$ResultCode[$installationResult.GetUpdateResult($Global:Counter++).resultCode ] }}  
} 
}
}

Add-WindowsUpdate -Auto

Thanks.


How to set Deny Logon Localy in PS Script?

$
0
0

Hello,

in the past I used "secedit" and an INF file in a CMD script to set "SeDenyRemoteInteractiveLogonRight" and "SeDenyInteractiveLogonRight" for an local user account on a local Server. Now I have to Switch my script to Power Shell and I did not find a solution for my problem in the www.

Do have anyone an idea?


regards Stephan

How to output each loop to a single line?

$
0
0

I have a powershell script that does a gsv check foreach server listed in a text file and outputs the result like so:

Hostname|Service|Status
I--------------------------------I
BOSAD2
ntrtscan Running
BOWAD3
ntrtscan Running

I would like the output to look like this instead:

Hostname|Service  |Status
I--------------------------------I
BOSAD2  ntrtscan  Running
BOWAD3  ntrtscan Running

Here's my code:

Set-Content $results "Hostname|Service|Status"
Add-Content $results "I--------------------------------I"
$a = (gc $list1)
$(foreach ($server in $a) {$server; gsv -Name "ntrtscan" -cn $server | select Name,Status | ft -AutoSize -HideTableHeaders}) | Out-File $results -Append ascii

Thanks.








Powershell Survival Guide on Technet

$
0
0

Hi,

I found the Survival Guide a couple of days ago - great resource!

But today, when I click the link to go there, I get:  Resource not found    (the page is gone)

The link I use is:

http://social.technet.microsoft.com/wiki/contents/articles/183.windows-powershell-survival-guide.aspx

Do you know why this is?

Thanks

Active Directory Powershell command error for some users

$
0
0

Hello,

I use following command to get a user DL membership using active directory module for PowerShell

Get-ADPrincipalGroupMembership username |select name,group* | ft  -autosize . This command in return gives me output for all the DL membership of the user that I have rqueried. How ever for some of my users when I run this command, I get below error:

PS C:\Users\adm> Get-ADPrincipalGroupMembership userabc |select name,group*
| ft  -autosize
Get-ADPrincipalGroupMembership : The server was unable to process the request d
ue to an internal error.  For more information about the error, either turn on
IncludeExceptionDetailInFaults (either from ServiceBehaviorAttribute or from th
e <serviceDebug> configuration behavior) on the server in order to send the exc
eption information back to the client, or turn on tracing as per the Microsoft
.NET Framework 3.0 SDK documentation and inspect the server trace logs.
At line:1 char:31
+ Get-ADPrincipalGroupMembership <<<<  userabc |select name,group* | ft  -autos
ize
    + CategoryInfo          : NotSpecified: (userabc:ADPrincipal) [Get-ADPrinc
   ipalGroupMembership], ADException
    + FullyQualifiedErrorId : The server was unable to process the request due
    to an internal error.  For more information about the error, either turn
  on IncludeExceptionDetailInFaults (either from ServiceBehaviorAttribute or
  from the <serviceDebug> configuration behavior) on the server in order to
 send the exception information back to the client, or turn on tracing as     p
er the Microsoft .NET Framework 3.0 SDK documentation and inspect the ser    ve
r trace logs.,Microsoft.ActiveDirectory.Management.Commands.GetADPrincip    alG
roupMembership

***********************

I get the above error output only for some users!!!


bws

Setting DisplayName as "LastName, First" in Active Directory

$
0
0

I am using this line to start:

Get-ADUser -Filter * -Properties DisplayName |select GivenName, Surname, DisplayName

 

I'd like somehow capture the GivenName and Surname and write it into DisplayName in the form of: "Surname, GivenName". Thank you in advance.


How to get the PSComputer name from Get-DnsServerForwarder

$
0
0

running this command gives me a blank "pscomputername"

get-dnsserver -cn dc1 | select *

How to inject the computer name "dc1" into my output string?

Also, why does running this command yield nothing:

get-dnsserverforwarder -cn (gc $list) | select ipaddress

yet this does?

gsv -cn (gc $list) | select machinename

Thanks.

Change machine names from lowercase to uppercase

$
0
0

This article shows where the change in the registry needs to be made

http://peteinman.wordpress.com/2009/01/06/changing-the-case-of-windows-computer-name/

The values that need to be modified are "Hostname" and "NV Hostname"  Currently a machine on our network reads like the following: "machinename-123"  I want to be able to change it to "MACHINENAME-123"  Every PC on our network has the same first part of the PC name, in this example that is "machinename-"  The only thing that changes from machine to machine is the 3 digit number after the dash.

Is there a way in Powershell or some other method to run that on all machines on our network to change those registry values to make the beginning part of the name uppercase?

Thank you.


How do I set RDP Gateway when trying to connect to Terminal Server in Powershell

$
0
0

Hey,

I need to remote logon to some windows servers and I must get through a RDP Gateway to connect.  I could use GUI (mstsc.exe) to connect them because I could see the options to set RDP gateway; But I did not see how I can set the RDP Gateway in Powershell, for command new-psession/enter-pssession, I did not see the parameter to set RDP gateway. How can I get this addressed as I MUST use command line to do remote login?

Thanks,

Jesse

retrieve latest revision of a file from perforce using web url

$
0
0

Hello,

I am trying to retrieve the latest revision of a file from perforce using the web url and powershell. e.g.

$Pforce = "perforce.test.com/@md=d&cd=//music/Database/DBA%20Scripts/&cdf=//msc/Database/DBA%20Scripts/20scrub%20script.sql&c=don@//music/Database/DBA%20Scripts/common%20script.sql"
$CommonScrub = Invoke-WebRequest $Pforce  

I am getting an error message below about invalid header. Does anyone have any ideas what this means and how to fix it?

Is there another method I can use to get the files from perforce using powershell. Has anyone done this?

Invoke-WebRequest : The server committed a protocol violation. Section=ResponseHeader Detail=Header name is invalid
At E:\scripts\GetHTML_Headers.ps1:3 char:16

Powershell script to move members to new security Group

$
0
0
Is there a powershell script through which I can move members of one security group to another.

powershell and internet explorer

$
0
0

I run the following script

$ie = new-object -com "InternetExplorer.Application"

$ie.visible = $false

$ie.navigate("http://localhost:8129/default.aspx")

$ie.quit()

On one system it works it opens the web page.  Does not display the page.

On the other system if opens the web page.  Displays the web page. Then gets the following error.

The script that is run s on a NAS drive.  so both system are executing the exact code.  This code has

worked for over a year.  About a month ago it started failing on one system but not the other.  both

system are running windows 7 Pro 64bit.  Other than number of disk drives and size of the disk drives

the systems are identical.

Method invocation failed because [System.__ComObject] doesn't contain a method named 'quit'.
At T:\ps1src\lib\Library.ps1:300 char:1
+ $ie.quit()
+ ~~~~~~~~~~
    + CategoryInfo          : InvalidOperation: (:) [], RuntimeException
    + FullyQualifiedErrorId : MethodNotFound

Some Powershell 4.0 version IIS commands not working in Powershell 2.0 ?

$
0
0

Hi,

    I am using some IIS commands like Get-website in Powershell 4.0 version under 64 bit OS.Those commands working fine in Powershell 4.0 .But when i am trying to use those commands in Powershell 2.0 version under 32 bit or 64 bit OS,i am getting below error

 PS C:\Windows\system32> get-website
Retrieving the COM class factory for component with CLSID {688EEEE5-6A7E-422F-B2E1-6AF00DC944A6} failed due to

the following error: 80040154 Class not registered (Exception from HRESULT: 0x80040154 (REGDB_E_CLASSNOTREG)).
At line:1 char:12
+ get-website <<<<
    + CategoryInfo          : NotSpecified: (:) [Get-Website], COMException
    + FullyQualifiedErrorId : System.Runtime.InteropServices.COMException,Microsoft.IIs.PowerShell.Provider.GetW
ebsiteCommand

Please suggest me in solving this issue with detailed steps

Viewing all 21975 articles
Browse latest View live


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