Quantcast
Channel: The Official Scripting Guys Forum! forum
Viewing all 15028 articles
Browse latest View live

need help with a script applied by GPO

$
0
0

Hello,

I need to automate WebFeed insertion for Remote App Users at user logon.

RDS 2012 R2 in place. Remote Apps are provided to W7 clients.

Currently, WebFeed link must be inserted manually in each user's Control Panel\RemoteApp and Desktop Connections. There
is no straight forward way from Microsoft.
But there is a script and instruction I found on web...

I followed the instruction... Created GPO. GPO applies to user but nothing happens.
Can somebody check the script and the instruction that I could wrongly applied.

In instruction there is no word about changing something in the script but only wcx file that the script should
use.
The script is below and here is my .wcx file:

______________________

<?xml version="1.0? encoding="utf-8? standalone="yes"?>
<workspace name="Enterprise Remote Access" xmlns="http://schemas.microsoft.com/ts/2008/09/tswcx" xmlns:xs="http://www.w3.org/2001/XMLSchema">
<defaultFeed url="https://my_webserver_real_FQDN/rdweb/Feed/webfeed.aspx" />
</workspace>

_______________________________________

I changed the quotes to vertical (") from (”) that
were in my wcx when copied the lines from web.

Still not works.
I
checked Application log, PowerShell and RemoteApp in eventviewer under user session


Everything is clean.

Were I can check the script execution log?

When the user with applied script logs in, the icon of Remote
connection appears for 10 seconds on the task bar and disappears.

Looks like it's trying...

Check please if the script really should not be touched and provide some troubleshooting
steps.

Thanks!

****************************
INSTRUCTIONS from
the link:
http://www.concurrency.com/infrastru...rver-2012-rds/

"Unfortunately
Windows 7 clients are out of luck here. If you really want to use GPO to deploy
RemoteApps to Windows 7 clients, then you have to jump through a few
hoops.

Create a new GPO and under User ConfigurationPoliciesWindows
SettingsScripts
, double click Logon and click the Show Files
button. This will open an explorer window where you can copy files that will be
saved within this GPO. Download the Install-RADCConnection.ps1 script from the TechNet gallery and
save it there. Also create a new Text file named something like feed.wcx,
open it in Notepad and paste in the following three lines of text:
<?xml
version=”1.0″ encoding=”utf-8″ standalone=”yes”?>
<workspace
name=”Enterprise Remote Access” xmlns=”http://schemas.microsoft.com/ts/2008/09/tswcx”xmlnss=”http://www.w3.org/2001/XMLSchema”>
<defaultFeed
url=”https://rds.domain.com/RDWeb/Feed/webfeed.aspx
/>
</workspace>
Now select the PowerShell Scripts tab and
click the Add button.

Click Browse and select the .ps1 file and
for the parameters enter the name of the wcx file. Click OK twice and you are
ready to scope that policy to a set of users.   

<#
.SYNOPSIS
    Installs a connection in RemoteApp and Desktop Connections.
.DESCRIPTION
    This script uses a RemoteApp and Desktop Connections bootstrap file(a .wcx file) to set up a connection in Windows 7 workstation. No user interaction is required.It sets up a connection only for the current user. Always run the script in the user's session.

The necessary credentials must be available either as domain credentials or as cached credentials on the local machine. (You can use Cmdkey.exe to cache the credentials.)

Error status information is saved in event log: (Applications and Services\Microsoft\Windows\RemoteApp and Desktop Connections).

.Parameter WCXPath
    Specifies the path to the .wcx file

.Example

PS C:\> Install-RADCConnection.ps1 c:\test1\work_apps.wcx

Installs the connection in RemoteApp and Desktop Connections using information
in the specified .wcx file.

#>
Param(
    [parameter(Mandatory=$true,Position=0)]
    [string]
    $WCXPath
)


function CheckForConnection
{
    Param (
        [parameter(Mandatory=$true,Position=0)]
        [string]
        $URL
    )

    [string] $connectionKey = ""
    [bool] $found = $false

    foreach ($connectionKey in get-item 'HKCU:\Software\Microsoft\Workspaces\Feeds\*' 2> $null)
    {

        if ( ($connectionKey | Get-ItemProperty -Name URL).URL -eq $URL)
        {
            $found = $true
            break
        }
    }

    return $found
}


# Process the bootstrap file
[string] $wcxExpanded = [System.Environment]::ExpandEnvironmentVariables($WCXPath)
[object[]] $wcxPathResults = @(Get-Item $wcxExpanded 2> $null)

if ($wcxPathResults.Count -eq 0)
{
    Write-Host @"

The .wcx file could not be found.

"@

    exit(1)
}

if ($wcxPathResults.Count -gt 1)
{
    Write-Host @"

Please specify a single .wcx file.

"@

    exit(1)
}

[string] $wcxFile = $wcxPathResults[0].FullName
[xml] $wcxXml = [string]::Join("", (Get-Content -LiteralPath $wcxFile))
[string] $connectionUrl = $wcxXml.workspace.defaultFeed.url

if (-not $connectionUrl)
{
    Write-Host @"

The .wcx file is not valid.

"@

    exit(1)
}

if ((CheckForConnection $connectionUrl))
{
    Write-Host @"

The connection in RemoteApp and Desktop Connections already exists.

"@

    exit(1)
}

Start-Process -FilePath rundll32.exe -ArgumentList 'tsworkspace,WorkspaceSilentSetup',$wcxFile -NoNewWindow -Wait

# check for the Connection in the registry
if ((CheckForConnection $connectionUrl))
{
    Write-Host @"

Connection setup succeeded.

"@
}
else
{
    Write-Host @"

Connection setup failed.

Consult the event log for failure information:
(Applications and Services\Microsoft\Windows\RemoteApp and Desktop Connections).

"@

    exit(1)
}






--- When you hit a wrong note its the next note that makes it good or bad. --- Miles Davis


Update and Append Data to SQL via PowerShell

$
0
0

Hello,

I've been searching online and in the forum for a way to do this, but haven't come up with anything yet.  This is my goal...

I have a CSV file that needs to get loaded into an existing SQL table.  

Some updates will be simple / standard field updates, but one field, named Comments, is a free text field that I need to retain the data in and only append the latest update to.

Example:  Keeping track of computers in a database.  Updating a PC...

Update SN XYZ, location=newlocation, inventorydate=newdate, personwhoinventoried=newpersonname, comments="Updated asset with new inventory date and location per physical inventory 2/11/2015."

Comments field will already contain other comments, all of which need to be retained with the newest one added to the bottom.

I'd like to do this via PowerShell if possible, but straight SQL is OK too.  

Thanks in advance.

Script to Delete All of the Profiles of users logged off of server

$
0
0

I have several servers I am in charge of. Because of load balancing and roaming profiles, over months, these servers get 1000's of profiles on them yet we have less than 1000 users. I found that by deleting all of the profiles from theAdvanced System Settings in Computer Properties, it cleared up 100's of GB's of data off of the servers and increased the servers efficiency 25%!Plus, since we use roaming profiles, none of the users noticed the difference except that their thin clients ran quicker.

Since this worked so well, I would rather not spend 3-4 hours once a month deleting profiles off of the servers again. I found a script that looks like it may work, but I need to make sure that it will only delete the users who are logged on. In theAdvanced System Settings, you were not able to delete a users profile if they were logged in. I am asking for help, since I cannot test this without potentially destroying a lot of stuff here, that this script below will not:

1. It will not delete users profiles while they are logged on.

2. It will not mess up when it comes across a user logged in.

Here is the script:

On Error Resume Next

args = WScript.Arguments.Count

If args <> 1 Then
  WScript.Echo "usage: delete_profiles SVRNAME"
  WScript.Echo "example (for remote profiles): cscript.exe delete_profiles SOMESERVER  "
  WScript.Echo "example (for local profiles): cscript.exe delete_profiles .  "
  WScript.Quit
End If

strComputer = WScript.Arguments.Item(0)
Set objWMIService = GetObject("winmgmts:\\" & strComputer &"\root\cimv2")
Set colProfiles = objWMIService.ExecQuery("Select * from Win32_UserProfile")
Wscript.Echo "==" & WScript.Arguments.Item(0) & "==" & vbNewLine

For Each objProfile in colProfiles
  Set objSID = objWMIService.Get("Win32_SID.SID='" & objProfile.SID &"'")
      If (objSID.ReferencedDomainName = "DOMAIN NAME") Then
      If Not ((objSID.AccountName = "USERNAME TO EXCLUDE") Or (Left (objSID.AccountName,2) = "USERNAME PREFIX TO EXCLUDE")) Then
          Set objUserProfile = GetObject("winmgmts:{impersonationlevel=impersonate}!\\" _
          & strComputer &"\root\cimv2:Win32_UserProfile." _
          &"SID='" & objProfile.Sid &"'")
          objUserProfile.Delete_
     Wscript.Echo objSID.AccountName & ";" & objSID.ReferencedDomainName & ";" & objProfile.LocalPath & " - " & "DELETED"
     End If
End If
Next

In line 19 you have to specify the domain name to be used in the script and in line 20 you can specify user accounts that shouldn't be deleted, such as Administrator accounts.

If this is not going to do what I want, is there a script for that?

Thanks in advance for any help!

Powershell: use of ++ and variables in a statement

$
0
0

Dear Experts:

I know ++ adds 1 to the count so for e.g. if $ file = 10 then

     $file++ changes the value of the variable to 11.

But I can't understand its application in this statement below because my (gci).count is 27, BUT  $filecount is giving me 54. Also the statement use $filecount instead of $_.

                        gci | foreach-object { $filecount++ $totsize+= $_.Length}

Also i thought we have separate each item with commas or semicolon but if this statement assuming it is correctly written is not using commas after $filecount++ like in $filecount++, $totsize

Can someone explain me what this command above is doing piece wise....

Regards

SQL75


Looking to build a batch file for BCDedit

$
0
0

I'm trying to build a batch file for bcdedit to get the variable off of one of my boots for the identifier to use to build my dual boot system.  I've been testing with trying to just get the identifier but I'm unable to get the variable when I try.

Any help will be greatly appreciated!

I've ran all the steps individually and they function like they are supposed to.

Here is the basics. 

First I need to change the descriptions around so

bcdedit /set {current} description "Staff"

bcdedit /set (insert variable for second boot) description "test"

next I need to change order

bcdedit /displayorder {current} /addfirst

Last is to set the second drive partition

bcdedit /set (insert variable) device partition=D:

bcdedit /set (insert variable) osdevice partition=D:

Powershell:Folder permission

$
0
0

I would like to use powershell to script out folder permissions in the following format (CSV)

Foldername                      Users/Group                            Permission                           Isinherit              FolderOwner      

[Powershell 3] add value from where-object ?

$
0
0

hello, in this script i need to add email value to a string email1@email.it; email2@email.it;email3@email.it ...

help :)


