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

Comparing XML Nodes

$
0
0

Thanks for taking a look!

I want to compare the first 2 XML files and produce the 3rd containing the differences but also retaining the ancestors of the differences.  Is there a simple powershell method or will I need to read and compare each node?

These files are small examples - the real one will have a lot more entries.

File 1.

<people><person username="tester"><title>Tester</title><displayname>Jon Tester</displayname></person></people>

File 2

<people><person username="tester"><title>Senior Tester</title><displayname>Jon Tester</displayname></person></people>

Result File

<people><person username="tester"><title>Senior Tester</title></person></people>


Piping script line in a powershell script

$
0
0

Hi,

I would like piping informations in a powershell script and getting this:

If (-NOT ([Security.Principal.WindowsPrincipal][Security.Principal.WindowsIdentity]::GetCurrent()).IsInRole([Security.Principal.WindowsBuiltInRole] "Administrator"))
{  
$arguments = "& '" + $myinvocation.mycommand.definition + "'"
Start-Process powershell -Verb runAs -ArgumentList $arguments
Break
}
[string]$scriptDirectory = Split-Path -Path $MyInvocation.MyCommand.Definition -Parent # Emplacement du script
powershell.exe -executionpolicy bypass -File $scriptDirectory\Vcredist2005_Frv1.ps1 install

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

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

My script is looking this:

$var_InterventionManuelle ="c:\temp"
$var_FichierLancementManuelle = "install_Man.ps1"
$var_EmplacementFichierLancementManuelle ="c:\temp\install_Man.ps1"
New-Item -path $var_InterventionManuelle -Name $var_FichierLancementManuelle -type file
Add-Content -path $var_EmplacementFichierLancementManuelle -Value "`nIf (-NOT ([Security.Principal.WindowsPrincipal][Security.Principal.WindowsIdentity]::GetCurrent()).IsInRole([Security.Principal.WindowsBuiltInRole] "Administrator"))"
Add-Content -path $var_EmplacementFichierLancementManuelle -Value "`n{"
Add-Content -path $var_EmplacementFichierLancementManuelle -Value "`n$arguments = ""&" '" + $myinvocation.mycommand.definition + "'""
Add-Content -path $var_EmplacementFichierLancementManuelle -Value "`nStart-Process powershell -Verb runAs -ArgumentList $arguments"
Add-Content -path $var_EmplacementFichierLancementManuelle -Value "`nBreak"
Add-Content -path $var_EmplacementFichierLancementManuelle -Value "`n}"
Add-Content -path $var_EmplacementFichierLancementManuelle -Value "`n[string]$scriptDirectory = Split-Path -Path $MyInvocation.MyCommand.Definition -Parent"
Add-Content -path $var_EmplacementFichierLancementManuelle -Value "`npowershell.exe -executionpolicy bypass -File $scriptDirectory\$var_Scriptactuel install"

It is failing on the first add-content. Where am I wrong? Is it an easier way to do this?

Thanks,

François





lots of functions inside one if statement

$
0
0

Hi friends

i have created a customized powershell profile (profile.ps1 file.)

i will use this file in servers which some of them are Domain controller & some of them are not.

since there are many Active directory related functions inside this file,  to avoid errors when loading this profile in non domain controller servers, i want to use a condition so check if the current server is Domain controller, then many AD-Related functions be loaded.

there are about 20 functions which takes about 200 lines. 

is it the best practice to put all of them inside an if statement?

for example is it standard to write them as following?

$ADService = Get-Service -Name NTDS

If ($ADService) {

function1 createOUs {

many lines of code here

}

function2 create users {

many lines of code here

}

function3 create GPOs{

many lines of code here

}

# and many other functions....

.

.

.

}    #-----> closing if statement


or its better to put the mentioned condition  "if ($service)" as the first line inside each function?

thanks in advanced

How to Get-EventLog from /Operational protocols of applications and services

$
0
0

Hello,

I want to get events by powershell from -Source "Microsoft-Windows-Backup/Operational" but with /Operational source doesn't work, just with -Source "Microsoft-Windows-Backup". But I want all messages which generates wbadmin = started backups, successful backups, failed etc. but these logs are saved underApplications and Services Logs > Microsoft > Windows > Backup > Operational

