Downloading files with powershell 2.0 on windows 7 - powershell-2.0

Here's my script to download the file, im replacing the url to download from because it's a private cloud site, i've searched everywhere and they all say that this is the right way to download in older versions of PS but i keep getting the error
Exception calling "DownloadFile" with "2" argument(s): "An exception occurred during a WebClient request." At line:60 char:25 + $client.DownloadFile <<<< ($url, $targetFile) + CategoryInfo : NotSpecified: (:) [], MethodInvocationException + FullyQualifiedErrorId : DotNetMethodException
$url = "(download url)"
$path = "C:\temp\jre-7u71-windows-i586.exe"
# param([string]$url, [string]$path)
if(!(Split-Path -parent $path) -or !(Test-Path -pathType Container (Split-Path -parent $path))) {
$targetFile = Join-Path $pwd (Split-Path -leaf $path)
}
"Downloading [$url]`nSaving at [$path]"
$client = new-object System.Net.WebClient
$client.DownloadFile($url, $targetFile)
#$client.DownloadData($url, $targetFile)
$path

I had the same problem and there seems to be a problem in the way you declared your $client variable.
Old post, but this works for me in Windows 7, PowerShell 2.0
Please note that URL and Path are changed.
$url = "http://www.7-zip.org/a/7z1604.exe"
$path = "C:\temp\7z1604.exe"
# param([string]$url, [string]$path)
if(!(Split-Path -parent $path) -or !(Test-Path -pathType Container (Split-Path -parent $path))) {
$targetFile = Join-Path $pwd (Split-Path -leaf $path)
}
(New-Object Net.WebClient).DownloadFile($url, $path)
$path

Related

Error when using Tags during certificate import through Azure PowerShell

Issue description: (Please see below screen dump for reference)
Failure using Tag with Import-AzureKeyVaultCertificate cmdlet.
The certificate would be imported into key vault okay even though I got the error message (as shown below).
However, I am not able to retrieve the certificate using Get-AzureKeyVaultCertificate cmdlet, even though I could use Get-AzureKeyVaultSecret cmdlet (Tags displayed correctly).
Additional info
• If I remove Tags from Azure portal or re-import the certificate without -Tag, I will still get the same error (Unable to cast object).
• If I delete the cert and re-import the certificate without Tags, everything is working great.
Assistance needed:
I am using 5.1.2 Azure PowerShell. Please advise what am I missing. Thanks.
PS C:\Users\tonychou> $certificateTag = #{
type = "certificate";
subjectname = "rsppe-microsoft-com";
alternatename = "dss";
environment = "Test"
};
PS C:\Users\tonychou> $certificatePasswordSecuredString = ConvertTo-SecureString $certificatePassword -AsPlainText -Force;
Import-AzureKeyVaultCertificate -VaultName $kvName -CertificateName $certInCertName -FilePath $certificatePfxFile -Password $certificatePasswordSecuredString -Tag $certificateTag;
Import-AzureKeyVaultCertificate : Unable to cast object of type 'System.Collections.Generic.Dictionary`2[System.String,System.String]' to type 'System.Collections.Hashtable'.
At line:2 char:1
+ Import-AzureKeyVaultCertificate -VaultName $kvName -CertificateName $ ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : CloseError: (:) [Import-AzureKeyVaultCertificate], InvalidCastException
+ FullyQualifiedErrorId : Microsoft.Azure.Commands.KeyVault.ImportAzureKeyVaultCertificate
PS C:\Users\tonychou> $certInCertificate = Get-AzureKeyVaultCertificate -VaultName $kvName -Name $certInCertName;
Get-AzureKeyVaultCertificate : Unable to cast object of type 'System.Collections.Generic.Dictionary`2[System.String,System.String]' to type 'System.Collections.Hashtable'.
At line:1 char:22
+ ... rtificate = Get-AzureKeyVaultCertificate -VaultName $kvName -Name $ce ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : CloseError: (:) [Get-AzureKeyVaultCertificate], InvalidCastException
+ FullyQualifiedErrorId : Microsoft.Azure.Commands.KeyVault.GetAzureKeyVaultCertificate
PS C:\Users\tonychou> $certInSecret = Get-AzureKeyVaultSecret -VaultName $kvName -Name $certInCertName;
PS C:\Users\tonychou> $certInCertificate
PS C:\Users\tonychou> $certInSecret
SecretValue : System.Security.SecureString
SecretValueText : MIIXegIBAzCCFzoGCSqGSIb3DQEHAaCCFysEghcnMIIXIzCCBgQGCSqGSIb3DQEHAaCCBfUEggXxMIIF7TCCBekGCyqGSIb3DQEMCgECoIIE9jCCBPIwHAYKKoZIhvcNAQwBAzAOBAgn0z9KUgiVSwICB9AEggTQ+38U79mo15qmAm7r0IgpGlveZFMHwqYt/LmEZOUyTKXv6GWHxkSoy/+dsa2XkVFruWas5WgqksMuwxY
43kum42JCzSHIkEzAbiN3zZNZWM7JDLaXBooR2bpOR49fdGdy44RmQjFGkU7w2cYLMjB+WSBQ9tt2xw4W1fJnv4d3vO44BQ/c2n1aHBZjmobdSrIDtpK8h+aiZyUrNix6wlifthI884h09rlF6ipBDicbgLn4NbpYPzfZlpa304fU9c7h0j/IDpdOi2zZOVT2Q3oc9ouMuSaKBC9CKE3Q99UBwyX/tZjM/A/uuW5nh3KQZ8
IJciW7/odBt3b9venZOHHbAZDns5iIzwop3hzSEDbQTqQ3hffdFEyUexHsq5AP2syveZYWlIrDpe9YJVB
PS C:\Users\tonychou> Get-Module -ListAvailable | ?{$_.Name -eq "Azure"}
Directory: C:\Program Files\WindowsPowerShell\Modules
ModuleType Version Name ExportedCommands
---------- ------- ---- ----------------
Script 5.1.2 Azure {Get-AzureAutomationCertificate, Get-AzureAutomationConnection, New-AzureAutomationConnection, Remove-AzureAutomationConnection...}
We suggest moving to Powershell version 6.0.0 and above

