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

Handling parameters on a single line script

$
0
0

Hi all

I have a single line of Powershell which spiders through all the sub directories of the current directory and returns a nice report giving the disk space used by each sub folder. 

I want to edit the script so that I can prompt the user for the directory to target. 

I need to keep the script as a single line because we use a remote management tool which, oddly, only allows one line for its remote powershell execution. 

My script is currently 

  gci .|%{$f=$_; gci -r $_.FullName| measure-object -property length -sum | select  @{Name="Name";Expression={$f}},@{Name="Sum (MB)";Expression={"{0:N3}"-f ($_.sum /1MB)}},Sum}| sort Sum-desc | format-table -PropertyName,"Sum (MB)",Sum-autosize

Any ideas how this can be done? I can hack it to work in a ps1 script but I can't actually use that here. 

Olly


Looping to Concatenate/Append Data from Another File using Powershell

$
0
0
I have Details.csv file which the content as below. It is lengthy but I'm making it 4 rows with top row is header. | is delimiter

EmployeeID|"name"|"address"
8004956782|"Čantona"|"Townstend Street"
8005884384|"Sælanto"|"Kentucky Street"
8004485843|"Ricardo"|"Chow Lin" 

I want to get an output to a new Scripts.txt file with content as below.

update sTVEmpID='b8004956782' sTVGhasd='Čantona' sTVplace='Townstend Street';
update sTVEmpID='b8005884384' sTVGhasd='Sælanto' sTVplace='Kentucky Street';
update sTVEmpID='b8004485843' sTVGhasd='Ricardo' sTVplace='TChow Lin';

Please help to create Powershell Script to do this task because i'm doing this manually now and it is taking up a lot of time. I couldn't find any solution for this online.

Data from simple query not passing to temp variable

$
0
0

I have been working on a script to gather info about a bunch of PCs and while I wrote very little of it originally, I've been tweaking it to make it run faster and to make the code less complex. This issue has to do with gathering info about monitors attached to a PC and I commented out a big snippet of code, in favor of a more simpler approach. I will post the code below but basically my new snippet works but the object data is not being passed to the Debugger - I have it write out the monitor info it found, but it is empty. I can see the variables in the Debugger and the monitor data is there. I just can't figure out why it's missing.


EDIT by Mike Laughlin: I've removed the posted script due to incorrect formatting. The code can be found in another post below.


I know it might be hard to read but hopefully someone can figure it out. The commented out section is what it had before. It worked but it is very complicated to follow, so I found an easier way to do it with less code. Any help would be greatly appreciated.

Brian Embree

Legacy Health System

Portland, OR


Where (SQL) Clause does not accept string Variable

$
0
0

Hi All

I have the following code below that throws an error.

I want to change the display name in an excel file based on certain Batch Numbers and Email

Exception calling "ExecuteNonQuery" with "0" argument(s): "No value given for one or more required parameters."
At line:7 char:1
+ $sqlCommand.ExecuteNonQuery()

If I change the strQuery line from:

$strQuery = "Update [$strSheetName] set DisplayName = 'HEYHEY' Where Batch = $Batche AND Email like $colme"

to

$strQuery = "Update [$strSheetName] set DisplayName = 'HEYHEY' Where Batch = $Batche AND Email like 'Apple9'"

It works fine Just not with the String Variable $colme. The $Batche Variable works ok as it is an number in the XLSX file.

Can anyone help please?

#EducationTest1.xlsx holds columns Batch; Email; Displayname; FirstName; LastName

#I want to change the display name based on certain Batch Numbers and Email

$strFileName ="C:\Dev\EducationTest1.xlsx"
$strSheetName = 'Sheet1$'
$strProvider = "Provider=Microsoft.ACE.OLEDB.12.0"
#$strProvider = "Provider=Microsoft.Jet.OLEDB.4.0"
$strDataSource = "Data Source = $strFileName"
$strExtend = "Extended Properties=Excel 8.0"


#Create Query here that loops Array of Batch Number and update

$Batches = 1003, 1004
$colme = 'Apple9'

ForEach ($Batche in $Batches){

$strQuery = "Update [$strSheetName] set DisplayName = 'HEYHEY' Where Batch = $Batche AND Email like $colme"

$objConn = New-Object System.Data.OleDb.OleDbConnection("$strProvider;$strDataSource;$strExtend")
$sqlCommand = New-Object System.Data.OleDb.OleDbCommand($strQuery)
$sqlCommand.Connection = $objConn
$objConn.open()
$sqlCommand.ExecuteNonQuery()
$objConn.Close()
}