PS command with just Microsoft-Windows-Backup source works:

Get-EventLog -LogName Application -Source "Microsoft-Windows-Backup"

PS command with Microsoft-Windows-Backup/Operational doesn't work:

Get-EventLog -LogName Application -Source "Microsoft-Windows-Backup/Operational"

Do you have any recommendation how to get logs from operational source? Thanks.



How to Move users from one OU to another

$
0
0

I need move user for one OU another, but show error

this my script:

Import-Module activedirectory
$Users = Import-Csv -Delimiter ";" -Path "D:\Joan\teste.txt"
foreach ($User in $Users)
{
    $DisplayName = $User.Usuarios
    $TempUser = Get-ADUser -Filter { DisplayName -like $DisplayName }

Move-ADObject -Identity $DisplayName -TargetPath "OU=teste,DC=teste,DC=br"
}

This error:

ove-ADObject : Não é possível localizar um objeto com identidade: 'ALCIDES ALVES MACHADO                                                                       ' em: 'DC=teste,DC=br'.
Em linha:8 caractere:14
+ Move-ADObject <<<<  -Identity $DisplayName -TargetPath "OU=teste,DC=teste,DC=br"
    + CategoryInfo          : ObjectNotFound: (ALCIDES ALVES M...               :ADObject) [Move-ADObject], ADIdentityNotFoundException
    + FullyQualifiedErrorId : Não é possível localizar um objeto com identidade: 'ALCIDES ALVES MACHADO                                                                       ' em: 'DC=teste,DC=br'.,Microsoft.ActiveDirectory.M
   anagement.Commands.MoveADObject

DSC Pull Server - difference between out of box version and using xPSDesiredStateConfiguration resource kit?

$
0
0
I'm new to DSC and after reading various blogs on both TechNet and 3rd party sites it appears the older articles strictly use the out of box DSC server role; whereas the more recent articles leverage the xPSDesiredStateConfiguration Module resource kit.  What is the difference between using the two?  I'm on Windows 2012 R2, and specifically looking to build a pull server. 

New-ADUser : Cannot convert 'System.Object[]' to the type 'System.String' required by parameter 'SamAccountName'. Specified method is not s upported.

$
0
0

Hi,

I am trying to create AD users via csv file separated by comma.   I have used following poweshell command to create user.

Import-Csv -Path D:\file.csv | ForEach-Object {New-ADUser -SamAccountName, $_.sAMAccountName, -Surname $_.sn, -GivenName $_.givenName, -DisplayName $_.DisplayName, -Department $_.Department, -EmployeeNumber $_.employeeNumber, -EmployeeID $_.employeeID, -Office $_.physicalDeliveryOfficeName, -State $_.st, -StreetAddress $_.streetAddress, -OfficePhone $_.telephoneNumber, -Company $_.company, -Fax $_.facsimilitelephoneNumber, -MobilePhone $_.Mobile, -Title $_.Title, -HomePhone $_.homePhone, -UserPrincipalName $_.userPrincipalName}

then it brings up following error.

New-ADUser : Cannot convert 'System.Object[]' to the type 'System.String' required by parameter 'SamAccountName'. Specified method is not supported.

any suggestion?


i get an errow using windows 8 windows powershell has stopped working

$
0
0
error message that says windows powershell has stopped working

Run a batch in specific user session using PowerShell script (without PSExec)

$
0
0

I've two sessions, both with same user, logged in one VM, i.e.:

User: user01
Sessions ID: 2, 3 and 4

I need to run a .bat file, schedule in windows task scheduler in a specific session (2, 3 or 4).

I already have an script to do this, but its using PSExec:

$session = $args[0]

$user = "user01"
$pass = "change123"

C:\PSTools\PsExec.exe -i $session -d \\$env:COMPUTERNAME -u $user -p $pass C:\test.bat

There someway to do this without using PSExec?


Getting Error When Executing PowerShell Script

$
0
0

I've been trying to execute a PowerShell script in a Windows cmd window and am having zero luck. I keep getting the following error:

It's complaining that the input file doesn't exist, but it does. I've double checked the syntax and it looks fine to me. I'm running the script from the local server as myself. I have permissions to the directory where the script is located.

Is there something I'm missing here??