Problem to the line

$
0
0
Hi,
Within the Win 7 machine, when running this line

Set objFunc = CreateObject("CSDemo.ComClass1")
...



I get the attached error below. 


Why?

Many Thanks & Best Regards, Hua Min


Not receiving all data while running a script

$
0
0
Hello, I have been working on this script the last few days now and get farther and farther on it. Yesterday I finally thought I had it all complete and went to implement on a server. When I finally moved it over and did a test run the only data I was sent was two things Success and seconds. I didn't actually get the date or anything else. When I says seconds it just said that but didn't actually get me any data. When I ran this on me machine before I moved it over it was working. When I moved it back to my computer and tried again I am no longer getting the same results. For some reason it worked for awhile but no it isn't.

$cred = Import-Clixml -Path C:\users\passworddoc.xml
$url = "siteURL"
$response=Invoke-WebRequest $url -Credential $cred


   if ($response.statuscode -eq 200) {
      "Success`t`t" + $startTime.DateTime + "`t`t" + ($endTime - $startTime).TotalSeconds + " seconds" | Out-File "C:\Users\T&E.csv" -Append
   } else {"Fail`t`t" + $startTime.DateTime + "`t`t" + ($endTime - $startTime).TotalSeconds + " seconds" | Out-File "C:\Users\T&E.csv" -Append
   }