Delete files deep in user profile on all machines

$
0
0

Howdy,

I have an app that occasionally needs to have its cache purged, and the cache is buried deep in users' profiles, e.g.

c:\Users\USERNAME\AppData\Local\VENDOR\Temp Download
c:\Users\USERNAME\AppData\Local\VENDOR\Temp Upload

To date I've used a simple batch file containing all of the machines in the domain when I need to purge the cache:

del "\\MACHINENAME\c$\Users\USERNAME\AppData\Local\VENDOR\Temp Download\*.*" /F /S /Q

The problem lies in the maintenance of the batch file, as our machine names and users change a fair amount. I'd rather have my script be able to dynamically determine machine names and profile paths. What I want to do is:

  1. Pull machine names from a specified OU
  2. Pull a list of profiles from each machine & get the pspath property
  3. Append the path to the cache to the pspath property
  4. Now that I have a complete path, delete the contents of the cache

Getting the list of machines is easy enough:

get-adcomputer -Filter * -SearchBase 'ou=OU,dc=SUBDOMAIN,dc=DOMAIN,dc=TLD'  |Select -expand name 

First question here - how do I pipe that output to the next bit that grabs the profile path:

Get-childItem ‘HKLM:\SOFTWARE\Microsoft\Windows NT\CurrentVersion\ProfileList’ | % {Get-ItemProperty $_.pspath } | Select profileImagePath

I've played around with assigning the Get-ADComputer output to a variable and using 'ForEach' but that isn't working. Array? I believe I have the logic for all of the individual steps, but I'm not sure how to pipe the data between the code blocks. I've searched this and other forums and haven't found anyone who is trying to do this. Any clue you can instill will be greatly appreciated.

Thanks in advance,

M-

Calling one PowerShell Script from Another

$
0
0

Hi,

I am trying to write a PowerShell script that will call another PowerShell script when the first one finishes. Can't get it to work.

1. First script downloads some folders and files from a network share to the users' local C: Drive

2. When the files have finished copying, then fire off another PowerShell script that is part of the files that were copied to the local computer.

    

# Specify the source and destination paths
$Source = "\\SERVER\SHARE$\PSAPPDEPLOY\"
$Destination = "C:\PSAPPDEPLOY"

# Check if the folder exists and if not create it and copy the PSAppDeploymentKit files to the local C: Drive

If (!(Test-Path $Destination)) {

   Copy-Item -Path $Source -Destination $Destination -Recurse

}

Else {
   Write-Host "Directory already exists!"
   Exit
}

$scriptpath = C:\PSAPPDEPLOY\Deploy-Application.ps1

$ArgumentList = -DeploymentType Install - DeployMode Interactive

Invoke-Expression"$scriptPath $argumentList"

Also, is there a way to bypass UAC and get these to fire off without the prompt? I see a way to do it via a batch file, but was hoping to use PowerShell for the whole thing.

Here's a batch file example:

@ECHO OFF
PowerShell.exe -NoProfile -Command "& {Start-Process PowerShell.exe -ArgumentList '-NoProfile -ExecutionPolicy Bypass -File ""C:\PSAPPDEPLOY\Deploy-Application.ps1""' -Verb RunAs}"
PAUSE


Powershell to get CPU usage report.

$
0
0

Hi All,

I am trying to get CPU usage in multiple server. Using the script below, I am able to get the result from one server without the Serverlist mentioned in the script.

$Output = "C:\Temp\Result.txt"
$Serverlist = "C:\temp\ServerNames.txt"
# $Servers = Get-Content -Path $Serverlist

$CPUPercent = @{
Label = 'CPUUsed'
Expression = {
    $SecsUsed = (New-Timespan -Start $_.StartTime).TotalSeconds
    [Math]::Round($_.CPU * 10 / $SecsUsed)
  }
}

foreach ($Servers in $Serverlist) {

Invoke-Command -ComputerName $Serverlist -ScriptBlock {

Get-Process | Select-Object -Property Name, CPU, $CPUPercent, Description | Sort-Object -Property CPUUsed -Descending | Select-Object -First 15 | Format-Table -AutoSize | Out-File $Output -Append

  }
}