Any help would be appreciated!


A. M. Robinson

Help exporting to excel.

$
0
0

I'm trying to use PowerShell to assist with asset inventory, but I am unable get it export the data directly to excel.  Eventually  I would like to be able to include the model of the pc, logged in user, and serial numbers for any devices attached via usb. 

When I used select-object instead of ft it gave me the model of the pc but didn't show the monitors.  We ft I get the monitors but not the model of the pc.

Any help would be greatly appreciated.  Here is what I have so far:

 

$computers = Get-Content C:\Temp\Powershell\MachineList.txt
$ErrorActionPreference = "SilentlyContinue"

foreach ($computer in $computers)
 {
   gwmi win32_bios -ComputerName $computer | ft __SERVER, Manufacturer, SerialNumber
 
   gwmi WmiMonitorID -ComputerName $computer -Namespace root\wmi |
    Select @{n="Model";e={[System.Text.Encoding]::ASCII.GetString($_.UserFriendlyName -ne 00)}},
        @{n="Serial Number";e={[System.Text.Encoding]::ASCII.GetString($_.SerialNumberID -ne 00)}} }

Powershell script to read xml data from multiple remote computers

$
0
0

Hello,


I'm trying to put together a script to read data from a very simple xml file on multiple remote computers and output that data into a csv file.

The remote computers are listed in a txt file (ex C:\Scripts\Computers.txt), path to xml on remote computer is same on all computers (ex C$\Drivers\Scripts\Version.xml) and layout of xml is shown below. Looking for assistance in putting it together.

<WSAU>
  <version>4.012</version>
</WSAU>

Thanks!

What is the future of Tokenizer method in system.management.automation

$
0
0

Does anyone know the future of system.management.automation.psparser.tokenize?How long will it be supported? Will it be implemented in future releases?

Is it wise to develop a product that depends upon Tokenize?

Regards,

Joginder Nahil
www.starprinttools.com

Console color overwriting sometimes

$
0
0

I've got a function that I wrote that is part of a larger script.  The issue I'm having doesn't seem specific to this function, but it's an example of what I'm seeing in general.  I'm doing this through the ISE if that matters.

About half the time when I run the script some of the colors get overwritten during the display where sometimes the line being written to the screen will have part of the color from the previous line in it, and not always just at the beginning.

Example output

Program Name | Installed   | Latest
---------------------------------------------
Program 1      | 8.4.5.196   | 8.4.5.196  

The "Program Name" line is in white which is the way it should be. On he second line the word "Program" is in green like it should be, but the number "1" through "| 8.4.5.196   | 8.4" is white and ".5.196" is back to green again like it should have been.

I'm assuming it has something to do with multithreading, but I'm not completely sure.  I've tried inserting Start-Sleep -m 100 in parts of the script and it does help a bit but does not completely eliminate it and I'd like to not have to slow the script down to fix it if there's another way around it.

Is there something I'm missing maybe?  I'm self learning PS after previous experience with batch files, and C#.

Thanks

function CheckProductVersion ($FilePath, $ProgName, $Current)
{
$ProgName = $ProgName.PadRight(16,' ')
if (Test-Path $FilePath)
{

$result=" "
clv -name result
$result = (Get-Item $FilePath).VersionInfo.ProductVersion
$result = $result -replace "`t|`n|`r",""
$result = $result.PadRight(12,' ')
$Current = $Current.PadRight(12,' ')

if ($result -ne $Current)
{
write-host "$ProgName|`t$result|`t$Current" -foregroundcolor "red"
}
else
{
write-host "$ProgName|`t$result|`t$Current" -foregroundcolor "green"
} # End
}
else
{
write-host "$ProgName|`tNot Found`t|`t$Current" -foregroundcolor "white"
}
}

## Calling the function

write-host "$CompName Report:`n"
write-host "Program Name`t|`tInstalled  `t|`tLatest" -foregroundcolor "white"
write-host "---------------------------------------------"
CheckProductVersion $Prog1FilePath "Program 1" $Prog1Current
CheckProductVersion $Prog2FilePath "Program 2" $Prog2Current
CheckProductVersion $Prog3FilePath "Program 3" $Prog3Current

Passing authentication to power shell script for SOAP calls.

$
0
0