Creating registry DWORD entry with PowerShell

I am trying to create registry entries for some time now.
Enviroment:
Offline environment (No Domain)
1 Windows Server 2012 R2
200 Windows 7 clients
The following entry should be created on several computers:
[HKLM\SOFTWARE\Microsoft\Windows\CurrentVersion\Policies\system]
"LocalAccountTokenFilterPolicy"=dword:00000001
For this I would like to use the following script
$Computers = Get-Content "C:\Scripts\Clients.txt"
$Path = "HKLM\SOFTWARE\Microsoft\Windows\CurrentVersion\Policies\System"
$Name = "LocalAccountTokenFilterPolicy"
$PropertyType = "DWord"
$Value = 1
$results = foreach ($computer in $Computers) {
if (Test-Connection -ComputerName $computer -Count 1 -Quiet) {
try {
Set-ItemProperty -Path $path -Name $Name -Value $Value -Type $PropertyType -ErrorAction 'Stop'
$status = "Success"
} catch {
$status = "Failed"
}
} else {
$status = "Unreachable"
}
New-Object -TypeName PSObject -Property #{
'Computer' = $computer
'Status' = $status
}
}
$results | Export-Csv -NoTypeInformation -Path "./error.csv"
The script is executed, no error appears, but the entries were not created.
Where is my error?
Always try a simple 'Get' first, and then progress to testing lines before trying your 'Set'...
So you first test locally on a system, before your foreach invoke, on single system:
`Get-ItemProperty HKLM:SOFTWARE\Microsoft\Windows\CurrentVersion\Policies\System -Name LocalAccountTokenFilterPolicy`
If you get a good response like this:
LocalAccountTokenFilterPolicy : 0
PSPath : Microsoft.PowerShell.Core\Registry::HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\Curre
ntVersion\Policies\System
PSParentPath : Microsoft.PowerShell.Core\Registry::HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\Curre
ntVersion\Policies
PSChildName : System
PSDrive : HKLM
PSProvider : Microsoft.PowerShell.Core\Registry
Then you've got the right command to work with. Now change the 'Get' to a 'Set' and work out the values LOCALLY.
I think you are close, but missed something in your tests...
Do ONE at a time, locally, first in PowerShell ISE. Then invoke-command to that same single system, then one by one add your tests...
- Patrick Burwell, 25 year Windows and Linux SysAdmin