But when try to run against multiple servers, I am getting error mentioned below - 

Invoke-Command : One or more computer names are not valid. If you are trying to pass a URI, use the -ConnectionUri parameter, or pass URI objects instead of strings.
At line:15 char:1+ Invoke-Command -ComputerName $Serverlist -ScriptBlock {+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~+ CategoryInfo          : InvalidArgument: (System.String[]:String[]) [Invoke-Command], ArgumentException+ FullyQualifiedErrorId : PSSessionInvalidComputerName,Microsoft.PowerShell.Commands.InvokeCommandCommand

Additionally, Is there a way to get User Name using the highest process as well in that out along with the memory Usage, pls let me know...


VT


Convert array to string

$
0
0

I get this message when I try to send an email with lots of text saved in a variable with the Array type

Send-MailMessage : Cannot convert 'System.Object[]' to the type 'System.String' required by parameter 'Body'. Specified method is not supported.

How can I convert that variable type to string, to send the message?

I'm trying to use the .ToString(), but after running that command, the variable is still an array


Freddy


Ransomware fight - make partition read only...but first want to close all open files on that partition

$
0
0

hi

i have script which make my partitions read-only after backup, for deny access as ransomware defence.

but have problem that many files are open and after some days I need to use chkdsk.

how to close all open files on some partition and make it read only?

tnx

disk 2 data source

disk 4 backup destination

Get-Disk -Number "2" | Set-Disk -IsReadOnly:$false
Get-Disk -Number "4" | Set-Disk -IsReadOnly:$false
cmd /c "some backup.cmd"
Get-Disk -Number "2" | Set-Disk -IsReadOnly:$true
Get-Disk -Number "4" | Set-Disk -IsReadOnly:$true



Trying to understand -expandProperty and objects

$
0
0

Lets say i would like to get-process from Ad-computer

get-adcomputer is an object, so in order to return a string needed for get-process i run the following:

Get-ADComputer hostname | Select-Object -ExpandProperty name

which does return s string:

Get-ADComputer hostname | Select-Object -ExpandProperty name | gm

TypeName: System.String

I know get-process is looking for a string on a -computername:

 -ComputerName [<String[]>]

Accept pipeline input?       True (ByPropertyName)

Then why i am getting an error :)

Get-ADComputer hostname | Select-Object -ExpandProperty name | Get-Process

Get-Process : The input object cannot be bound to any parameters for the command 
either because the command does not take pipeline input or the input and its 
properties do not match any of the parameters that take pipeline input.

I know i am missing something very small....

Need help running PS1 on multiple computers

$
0
0

Looking for some help. I have this script to fix unquoted path enumeration, but I need to run this on hundreds of PCs. Need a little help with the syntax and reporting. How can I get this to a) run remotely on multiple PCs and b) get a log of it as well.

Original Script