Hi All,

Greetings.

Need your suggestions for the following scenario-

My  network allows internet access through web proxy server. While writing script to make SOAP calls to a server which is in internet i have to specify URL,Port and credentials of web proxy server, and the application I am making SOAP calls to requires https authentication.

Need your suggestions to specify both credentials (web proxy server and application ) in the script.

Thanks and regards.


How can I split or create a new table in a foreach loop in powershell (and merge certain cells)

$
0
0

I've been beating my head against this the last for days and haven't figured it out.  Basically I want to start,split, or create a new table for test procedures based off of data I'm collecting form XML requirements.  Here's what I've got so far:

$nist = [xml] (Get-Content $dir\800-53-800-53A-controls-and-objectives.xml)
$controls = $nist.controls.control | ? {$_.number -match "AC"}

$Word = New-Object -comobject Word.Application
$Word.Visible = $True
$Document = $Word.Documents.Add()
$Document.Activate()
    $objRange = $Document.Range()
    [void]$Document.Tables.Add($objRange,1,3)
    $Table = $Document.Tables.Item(1)
    $Table.Range.Style = "Table Grid"

# Row headings
$rowHeadings = @("Control","Test Description","Target of Evaluation","Test Procedure","Expected Result","Pass/Fail/Not Tested","Remarks","Test Conductor","Test Witness","Spacer")

 foreach ($control in $controls) {

$class = $control.'control-class'
$family = $control.family
$number = $control.number
$title = $control.title
$controlname = $control.number, $control.title
$name = $controlname -join " "
$priority = $control.priority
$description = $control.objectives.objective.decisions.decision | % {$($_.name), $($_.div),"`n"}
$guidence = $control.'supplemental-guidance'.div.p.'#text'
$enhancement = $control.'control-enhancements'.'control-enhancement'.objectives.objective

# Create Test Case Table
foreach ($heading in $rowHeadings) {

    If ($x -gt 1) {
        [void] $Table.Rows.Add()
    }

    # Create Row Heading
    $Table.Cell($x, 1).Range.Font.Bold = $True
    $Table.Cell($x, 1).Range.Text = $heading

    if ($heading -match "Control" ) {$Table.cell($x,2).Range.Text = $name}
    if ($heading -match "Test Description") {$table.cell($x,2).Range.Text = $description}

    # Create Date Fields
    if ( $heading -match "Conductor" -or $heading -match "Witness") {
        $Table.Cell($x,3).Range.Font.Bold = $True
        $Table.Cell($x,3).Range.Text = "Date"}

        $x++
    }

My "header" called "Spacer" is where I'm trying to split the tables up.  I would also like to merge cells two and three in rows 1-4 but haven't had any luck.

Import-Module ActiveDirectory - Error - after upgrading DC's to 2012 R2

$
0
0

Hi.

We done upgrading our Domain Controllers to 2012 R2 Version, and after upgrade i can't use ActiveDirectory  module outside my DC

When i\m trying to run  Import-Module ActiveDirectory on my Windows 7 desktop i get error:

WARNING: Error initializing default drive: 'Unable to contact the server. This may be because this server does not
exist, it is currently down, or it does not have the Active Directory Web Services running.'.

( But if i start it as Domain Admin on the same PC - all is OK. Permissions for my account is ok - i think - checked by: Get-PSSessionConfiguration on DC's ). When it was 2008 R2 DC's - all was fine

How can i fix this issue? ( i think this is access rights by i cannot manage where... )


Best Wishes, Andrew Golubenkoff

Dynamic Distribution List - Anyone ever gotten 'memberofgroup' to work with the 'like' operator? I can only do "-eq" with success

$
0
0

Hi All,

Reposting this from the Exchange Forums based upon feedback...

We have some AD groups that I can successfully pull into a recipient filter if I use the "-eq" operator. Thing is, there are now more groups and it seems like there is a limit to how many groups you can add.

So, I thought a wildcard would make it cleaner and negate the size limitation, whatever that may be. Thing is, I cannot get it to work when just testing.

This works:

get-recipient -RecipientPreviewFilter {(memberofgroup -eq 'CN=MyADGroupInMN,OU=Groups,OU=MN,OU=SomeCompany,DC=PartyTown,DC=org')}

This does not:

 get-recipient -RecipientPreviewFilter {(memberofgroup -like 'CN=MyADGroupIn*')}

I've tried about every variation of the above. According to this article you should be able to use the 'like' operator, but I'll be damned if I can find an example using 'memberofgroup.'

http://technet.microsoft.com/en-us/library/bb124268(v=exchg.150).aspx#OPATH

Powershell Event ID 300

$
0
0

Dear Microsoft Gurus,

i have a problem with our Citrix Storefront 2.6 Servers running on Windows 2008R2. The Servers are configured to run in a Microsoft NLB Cluster.

The Eventlog is flooded with Warnings with Event ID 300, generated by Powershell:

 Cannot find the X509 certificate at path CurrentUser\TrustedPublisher\611D588C5E69ADFDF3B896C7034B202CA0CA2F15.

ProviderName=Certificate ExceptionClass=ProviderInvocationException ErrorCategory=ObjectNotFound ErrorId=CertProviderItemNotFound ErrorMessage=Cannot find the X509 certificate at path CurrentUser\TrustedPublisher\611D588C5E69ADFDF3B896C7034B202CA0CA2F15. Severity=Warning SequenceNumber=37 HostName=Delivery Services PowerShell Host HostVersion=2.0.0.0 HostId=b80b9aae-02c7-412f-8d88-40367c12b9f5 EngineVersion=2.0 RunspaceId=3bcf9856-c988-4101-b10a-15bd3ae4c964 PipelineId=1 CommandName= CommandType= ScriptName= CommandPath= CommandLine=

Do you have any input on this?

Thx,
Daniel

Search alertlog and send an email

$
0
0

Hello,
I am new to both scripting and powershell, so please forgive me beforehand. Here is the script I am working on and need some advice/help.

1. The script should run Dell's Open Manage command "omreport system alertlog" and save the contents to a .csv file.

2. Then I want to import the .csv file into a variable and have ; as a delimiter.

3. Next, I want to search the .csv file for the current date and if the error severity is "critical" then I want it to email me. If nothing "critical" is found, then just exit.

I have bits and pieces of this script working but I am stuck and not sure of what to do to accomplish step 3. Here is what I have so far:

omreport system alertlog -fmt ssv > c:\alerts.csv

get-content c:\alerts.csv
$file = Import-Csv c:\alerts.csv -Delimiter ;
$file |
    foreach-object {


When I run the this command on a server "omreport system alertlog -fmt ssv > c:\alerts.csv", here is what the output looks like, if that helps.


Alert Log

Alert Log contains...

Severity;ID;Date and Time;Category;Description
Ok;1352;Tue Mar 29 14:55:48 2011;Instrumentation Service;Power supply returned to normal
Sensor location: PS 1 Status
Chassis location: Main System Chassis
Previous state was: Critical (Failed)
Power Supply type: AC
Power Supply state: Presence detected
Ok;1304;Tue Mar 29 14:55:48 2011;Instrumentation Service;Redundancy regained
Redundancy unit: System Board PS Redundancy
Chassis location: Main System Chassis
Previous redundancy state was: Lost
Ok;2121;Tue Mar 29 14:49:04 2011;Storage Service;Device returned to normal:  Virtual Disk 0 (Virtual Disk 0) Controller 0 (PERC 5/i Integrated)
Ok;2124;Tue Mar 29 14:49:04 2011;Storage Service;Redundancy normal:  Virtual Disk 0 (Virtual Disk 0) Controller 0 (PERC 5/i Integrated)
Ok;2158;Tue Mar 29 14:49:04 2011;Storage Service;Physical disk online:  Physical Disk 0:0:1 Controller 0, Connector 0
Ok;2092;Tue Mar 29 14:49:03 2011;Storage Service;Physical disk Rebuild completed:  Physical Disk 0:0:1 Controller 0, Connector 0
Critical;1306;Tue Mar 29 13:56:38 2011;Instrumentation Service;Redundancy lost
Redundancy unit: System Board PS Redundancy
Chassis location: Main System Chassis
Previous redundancy state was: Normal

Again, I am new to all of this, but any help you can give me with be greatly appreciated. Thank you!


Viewing all 21975 articles
Browse latest View live


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