how to add a local serial printer with vbscript

$
0
0
For a new application that we are rolling out I need to add several printers to about 100 Windows XP workstations.  Two of them are network printers and fairly easy to add using vbscript.  The one I am having problems with is a locally attached serial printer.  I am not really sure where to start for creating the port.  I need it to use COM1 (4800, 8, none, 1) with the Generic / Text Only driver.  Any ideas how to get started on this?

Modifying Active directory problems

$
0
0

I imported users from xml file to AD. I created some attributes in my AD schema which are starting with letter 'v'.

I am try to modify some attributes of AD users using this script. 

$path_to_users_xml = "C:\veracross\facstaff.xml"
$Dataxml = [Xml] (Get-Content $path_to_users_xml)
 $Datas =  $Dataxml.facstaff.facstaff



 #$datas

 foreach ($facstaff in $Datas )
  {
  $facstaff

    $OU = "ou=Staff,dc=psi,dc=kiev,dc=ua"
    $login = [string] $facstaff.email_1
    $login =  $login.replace("@psi.kiev.ua", "")

  $hash= @{

  Company = $facstaff.faculty_type
  Title = $facstaff.job_title
  Department = $facstaff.department
  Enabled = $true
  Path = $OU
  vbiography = $facstaff.biography
  vrole = $facstaff.roles
  vSchoolLevel = $facstaff.School_Level
  vupdatedate = $facstaff.update_date

  }
 Get-ADUser -identity $login -properties Company,Title,Department,vbiography,vrole,vschoollevel,vupdatedate
    Set-ADUser $login -Replace $hash

}
            