cls
Function Fix-ServicePath ([System.IO.DirectoryInfo]$LogPath = "C:\temp") {<#
	.SYNOPSIS
	    Microsoft Windows Unquoted Service Path Enumeration

	.DESCRIPTION
	    Use Fix-ServicePath to fix vulnerability "Unquoted Service Path Enumeration".



	    ------------------------------------------------------------------
	    Author: Vector BCO
		Version: 3.1

	.PARAMETER LogPath
		You can set different path for log files
		Defaul path is c:\Temp
		Default log file: servicesfix.log

	.NOTES


	.EXAMPLE
		 Fix-Servicepath

	.EXAMPLE
		 Fix-ServicePath -LogPath C:\DifferentPath

	.LINK
		https://gallery.technet.microsoft.com/scriptcenter/Windows-Unquoted-Service-190f0341
		https://www.tenable.com/sc-report-templates/microsoft-windows-unquoted-service-path-enumeration
		http://www.commonexploits.com/unquoted-service-paths/
	#>

if (-not (Test-Path $LogPath)){New-Item $LogPath -ItemType directory}

"**************************************************" | Out-File "$LogPath\servicesfix.log" -Append"Computername: $($Env:COMPUTERNAME)" | Out-File "$LogPath\servicesfix.log" -Append"Date: $(Get-date -Format "dd.MM.yyyy HH:mm")" | Out-File "$LogPath\servicesfix.log" -Append

# Get all services
Get-ChildItem "HKLM:\SYSTEM\CurrentControlSet\Services\" | foreach {
$OriginalPath = (Get-ItemProperty "$($($_).name.replace('HKEY_LOCAL_MACHINE', 'HKLM:'))")
$ImagePath = $OriginalPath.ImagePath

# Get all services with vulnerability
If (($ImagePath -like "* *") -and ($ImagePath -notlike '"*"*') -and ($ImagePath -like '*.exe*')){
    $NewPath = ($ImagePath -split ".exe ")[0]
    $key = ($ImagePath -split ".exe ")[1]
    $triger = ($ImagePath -split ".exe ")[2]

    # Get all services with vulnerability with key in ImagePath
    If (-not ($triger | Measure-Object).count -ge 1){
        If (($NewPath -like "* *") -and ($NewPath -notlike "*.exe")){" ***** Old Value $ImagePath" | Out-File "$LogPath\servicesfix.log" -Append"$($OriginalPath.PSChildName) `"$NewPath.exe`" $key" | Out-File "$LogPath\servicesfix.log" -Append
            Set-ItemProperty -Path $OriginalPath.PSPath -Name "ImagePath" -Value "`"$NewPath.exe`" $key"
        }
        }

    # Get all services with vulnerability with out key in ImagePath
    If (-not ($triger | Measure-Object).count -ge 1){
        If (($NewPath -like "* *") -and ($NewPath -like "*.exe")){" ***** Old Value $ImagePath" | Out-File "$LogPath\servicesfix.log" -Append"$($OriginalPath.PSChildName) `"$NewPath`"" | Out-File "$LogPath\servicesfix.log" -Append
            Set-ItemProperty -Path $OriginalPath.PSPath -Name "ImagePath" -Value "`"$NewPath`""
        }
        }
    }
    If (($triger | Measure-Object).count -ge 1) { "----- Error Cant parse  $($OriginalPath.ImagePath) in registry  $($OriginalPath.PSPath -replace 'Microsoft\.PowerShell\.Core\\Registry\:\:') " | Out-File $LogPath\servicesfix.log -Append}
}
}
Fix-ServicePath -LogPath C:\Temp

Here is my attempt at getting it to run on multiple computers. It doesnt work but it also doesnt error out...

cls
$a = Get-Content "C:\support\scripts\PowerShell\UnquotedPathsFix\computers.txt"
Function Fix-ServicePath ([System.IO.DirectoryInfo]$LogPath = "C:\temp") {<#
	.SYNOPSIS
	    Microsoft Windows Unquoted Service Path Enumeration

	.DESCRIPTION
	    Use Fix-ServicePath to fix vulnerability "Unquoted Service Path Enumeration".



	    ------------------------------------------------------------------
	    Author: Vector BCO
		Version: 3.1

	.PARAMETER LogPath
		You can set different path for log files
		Defaul path is c:\Temp
		Default log file: servicesfix.log

	.NOTES


	.EXAMPLE
		 Fix-Servicepath

	.EXAMPLE
		 Fix-ServicePath -LogPath C:\DifferentPath

	.LINK
		https://gallery.technet.microsoft.com/scriptcenter/Windows-Unquoted-Service-190f0341
		https://www.tenable.com/sc-report-templates/microsoft-windows-unquoted-service-path-enumeration
		http://www.commonexploits.com/unquoted-service-paths/
	#>

if (-not (Test-Path $LogPath)){New-Item $LogPath -ItemType directory}

"**************************************************" | Out-File "$LogPath\servicesfix.log" -Append"Computername: $i" | Out-File "$LogPath\servicesfix.log" -Append"Date: $(Get-date -Format "dd.MM.yyyy HH:mm")" | Out-File "$LogPath\servicesfix.log" -Append

# Get all services
Get-ChildItem "HKLM:\SYSTEM\CurrentControlSet\Services\" | foreach {
$OriginalPath = (Get-ItemProperty "$($($_).name.replace('HKEY_LOCAL_MACHINE', 'HKLM:'))")
$ImagePath = $OriginalPath.ImagePath

# Get all services with vulnerability
If (($ImagePath -like "* *") -and ($ImagePath -notlike '"*"*') -and ($ImagePath -like '*.exe*')){
    $NewPath = ($ImagePath -split ".exe ")[0]
    $key = ($ImagePath -split ".exe ")[1]
    $triger = ($ImagePath -split ".exe ")[2]

    # Get all services with vulnerability with key in ImagePath
    If (-not ($triger | Measure-Object).count -ge 1){
        If (($NewPath -like "* *") -and ($NewPath -notlike "*.exe")){" ***** Old Value $ImagePath" | Out-File "$LogPath\servicesfix.log" -Append"$($OriginalPath.PSChildName) `"$NewPath.exe`" $key" | Out-File "$LogPath\servicesfix.log" -Append
            Set-ItemProperty -Path $OriginalPath.PSPath -Name "ImagePath" -Value "`"$NewPath.exe`" $key"
        }
        }

    # Get all services with vulnerability with out key in ImagePath
    If (-not ($triger | Measure-Object).count -ge 1){
        If (($NewPath -like "* *") -and ($NewPath -like "*.exe")){" ***** Old Value $ImagePath" | Out-File "$LogPath\servicesfix.log" -Append"$($OriginalPath.PSChildName) `"$NewPath`"" | Out-File "$LogPath\servicesfix.log" -Append
            Set-ItemProperty -Path $OriginalPath.PSPath -Name "ImagePath" -Value "`"$NewPath`""
        }
        }
    }
    If (($triger | Measure-Object).count -ge 1) { "----- Error Cant parse  $($OriginalPath.ImagePath) in registry  $($OriginalPath.PSPath -replace 'Microsoft\.PowerShell\.Core\\Registry\:\:') " | Out-File $LogPath\servicesfix.log -Append}
}
}
foreach ($i in $a)
	{$i + "'n" + "============================"; Fix-ServicePath -LogPath C:\Temp}