Getting both TF.exe and Query TFS in Windows container

I have two docker files. One allows me to Query TFS using $versionControlServer.QueryHistory. The second allows me to use tf.exe to pull code down from the server make modifications to Version.html file and check in the changes. I would like to have one docker file that can do both, Query TFS and Modify code. I am having problems doing this. First off one docker file is using microsoft/windowservercode:10.0.14393.1480 and the other one is using microsoft/dotnet-framework:4.7.1
Here is the code for doing a Query against TFS
FROM microsoft/windowsservercore:10.0.14393.1480
# Setup shell
SHELL ["powershell", "-Command", "$ErrorActionPreference = 'Stop'; $ProgressPreference = 'SilentlyContinue';"]
# Note: Add NuGet
RUN Invoke-WebRequest "https://dist.nuget.org/win-x86-commandline/latest/nuget.exe" -OutFile "C:\windows\nuget.exe" -UseBasicParsing
RUN Mkdir LoadClient
COPY powershell \LoadClient
Here is the psm1 file to load the TFS Assemblies
Write-Host "Loading InstallTFSClient"
#Module location folder
$TFSClientRoot = "C:\TFSClient"
#where to put TFS Client OM files
$NugetFolder = "$TFSClientRoot\Nuget\"
$BinFolder = $("$TFSClientRoot\bin\")
# TFS Object Model Assembly Names
$vsCommon = "Microsoft.VisualStudio.Services.Common"
$commonName = "Microsoft.TeamFoundation.Common"
$clientName = "Microsoft.TeamFoundation.Client"
$VCClientName = "Microsoft.TeamFoundation.VersionControl.Client"
$WITClientName = "Microsoft.TeamFoundation.WorkItemTracking.Client"
$BuildClientName = "Microsoft.TeamFoundation.Build.Client"
$BuildCommonName = "Microsoft.TeamFoundation.Build.Common"
$Source = #"
using System;
using System.Collections.Generic;
using System.Text;
using Microsoft.TeamFoundation.Client;
using System.Net;
public class ConnectByImplementingCredentialsProvider : ICredentialsProvider
{
public ICredentials GetCredentials(Uri uri, ICredentials iCredentials)
{
return new NetworkCredential("OurUser", "OurPassword", "OurEnv");
}
public void NotifyCredentialsAuthenticated(Uri uri)
{
throw new ApplicationException("Unable to authenticate");
}
}
"#
#============================================================================
# new folder method
#============================================================================
function New-Folder{
param( [Parameter( Mandatory=$true)] $folderPath
)
if (Test-Path( $folderPath ))
{
Remove-Item $folderPath -Force -Recurse
}
mkdir $folderPath
}
#============================================================================
# Get-TfsAssembliesFromNuget method
#============================================================================
function Get-TfsAssembliesWithNuget{
New-Folder $TFSClientRoot
New-Folder $NugetFolder
New-Folder $BinFolder
#get all of the TFS 2015 Object Model packages from nuget
C:\windows\nuget install "Microsoft.TeamFoundationServer.Client" -Version 14.83.0 -OutputDirectory $NugetFolder -ExcludeVersion -NonInteractive
C:\windows\nuget install "Microsoft.TeamFoundationServer.ExtendedClient" -Version 14.83.0 -OutputDirectory $NugetFolder -ExcludeVersion -NonInteractive
C:\windows\nuget install "Microsoft.VisualStudio.Services.Client" -Version 14.83.0 -OutputDirectory $NugetFolder -ExcludeVersion -NonInteractive
C:\windows\nuget install "Microsoft.VisualStudio.Services.InteractiveClient" -Version 14.83.0 -OutputDirectory $NugetFolder -ExcludeVersion -NonInteractive
#Copy all of the required .dlls out of the nuget folder structure
#to a bin folder so we can reference them easily and they are co-located
#so that they can find each other as necessary when loading
$allDlls = Get-ChildItem -Path $NugetFolder -Recurse -File -Filter "*.dll"
# Create list of all the required .dlls
#exclude portable dlls
#$net45Dlls = $allDlls | ? {$_.PSPath.Contains("portable") -ne $true } | ? {$_.PSPath.Contains("resources") -ne $true } | ? { ($_.PSPath.Contains("net45") -eq $true) -or ($_.PSPath.Contains("native") -eq $true) -or ($_.PSPath.Contains("Microsoft.ServiceBus") -eq $true) }
$requiredDlls = $allDlls | Where-Object {$_.PSPath.Contains("portable") -ne $true } | where-object {$_.PSPath.Contains("resources") -ne $true } | where-object { ($_.PSPath.Contains("net45") -eq $true) -or ($_.PSPath.Contains("native") -eq $true) -or ($_.PSPath.Contains("Microsoft.ServiceBus") -eq $true) }
#exclude resource dlls
$requiredDlls = $requiredDlls | Where-Object {$_.PSPath.Contains("resources") -ne $true }
#include net45, native, and Microsoft.ServiceBus.dll
$requiredDlls = $requiredDlls | Where-Object { ($_.PSPath.Contains("net45") -eq $true) -or ($_.PSPath.Contains("native") -eq $true) -or ($_.PSPath.Contains("Microsoft.ServiceBus") -eq $true) }
#copy them all to a bin folder
$requiredDlls | ForEach-Object { Copy-Item -Path $_.Fullname -Destination $BinFolder}
}
#============================================================================
# Install-TfsAssembliesFromDisk method
#============================================================================
function Install-TfsAssembliesFromDisk{
Write-Host "loading TFS assemblies"
$TestVar = $($BinFolder + $vsCommon + ".dll")
write-host $TestVar
try {
Add-Type -LiteralPath $($BinFolder + $vsCommon + ".dll")
Add-Type -LiteralPath $($BinFolder + $commonName + ".dll")
Add-Type -LiteralPath $($BinFolder + $clientName + ".dll")
Add-Type -LiteralPath $($BinFolder + $clientName + ".dll")
$Assem = ("Microsoft.TeamFoundation.Client, Version=14.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a")
Add-Type -ReferencedAssemblies $Assem -TypeDefinition $Source -Language CSharp
Add-Type -LiteralPath $($BinFolder + $VCClientName + ".dll")
Add-Type -LiteralPath $($BinFolder + $WITClientName + ".dll")
Add-Type -LiteralPath $($BinFolder + $BuildClientName + ".dll")
Add-Type -LiteralPath $($BinFolder + $BuildCommonName + ".dll")
}
catch {
$_.Exception.LoaderExceptions | ForEach-Object { $_.Message }
}
}
Get-TfsAssembliesWithNuget
Install-TfsAssembliesFromDisk here
Here is the powershell that needs to run on the container to activate everything.
#============================================================================
# Setup TFS stuff
#============================================================================
function Setup-Tfs {
# Get TFS nuget packages installed
Import-Module C:\LoadClient\InstallTFSClient.psm1
# Connect to TFS
[System.Reflection.Assembly]::LoadWithPartialName("Microsoft.TeamFoundation.Client") | out-null
[System.Reflection.Assembly]::LoadWithPartialName("Microsoft.TeamFoundation.VersionControl.Client") | out-null
$tfsServer = "http://OurUrl:Port/etc...";
$tfs = [Microsoft.TeamFoundation.Client.TeamFoundationServerFactory]::GetServer($tfsServer, (New-Object ConnectByImplementingCredentialsProvider))
$Script:versionControlServer = $tfs.GetService([Microsoft.TeamFoundation.VersionControl.Client.VersionControlServer] )
$Script:recursionType = [Microsoft.TeamFoundation.VersionControl.Client.RecursionType]::Full
}
Here is the docker file to load tf.exe
# escape=`
# Use the latest Windows Server Core image with .NET Framework 4.7.1.
FROM microsoft/dotnet-framework:4.7.1
# Download the Build Tools bootstrapper.
ADD https://aka.ms/vs/15/release/vs_buildtools.exe C:\TEMP\vs_buildtools.exe
# Install Build Tools excluding workloads and components with known issues.
RUN C:\TEMP\vs_buildtools.exe --quiet --wait --norestart --nocache `
--installPath C:\BuildTools `
--all `
--remove Microsoft.VisualStudio.Component.Windows10SDK.10240 `
--remove Microsoft.VisualStudio.Component.Windows10SDK.10586 `
--remove Microsoft.VisualStudio.Component.Windows10SDK.14393 `
--remove Microsoft.VisualStudio.Component.Windows81SDK `
|| IF "%ERRORLEVEL%"=="3010" EXIT 0
# Start developer command prompt with any other commands specified.
ENTRYPOINT C:\BuildTools\Common7\Tools\VsDevCmd.bat
# Default to PowerShell if no other command specified.
CMD ["powershell.exe", "-NoLogo", "-ExecutionPolicy", "Bypass"]
Any help on getting this to one docker file would be greatly appricated.

Can't replace file names with PowerShell 2.0

I have files like this.
[mix]aaaa.flv
[mix]aaaa.mpv
[mix]aaaa.ogv
[mix]aaaa.webm
[mix]bb.flv
[mix]bb.mpv
[mix]bb.ogv
[mix]bb.webm
...
I just need to remove "[mix]" from the file names.
I use this command, but failed
Dir | Rename-Item –NewName { $_.name –replace "[mix]", "" }
Error says
Rename-Item : 'Microsoft.PowerShell.Core\FileSystem::C:\Users\Desktop\[mix]aaaa.mp4'에 항목이 없으므로 이름을 바꿀 수 없습니다.
위치 줄:1 문자:18
+ Dir | Rename-Item <<<< –NewName { $_.name –replace “[mix]“,”” }
+ CategoryInfo : InvalidOperation: (:) [Rename-Item], PSInvalidOperationException
+ FullyQualifiedErrorId : InvalidOperation,Microsoft.PowerShell.Commands.RenameItemCommand
There's korean in error code, it might say : Can't change name, there is no item at 'Microsoft.PowerShell.Core\FileSystem::C:\Users\Desktop\[mix]aaaa.mp4'
And I don't understand what I'm doing wrong. I used to change file names with this command.
I think this is a known bug with Rename-Item and powershell 2.0
What I did was to use Move-Item instead, you should be able to use the following (tested on powershell 2.0):
Dir | Move-Item -Destination {$_.Name -replace "\[mix\]", ""}
I was able to make this work. Remember that [ and ] are regex metacharacters and need to be escaped:
Dir | Rename-Item -NewName {$_.Name -replace "\[mix\]",""}

PowerShell PSCX Read-Archive: Cannot bind parameter... problem

I'm running across a problem I can't seem to wrap my head around using the Read-Archive cmdlet available via PowerShell Community Extensions (v2.0.3782.38614).
Here is a cut down sample used to exhibit the problem I'm running into:
$mainPath = "p:\temp"
$dest = Join-Path $mainPath "ps\CenCodes.zip"
Read-Archive -Path $dest -Format zip
Running the above produces the following error:
Read-Archive : Cannot bind parameter 'Path'. Cannot convert the "p:\temp\ps\CenCodes.zip" value of type "System.String" to type "Pscx.IO.PscxPathInfo".
At line:3 char:19
+ Read-Archive -Path <<<< $dest -Format zip
+ CategoryInfo : InvalidArgument: (:) [Read-Archive], ParameterBindingException
+ FullyQualifiedErrorId : CannotConvertArgumentNoMessage,Pscx.Commands.IO.Compression.ReadArchiveCommand
If I do not use Join-Path to build the path passed to Read-Archive it works, as in this example:
$mainPath = "p:\temp"
$path = $mainPath + "\ps\CenCodes.zip"
Read-Archive -Path $path -Format zip
Output from above:
ZIP Folder: CenCodes.zip#\
Index LastWriteTime Size Ratio Name ----- ------------- ---- ----- ----
0 6/17/2010 2:03 AM 3009106 24.53 % CenCodes.xls
Even more confusing is if I compare the two variables passed as the Path argument in the two Read-Archive samples above, they seem identical:
This...
Write-Host "dest=$dest"
Write-Host "path=$path"
Write-Host ("path -eq dest is " + ($dest -eq $path).ToString())
Outputs...
dest=p:\temp\ps\CenCodes.zip
path=p:\temp\ps\CenCodes.zip
path -eq dest is True
Anyone have any ideas as to why the first sample gripes but the second one works fine?
I created an item in the issue tracker on the CodePlex home of PSCX. Apparently this is a current known issue with PscxPathInfo. (See item #28023 in the PSCX Issue Tracker).
A work around is to do this:
Get-Item $dest | Read-Archive
Credit to r_keith_hill on CodePlex for that particular work around.

Resources