But I receive error listed down :

Set-ADUser : An attempt was made to modify an object to include an attribute that is not legal for its class
At C:\Users\Administrator\Desktop\Scripts\Creaters\Staff_User_Update.ps1:53 char:5
+     Set-ADUser $login -Replace $hash
+     ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : NotSpecified: (XXXX:ADUser) [Set-ADUser], ADException
    + FullyQualifiedErrorId : An attempt was made to modify an object to include an attribute that is not legal for its class,Microsoft.ActiveDirectory.Management.Commands.Set 
   ADUser

Problem enabling inheritance

$
0
0

Hi there!

I've been coding 8 hours for a little script for change the audit rules of a folder tree, and I doesn't understand yet how SetAuditRuleProtection works. This snippet is pretty simple:

$Acl = Get-Acl $Object.FullName -Audit

$Acl.SetAuditRuleProtection($false, $false)

$Acl | Set-Acl # Or $Acl | Set-Acl $Object.FullName, same behavior

This not enable the inheritance in the object $Object, why? What am Idoing wrong? I am very frustrated with this :(

Even when I have the button "Disable inheritance" in the Auditingtab of the object (it means that inheritance is enabled, I think), the audit rules from parent doesn't appears until I modify this (create a rule, delete the rule [no changes at all], apply should work).

It's annoying :(

Sorry for my bad English



Set pagefile size to 1.5x RAM

$
0
0

Hi guys,

Could not find another forum for this. Trying to automate Server 2012 R2 deployments, in our normal checklist for deploying an OS, someone has to go in and set the pagefile to 1.5x RAM on server. Majority of our servers have 4GB, but can vary +/- a few GBs. What I am looking for is something I can have run from Altiris to query amount of RAM installed and then set pagefile initial & max to 1.5x RAM installed. 

Any help is appreciated. Thanks.

Mapping a persistent drive under a different user

$
0
0

I have my regular user account and I have an admin account. A lot of times I need to run PowerShell under the context of my admin account so I have access to do things on servers that my regular account does not have. 

I want to map a drive persistently under this admin account using PowerShell commands. I foundthis post by Jeffery Hicks that sounds like I can do exactly what I was hoping to do. However, it is not behaving as I would expect.

I am using PowerShell v4 on Win7.

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

The setup: Logged in as Regular-User; running PowerShell as admin-account

I execute the command just like in the post by Jeff:

New-PSDrive -Name S -PSProvider FileSystem -root "\\some\unc\path" -persist

After running this command, I can verify it exists by navigating to it and or running psdrive to see it listed.

Now, according to the article (Jeff Hicks is a MVP in PowerShell btw) I should be able to close this PowerShell session and open a new one in the context of the same user and that drive will still be there:

"Now I have a drive that is accessible in Windows. The PSDrive will persist between PowerShell sessions and it even reboots until I remove it. The one requirement is that you must define the new PSDrive using an available drive letter for the PSDrive name.

Also, don't forget that drive mappings are stored per user. Normally this shouldn't matter much, but be aware that when you run an elevated PowerShell session that is actually using different credentials -- if you map a persistent drive, you may not see it in Windows."

I am finding this not true. If I run 'psdrive' I no longer see it listed. If I run 'net use' I see my drive but it is "unavailable". I have tried using different drive letters, running PS as administrator and using the same account, and specifying -credentials in the drive mapping. 

Have I misinterpreted the article? Am I missing something? Thanks in advance.

search files from multiple servers from get-childitem

$
0
0

Hi 

I have created below script to find out all files from remote computers which have extensions like jpg and all. I am able to find 

But I want to search files which are more than 10 MB and length header should be likeSize in MB" instead of length.

Please help or guide me..

Import-Csv .\serverlist.csv | Foreach {

$searchservername = $_.rebootserveranme
$path = "c:\","D:\"
$size = 10MB
$extensions = '*.jpg*', '*.jpeg*', '*.mpeg', '*.pdf', '*.avi', '*.mov'
Get-ChildItem -Path $path -Include $extensions -Recurse -Force | select fullname,CreationTime,LastAccessTime,LastWriteTime,PSChildName,extension,length | export-CSv "files-$searchservername.csv" -Notypeinformation
}


Get all IPV4 address with power shell

$
0
0

Hello

I need to be able to output all IPV4 address to one line in txt file. Here is what I am using currently:

$IP= (get-WmiObjectWin32_NetworkAdapterConfiguration |Where-Object { $_.Ipaddress.length-gt1 }).ipaddress[0]

 

When I run this command on a computer that has wired network adapter it works fine. When I run this same command against a computer that has wireless adaptor I get nothing in the output file. Can you tell me what I am doing wrong or point to a web resource please.

Thanks



concurrent do-loops in powershell

$
0
0

I'm looking for the simplest and/or best way to run two do-loops concurrently. I can do this with two separate scripts running in two separate windows...but I'm sure there's a more efficient way. I played a little with the "workspace" method, but haven't yet figured it all out. Is the workspace approach the best way? Is it the easiest way? A sample script that launches two do-until loops concurrently would be appreciated. Here are to two scripts I have running in separate windows now:

SCRIPT 1--

$relayoff = {

do {
$request = get-content relay.txt
} until ($request -notmatch '0')

&$relayon

}

$relayon = {

$port= new-object system.io.ports.serialport com7,4800,none,8,one

$port.open()

echo 1 > relay.txt

do {
$hold = get-content relay.txt
$port.writeline("1InthebeginningwastheWord,andtheWordwaswithGod,andtheWordwasGod.2HewasinthebeginningwithGod.3AllthingsweremadethroughHim,andwithoutHimnothingwasmadethatwasmade.4InHimwaslife,andthelifewasthelightofmen.5Andthelightshinesinthedarkness,andthedarknessdidnotcomprehend[a]it.")
} until ($hold -match '0')

$port.close()

&$relayoff

}

&$relayoff

SCRIPT 2--

$wait = {

do {
$read = get-content relay.txt
$request = $read
} until ($read -notmatch '0')

do {
$read = get-content relay.txt
} until ($read -match '1')

&$play

}

$play = {

.\sounder.exe $request

Wait-Process sounder

echo 0 > relay.txt

&$wait

}

$read = get-content relay.txt

&$wait

Flags and other information are passed between these two scripts and a GUI via the text file "relay.txt".  So currently there are three programs running concurrently: two powershell windows and the GUI.  If I can combine the two scripts, I will eliminate one of these windows. I'll still need the text file for the sake of the GUI, but not for the do-loop variables.


Download a UNIX based CGI page into a CSV file using Powershell

$
0
0

Hello,

I have been struggling to get a powershell script to work.

I have a web-based page which ends in .cgi and I want to copy the text from that page to a CSV file.

Normally the below script works for .html or .aspx types of pages but this time I have been getting the 'The remote server returned an error: (401) Unauthorized' page. I think the error is because the page is Unix based and for some reason I am not able to automate the authentication process.

Below is the Powershell script I have been using. I have already created the securestring for my password and saved in a temp folder.

__________________________________________________________________________________

$wc=new-object system.net.webclient

$password = get-content 'C:\temp\Scripts\SecureString.txt' | convertto-securestring

$wc.Credentials = new-object -typename System.Management.Automation.PSCredential -argumentlist "Domain\username", $password

$wc.downloadfile("https://website.domain.com/cgi-bin/text_status_csv.cgi", "C:\temp\Scripts\output.csv")

_________________________________________________________________________________________

Currently I am able to successfully copy the data from the page over if I use

$wc.Credentials = Get-Credential

And then type in the username and password manually. I could really use some help to get this automated.

Thanks in advance for your help

Removing TMP files.

$
0
0

Hello everyone.. Hoping to get a little help from the more experienced. :)  