thanks for the help

PowerShell - Obtain parameter from SSRS report

$
0
0

Hello

I'm using PowerShell to render SSRS reports. The report I'm trying to render has a parameter that is dependent on the value(s) selected from the first parameter. I'm trying to obtain the valid values for this second parameter. Is there a way to render the report using the first parameter value to return the ValidValues available for the second parameter please? This is the code I have so far:

#-------------------------------------------------------------- 
# add assembly 
#-------------------------------------------------------------- 
Add-Type -AssemblyName "Microsoft.ReportViewer.WinForms, Version=12.0.0.0, Culture=neutral, PublicKeyToken=89845dcd8080cc91"

#-------------------------------------------------------------- 
# create timestamped folder 
# where we will save our report 
#-------------------------------------------------------------- 
$dt = Get-Date -Format "yyyy-MMM-dd hhmmtt" 
$baseFolder = "\\Folder1\"
$tempfolder = "\\Folder1\Excel files\"

# if the path exists, will error silently and continue 
New-Item -ItemType Directory -Path $baseFolder -ErrorAction SilentlyContinue | Out-Null

$ReportServerUri = "http://ServerName/ReportServer//ReportService2005.asmx?wsdl"
$global:proxy = New-WebServiceProxy -Uri $ReportServerUri  -UseDefaultCredential;
$items = $global:proxy.ListChildren("/", $true) |
         Where-Object {$_.Path -like "/ReportFolder/*"};

ForEach ($i in $items){
#-------------------------------------------------------------- 
# report Server Properties 
#-------------------------------------------------------------- 
$rv = New-Object Microsoft.Reporting.WinForms.ReportViewer
$rv.ServerReport.ReportServerUrl = "http://ServerName/ReportServer" 
$rv.ServerReport.ReportPath = $i.Path
$ReportName = $i.Name
$rv.ProcessingMode = "Remote"

$rv.ServerReport.GetParameters()| Where-Object {$_.Name -eq "P_Reg"}|
ForEach-Object {
    $param = $_
    $validValues1 = ""
    $validValues3 = ""
    if ($param.ValidValues -ne $null)
    {
        $validValues1 = [string]::Join(",", ($param.ValidValues[-1..-1] |
                       ForEach-Object {$_.Value}))
$validValues3 = $param.ValidValues[-1..-1] |
                       ForEach-Object {$_.Value}
    }
}

$rv.ServerReport.GetParameters()| Where-Object {$_.Name -eq "P_Qual"}
}

problems with null-valued expression error

$
0
0

I run my code that gathers certain parameters against multiple machines to create a report. I gather the parameters in a hashtable. Problem is when running the script against one of the machines which in theory should be identical like the others I get

You cannot call a method on a null-valued expression.

+$properties = @{

+~~~~~~~

       +CategoryInfo : InvalidOperation: (:) [], RuntimeException

       +FullyQualifiedErrorID : InvokeMethodNull

I checked all the variables that go to the hashtable and all return values unless I have some caching I'm not aware of. How can I pinpoint the one causing the error? 


yaro

vbs script to Powershell

$
0
0

Hi,

Is it possible to "translate" this VBScript to a PowerShell script. I'm a leek in PowerShell so I hope you can help. The VBScript is a logonscript so the first part is mapping drives and the second part verify if the registrysettings are correct configured for folderredirection (by check if the registryvalue's data of a random value is correct).

VBScript:

' == First Part ==

On Error Resume Next

dim objNetwork, strDrive, objShell, objUNC
dim strRemotePath, strDriveLetter, strNewName
set wshNetwork = createObject("Wscript.Network")
strUsername = wshNetwork.UserName


call cleardrives() 'Delete all mapped drives...
call mapdrive("H:","\\Server01\Home\" & strUsername,"Home")
call mapdrive("N:","\\Server01\Network","Netwerk")
call mapdrive("P:","\\Server01\Profile\" & strUsername & ".V5","Profile")
'call mapdrive("Z:","\\SERVER03\" & strUsername & "$","Home Directory")

function cleardrives()
    ' This sections creates two objects:
    ' objShell and objNetwork and counts the drives
    set objShell = createObject("WScript.Shell")
    set objNetwork = createObject("WScript.Network")
    set CheckDrive = objNetwork.EnumNetworkDrives()

    ' This section deletes all mapped network drives
    on error resume next
    for intDrive = 0 To CheckDrive.Count - 1 Step 2
    if CheckDrive.Item(intDrive) <> strDriveLetter _
    then objNetwork.RemoveNetworkDrive _
    CheckDrive.Item(intDrive), bforce
    next
end function

function mapdrive(strDriveLetter,strRemotePath,strNewName)
    'Map the network drive
    set objNetwork = createObject("WScript.Network")
    objNetwork.MapNetworkDrive strDriveLetter, strRemotePath

    'Rename the Mapped Drive
    set objShell = createObject("Shell.Application")
    objShell.NameSpace(strDriveLetter).Self.name = strNewName

end function


' == second part ==

const HKEY_CURRENT_USER = &H80000001
strRemoteComputer = "."

Set regObj=GetObject( _
    "winmgmts:{impersonationLevel=impersonate}!\\" & _
   strRemoteComputer & "\root\default:StdRegProv")

strKeyPath = "SOFTWARE\Microsoft\Windows\CurrentVersion\Explorer\User Shell Folders"
strValueName = "Desktop"
regObj.GetStringValue HKEY_CURRENT_USER,strKeyPath,strValueName,strValue
'Wscript.Echo "Application Name: " & strValue

If strValue = "H:\Desktop" Then
   Wscript.Quit
Else
Set Shell = CreateObject( "WScript.Shell" )

Shell.RegWrite "HKCU\Software\Microsoft\Windows\CurrentVersion\Explorer\User Shell Folders\{374DE290-123F-4565-9164-39C4925E467B}","H:\Downloads", "REG_EXPAND_SZ"
Shell.RegWrite "HKCU\Software\Microsoft\Windows\CurrentVersion\Explorer\User Shell Folders\Desktop","H:\Desktop", "REG_EXPAND_SZ"
Shell.RegWrite "HKCU\Software\Microsoft\Windows\CurrentVersion\Explorer\User Shell Folders\My Music","H:\Music", "REG_EXPAND_SZ"
Shell.RegWrite "HKCU\Software\Microsoft\Windows\CurrentVersion\Explorer\User Shell Folders\My Pictures","H:\Pictures", "REG_EXPAND_SZ"
Shell.RegWrite "HKCU\Software\Microsoft\Windows\CurrentVersion\Explorer\User Shell Folders\Personal","H:\Documents", "REG_EXPAND_SZ"
Shell.RegWrite "HKCU\Software\Microsoft\Windows\CurrentVersion\Explorer\User Shell Folders\My Video","H:\Videos", "REG_EXPAND_SZ"
WScript.Quit
End if

All of my about_* topics are missing from help. What gives?

$
0
0

I upgraded a windows 7 machine to windows 10, and $PSVersionTable reports PSVersion 5.0.10586.494. I've opened the PowerShell window as admin, and run update-help. None of the about_* help topics work!

I ran Get-Help * | Where-Object { $_.Name -Like "about_*" } and only about_CimSession was returned. All attempts to get-help for other about_ topics return a search list or a related topic.

What do I need to do to create a normal PowerShell environment?


No output from remote console in localhost when used foreach with invoke-command

$
0
0

Hello Experts,

I'm not getting any output from the below script. I'm trying to execute a foreach loop in remote computer and get the output in local machine. However, am not getting any output. Below is the script and output.

SCRIPT

$servers = "SERVER1","SERVER2"
ForEach ($server in $servers)
{
Write-Host "Collecting data from $server" -ForegroundColor "Green"
       If (Test-Connection -computername $server -quiet) 
       {
            Invoke-Command -ComputerName $server -ScriptBlock {foreach ($n in (get-disk -FriendlyName "HITACHI OPEN-V  Multi-Path Disk Device").Number) {mpclaim -s -d $n | Select-String -Pattern "SN|Paths"}}
       }
}

OUTPUT

PS C:\Windows\system32> C:\Users\suman\Desktop\Untitled1.ps1
Collecting data from SERVER1

   < NO OUTPUT HERE>

Collecting data from SERVER2


   < NO OUTPUT HERE>


PS C:\Windows\system32>

Could someone please help me in getting this fixed.

HTML email sent as raw

$
0
0

use the following command to send an HTML formatted (hopefully) message.

Send-MailMessage -From $From -to $Recipients `
   -Subject $Subject -BodyIsHtml -Body $Body `
   -SmtpServer $SMTPServer -port $SMTPPort `
   -Credential $Credentials

But the output to an email client is

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <title>HTML TABLE</title> </head><body style="border: 1px solid black; border-collapse: collapse;">     <h3>Script name: backup_outlook_test.ps1</h3><h3>Start: 2016-08-25 15:01:25, End: 2016-08-25 15:01:25 Duration: 0:00:00.0298102 </h3> <table style="border: 1px solid black; border-collapse: collapse;"> <colgroup><col/><col/></colgroup> <tr><th style="border: 1px solid black; background: #dddddd; padding: 5px;">TimeStamp</th><th style="border: 1px solid black; background: #dddddd; padding: 5px;">Message</th></tr> <tr><td style="border: 1px solid black; padding: 5px;">8/25/2016 3:01:25 PM</td><td style="border: 1px solid black; padding: 5px;">test</td></tr> <tr><td style="border: 1px solid black; padding: 5px;">8/25/2016 3:01:25 PM</td><td style="border: 1px solid black; padding: 5px;">Archiving complete</td></tr> <tr><td style="border: 1px solid black; padding: 5px;">8/25/2016 3:01:25 PM</td><td style="border: 1px solid black; padding: 5px;">Archive created and moved to D:\temp</td></tr> <tr><td style="border: 1px solid black; padding: 5px;">8/25/2016 3:01:25 PM</td><td style="border: 1px solid black; padding: 5px;">Successful completion</td></tr> </table> </body></html>
What am I doing wrong?

merging or combining to powershell scripts

$
0
0

Hello Powershell Community.

I have a powershell script that returns critical info about the different machines on my network. Right now in my powershell script I'm calling a text file from my desktop that loops through a list of machine names that I've provided.

This process is taking a very long time because I have over 250 machines in my text file and not all of them are always on at the same time. What I would like to do is modify my current powershell to scan an IP range instead of read from a text file with a list of machine names. My current process is taking over 7 minutes and I believe it is because my PS script is querying the text file regardless if the machine is on or not.

I think this is possible, but I don't know how to do it. I have a separate powershell that will scan an IP range and resolve machine names.

1..254 | ForEach-Object {Get-WmiObject Win32_PingStatus -Filter "Address='10.128.116.$_' and Timeout=200 and ResolveAddressNames='true' and StatusCode=0" | select ProtocolAddress*}

And Here is my main PS script:

# http://powershell.org/wp/forums/topic/creating-a-array-of-info-for-remote-computers/
function Get-IPAddress ($computer = $env:COMPUTERNAME) {
    return (Test-Connection $computer -Count 1).IPV4Address.tostring()
}
function Get-MachineName ($computer = $env:COMPUTERNAME) {
    $reg = [Microsoft.Win32.RegistryKey]::OpenRemoteBaseKey('LocalMachine', $computer)

    return $computer
}

function Get-LoggedInUser ($computer = $env:COMPUTERNAME) {
    # could use this to get logged in user
    #(Get-WmiObject win32_computerSystem -ComputerName $computer).username

    $owners = @{}
    Get-WmiObject win32_process -ComputerName $computer -Filter 'name = "explorer.exe"' | % {$owners[$_.handle] = $_.getowner().user}
    return Get-Process -ComputerName $computer explorer | % {$owners[$_.id.tostring()]}
}

function Get-OfficeVersion ($computer = $env:COMPUTERNAME) {
    $version = 0

    $reg = [Microsoft.Win32.RegistryKey]::OpenRemoteBaseKey('LocalMachine', $computer)

    $reg.OpenSubKey('SOFTWARE\Microsoft\Office').GetSubKeyNames() | % {
        if ($_ -match '(\d+)\.') {
            if ([int]$matches[1] -gt $version) {
                $version = $matches[1]
            }
        }
    }

    return $version
}

function Get-IPAddress ($computer = $env:COMPUTERNAME) {
    return (Test-Connection $computer -Count 1).IPV4Address.tostring()
}

function Get-IEVersion ($computer = $env:COMPUTERNAME) {
    $keyname = 'SOFTWARE\Microsoft\Internet Explorer'

    $reg = [Microsoft.Win32.RegistryKey]::OpenRemoteBaseKey('LocalMachine', $computer)
    $key = $reg.OpenSubkey($keyname)
    $version = $key.GetValue('Version')
    $svcUpdateVersion = $key.GetValue('svcUpdateVersion')

    if ($svcUpdateVersion) {
        return $svcUpdateVersion
    } else {
        return $version
    }
}

function Get-JavaVersion ($computer = $env:COMPUTERNAME) {
    $keyname = 'SOFTWARE\JavaSoft\Java Web Start'

    $reg = [Microsoft.Win32.RegistryKey]::OpenRemoteBaseKey('LocalMachine', $computer)
    $key = $reg.OpenSubkey($keyname)
    $version = $key.GetValue('CurrentVersion')

    return $version
}

# script entry point
$computernames = Get-Content C:\Users\ppagal\Desktop\servers.txt

foreach ($computer in $computernames) {
    [pscustomobject]@{

        MachineName = Get-MachineName $computer
        IPAddress = Get-IPAddress $computer
        LoggedInUser = Get-LoggedInUser $computer
        OfficeVersion = Get-OfficeVersion $computer
        IEVersion = Get-IEVersion $computer
        JavaVersion = Get-JavaVersion $computer
    }
}

$results | Format-Table -AutoSize

$results | Export-Csv c:\users\ppagal\desktop\Test.csv -NoTypeInformation
I have already tried replacing 
# script entry point
$computernames = Get-Content C:\Users\ppagal\Desktop\servers.txt

with 

1..254 | ForEach-Object {Get-WmiObject Win32_PingStatus -Filter "Address='10.128.116.$_' and Timeout=200 and ResolveAddressNames='true' and StatusCode=0" | select ProtocolAddress*}

BUT that did not work.

Any help would be appreciated! Thanks so much in advance.

Techstudent01

How to use Select with collections and single value variables

$
0
0

Hi,

The goal is to retrieve properties from user accounts to export to a csv file.  Some properties are collections, like businesscategory, while others are not, like enabled, passwordLastset, passwordexpired, etc.  How do I expand the businesscategory collection during a select-object while also selecting other single value variables?  The following does not work.

Get-Aduser -filter {SamAccountName -like "abc*"} -properties DisplayName, Description, Enabled, BusinessCategory, PasswordExpired, PasswordLastSet | Select SamAccountName, DisplayName, Description, Enabled, BusinessCategory, PasswordExpired, PasswordLastSet -ExpandProperty BusinessCategory | Export-Csv -LiteralPath c:\afile.csv -NoTypeInformation


Thanks for your help! SdeDot

hashtable error

$
0
0

When I run my script the below line throws an error:

$MyArray1 = @{address = $a,filename = $filename}

The red error text repeats the line, puts a squiggly after the first comma following $a and says "Missing expression after ','

$a and $filename are declared beforehand

Viewing all 21975 articles
Browse latest View live


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