We have this PS command to delete users temp folders - 

Remove-Item -Path 'C:\Users\*\NS5\tmp' –Recurse

We have been asked to complete this process by adding it to the end of an already used batch file.  Is it possible to change the above powershell command to a batch command and add it into a working script?  It can be ran at the end of the process or anywhere in between. 

Hope this is clear, and thanks for the help!

Explanation for about_splatting example?

$
0
0

Hi,

I was just exploring the help files in Powershell and stumbled upon the about_splatting examples. There is one example that looks like this:

function Get-MyCommand 
        { 
            Param ([switch]$P, [switch]$C)
            if ($P) { Get-Process @Args }
            if ($C) { Get-Command @Args }
        }
PS C:\> Get-MyCommand -P -C -Name PowerShell

The results are quite interesting. If I run:

Get-Process -Name PowerShell

and then

Get-Command Powershell

... I get very different results compared to if I run them at the same time, like this:

Get-Process -Name PowerShell
Get-Command -Name Powershell

I guess this was discussed during the scripting games 2012 (Rohn Edwards, respect!), but I wasnt around at that time and I cant find anything related if I search for it.

The last part of the result looks similar to the result from this:

Get-Command -Name PowerShell | select *
Can someone please explain how this works? Why do I get two very different results if I run the commands separately compared to if i run them after one another, on separate lines, in a script?

Viewing all 15028 articles
Browse latest View live


Latest Images

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