Everything in this script I wrote works with if and ifelse statements but not the else statements. Could someone please review the following and help me figure out why? The desired outcome is if I type aconda, a conda environment launches, aconda -d deactivates conda and alters the path, aconda -a activates conda and alters the path . Is there a way to specify the outcome of no parameter?
function aconda {
param(
[Alias('d')]
[Parameter(ParameterSetName='Deactivate')]
[switch] $Deactivate
,
[Alias('a')]
[Parameter(ParameterSetName='Activate')]
[switch] $Activate
,
[Alias("h")]
[Parameter(ParameterSetName='help')]
[switch] $help
)
if ($Activate) {
$Environment = [System.Environment]::GetEnvironmentVariable("Path", "Machine")
foreach ($path in ($Environment).Split(";"))
{
if ($path -like "C:\Program Files\Python310\Scripts\")
{
$Environment = $Environment.Replace($Path ,"")
}
if ($path -like "C:\Program Files\Python310\")
{
$Environment = $Environment.Replace($Path ,"")
}
}
$env:PATH = $Environment
. C:\Anaconda3\shell\condabin\conda-hook.ps1 ; conda activate 'C:\Anaconda3'
}
elseif ($Deactivate)
{
. C:\Anaconda3\shell\condabin\conda-hook.ps1 ; conda deactivate 'C:\Anaconda3'
$env:PATH = [Environment]::GetEnvironmentVariable('Path', 'Machine'),
[Environment]::GetEnvironmentVariable('Path', 'User') -join ';'
}
elseif ($help)
{ Write-Output "
-a activate conda
-d deactivate conda
-? Help. This is the same as not typing any options"
}
else { . C:\Anaconda3\shell\condabin\conda-hook.ps1 ; conda deactivate 'C:\Anaconda3'
}
}
EDIT:
This works, but still ignores the else statement:
function aconda {
[CmdletBinding(DefaultParameterSetName = 'Activate')]
param(
[Alias('d')]
[Parameter(ParameterSetName='Deactivate')]
[switch] $Deactivate
,
[Alias('a')]
[Parameter(ParameterSetName='Activate')]
[switch] $Activate
,
[Alias("h")]
[Parameter(ParameterSetName='help')]
[switch] $help
)
$noInput = !$Deactivate -and !$Activate
if ($PSBoundParameters.ContainsKey('Activate') -or $noInput ) {
$Environment = [System.Environment]::GetEnvironmentVariable("Path", "Machine")
foreach ($path in ($Environment).Split(";"))
{
if ($path -like "C:\Program Files\Python310\Scripts\")
{
$Environment = $Environment.Replace($Path ,"")
}
if ($path -like "C:\Program Files\Python310\")
{
$Environment = $Environment.Replace($Path ,"")
}
}
$env:PATH = $Environment
. C:\Anaconda3\shell\condabin\conda-hook.ps1 ; conda activate 'C:\Anaconda3'
}
elseif ($Deactivate)
{
. C:\Anaconda3\shell\condabin\conda-hook.ps1 ; conda deactivate 'C:\Anaconda3'
$env:PATH = [Environment]::GetEnvironmentVariable('Path', 'Machine'),
[Environment]::GetEnvironmentVariable('Path', 'User') -join ';'
}
elseif ($help)
{ Write-Output "
-a activate conda
-d deactivate conda
-? Help. This is the same as not typing any options"
}
else { . C:\Anaconda3\shell\condabin\conda-hook.ps1 ; conda deactivate 'C:\Anaconda3'
}
}
This does not, the only difference being if ($PSBoundParameters.ContainsKey('Activate') -or $noInput ) vs elseif ($noInput) { . C:\Anaconda3\shell\condabin\conda-hook.ps1 ; conda deactivate 'C:\Anaconda3' }:
function aconda {
[CmdletBinding(DefaultParameterSetName = 'Activate')]
param(
[Alias('d')]
[Parameter(ParameterSetName='Deactivate')]
[switch] $Deactivate
,
[Alias('a')]
[Parameter(ParameterSetName='Activate')]
[switch] $Activate
,
[Alias("h")]
[Parameter(ParameterSetName='help')]
[switch] $help
)
$noInput = !$Deactivate -and !$Activate
if ($PSBoundParameters.ContainsKey('Activate') ) {
$Environment = [System.Environment]::GetEnvironmentVariable("Path", "Machine")
foreach ($path in ($Environment).Split(";"))
{
if ($path -like "C:\Program Files\Python310\Scripts\")
{
$Environment = $Environment.Replace($Path ,"")
}
if ($path -like "C:\Program Files\Python310\")
{
$Environment = $Environment.Replace($Path ,"")
}
}
$env:PATH = $Environment
. C:\Anaconda3\shell\condabin\conda-hook.ps1 ; conda activate 'C:\Anaconda3'
}
elseif ($Deactivate)
{
. C:\Anaconda3\shell\condabin\conda-hook.ps1 ; conda deactivate 'C:\Anaconda3'
$env:PATH = [Environment]::GetEnvironmentVariable('Path', 'Machine'),
[Environment]::GetEnvironmentVariable('Path', 'User') -join ';'
}
elseif ($help)
{ Write-Output "
-a activate conda
-d deactivate conda
-? Help. This is the same as not typing any options"
}
elseif ($noInput) { . C:\Anaconda3\shell\condabin\conda-hook.ps1 ; conda deactivate 'C:\Anaconda3'
}
}
Answering your question
Switch parameters are inherently $False, unless the user specifies that param. Since you want to do an operation if both switch params are false, you can add a check for that condition.
$noInput = !$Deactivate -and !$Activate
#...
elseif ($help -or $noInput){
#your Code here
}
Note: You will need to remove your CmdletParamSet attributes to use this technique.
If you want to ensure your users aren't running the function with both -Activate -Deactivate specified, then just add a check to see if both are true and if so Write-Error "You may only specify one activation selection"
Easier Alternative
Or better yet, change the switch statements to [switch]$ActivationStatus and remove the second switch, then users will use the function like this:
aconda -ActivationStatus $true
aconda -ActivationStatus $false
Related
I am trying to modify my PowerShell script to find the best possible ways to check for Pending Reboots on our servers. This script checks the registry entries. However, I am seeing inconsistencies from other PowerShell scripts and wanting guidance on the best approach.
function PendingReboot ($comp) {
process {
try {
$WMI_OS = ""
$RegCon = ""
$WMI_OS = Get-WmiObject -Class Win32_OperatingSystem -ComputerName $comp -ErrorAction Stop
if ($?){
try{
$RegCon = [Microsoft.Win32.RegistryKey]::OpenRemoteBaseKey([Microsoft.Win32.RegistryHive]"LocalMachine",$comp)
If ($WMI_OS.BuildNumber -ge 6001){
$RegValueSetupex = ""
$RegValuePFRO2k8 = ""
$RegSubKeySM = $RegCon.OpenSubKey("SYSTEM\CurrentControlSet\Control\Session Manager\")
$RegValueSetupex = $RegSubKeySM.GetValue("SetupExecute",$null)
if ($RegValueSetupex){
$RegValueSetupex = $true
}
$RegSubKeySM = $RegCon.OpenSubKey("SYSTEM\CurrentControlSet\Control\Session Manager\")
$RegValuePFRO2k8 = $RegSubKeySM.GetValue("PendingFileRenameOperations",$null)
if ($RegValuePFRO2k8 ){
$RegValuePFRO2k8 = $true
}
$RegCon.Close()
if ( $RegValueSetupex -eq $true -or $RegValuePFRO2k8 -eq $true){
return '<font color="#FF0000">'+$true
}
else {
return $false
}
}
else{
$RegValuePFRO2k3 = $false;
$RegCon = [Microsoft.Win32.RegistryKey]::OpenRemoteBaseKey([Microsoft.Win32.RegistryHive]"LocalMachine","$comp")
$RegSubKeySM = $RegCon.OpenSubKey("SYSTEM\CurrentControlSet\Control\Session Manager\")
$RegValuePFRO2k3 = $RegSubKeySM.GetValue("PendingFileRenameOperations",$null)
$RegCon.Close()
If ($RegValuePFRO2k3) {
return '<font color="#FF0000">'+$true;
}
else {
return $false;
}
}
}
catch {
return '<font color="#FFFF00">'+"Remote Registry Service KO"
}
}
else {
throw $error[0].Exception
}
}
catch {
return '<font color="#FF0000">'+"RPC Issue"
}
}
}
Try this.
function PendingBoot($comp) {
$pendingRebootTests = #(
#{
Name = 'RebootPending'
Test = { Get-ItemProperty -Path 'HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\Component Based Servicing' Name 'RebootPending' -ErrorAction Ignore }
TestType = 'ValueExists'
}
#{
Name = 'RebootRequired'
Test = { Get-ItemProperty -Path 'HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\WindowsUpdate\Auto Update' Name 'RebootRequired' -ErrorAction Ignore }
TestType = 'ValueExists'
}
#{
Name = 'PendingFileRenameOperations'
Test = { Get-ItemProperty -Path 'HKLM:\SYSTEM\CurrentControlSet\Control\Session Manager' -Name 'PendingFileRenameOperations' -ErrorAction Ignore }
TestType = 'NonNullValue'
}
)
$session = New-PSSession -Computer SRV1
foreach ($test in $pendingRebootTests) {
$result = Invoke-Command -Session $session -ScriptBlock $test.Test
if ($test.TestType -eq 'ValueExists' -and $result) {
$true
} elseif ($test.TestType -eq 'NonNullValue' -and $result -and $result.($test.Name)) {
$true
} else {
$false
}
}
$session | Remove-PSSession
}
Below is my script istalling Monserrat fonts from zip file. I can't figure how to check if a font already installed. After installation I can open folder C:\Windows\Fonts\Montserrat and I see al of them. When I am running script second time, it is not recognize existance of this folder. Where is my mistake?
$Source = "Montserrat.zip"
$FontsFolder = "FontMontserrat"
Expand-Archive $Source -DestinationPath $FontsFolder
$FONTS = 0x14
$CopyOptions = 4 + 16;
$objShell = New-Object -ComObject Shell.Application
$objFolder = $objShell.Namespace($FONTS)
$allFonts = dir $FontsFolder
foreach($File in $allFonts)
{
If((Test-Path "C:\Windows\Fonts\Montserrat") -eq $True)
{
echo "Font $File already installed"
}
Else
{
echo "Installing $File"
$CopyFlag = [String]::Format("{0:x}", $CopyOptions);
$objFolder.CopyHere($File.fullname,$CopyFlag)
}
}
Finally my script:
$Source = "Montserrat.zip"
$FontsFolder = "FontMontserrat"
Expand-Archive $Source -DestinationPath $FontsFolder -Force
$FONTS = 0x14
$CopyOptions = 4 + 16;
$objShell = New-Object -ComObject Shell.Application
$objFolder = $objShell.Namespace($FONTS)
$allFonts = dir $FontsFolder
foreach($font in Get-ChildItem -Path $fontsFolder -File)
{
$dest = "C:\Windows\Fonts\$font"
If(Test-Path -Path $dest)
{
echo "Font $font already installed"
}
Else
{
echo "Installing $font"
$CopyFlag = [String]::Format("{0:x}", $CopyOptions);
$objFolder.CopyHere($font.fullname,$CopyFlag)
}
}
I am running this script by following cmd:
set batchPath=%~dp0
powershell.exe -noexit -file "%batchPath%InstMontserrat.ps1"
I don't have to run it as administrator, but user have admin permissions.
Corrections of your script based on my comment assuming Windows 10:
# well-known SID for admin group
if ('S-1-5-32-544' -notin [System.Security.Principal.WindowsIdentity]::GetCurrent().Groups) {
throw 'Script must run as admin!'
}
$source = 'Montserrat.zip'
$fontsFolder = 'FontMontserrat'
Expand-Archive -Path $source -DestinationPath $fontsFolder
foreach ($font in Get-ChildItem -Path $fontsFolder -File) {
$dest = "C:\Windows\Fonts\$font"
if (Test-Path -Path $dest) {
"Font $font already installed."
}
else {
$font | Copy-Item -Destination $dest
}
}
If you do not want to install the font on OS level but only make it available for programs to use until reboot you may want to use this script that:
Will fail/throw if it cannot register/unregister font.
Broadcasts WM_FONTCHANGE to inform all windows that fonts have changed
Does not require administrator privileges
Does not install fonts in Windows, only makes them available for all programs in current session until reboot
Has verbose mode for debugging
Does not work with font folders
Usage:
register-fonts.ps1 [-v] [-unregister <PATH>[,<PATH>...]] [-register <PATH>[,<PATH>...]] # Register and unregister at same time
register-fonts.ps1 [-v] -unregister <PATH>
register-fonts.ps1 [-v] -register <PATH>
register-fonts.ps1 [-v] <PATH> # Will register font path
Param (
[Parameter(Mandatory=$False)]
[String[]]$register,
[Parameter(Mandatory=$False)]
[String[]]$unregister
)
# Stop script if command fails https://stackoverflow.com/questions/9948517/how-to-stop-a-powershell-script-on-the-first-error
$ErrorActionPreference = "Stop"
add-type -name Session -namespace "" -member #"
[DllImport("gdi32.dll")]
public static extern bool AddFontResource(string filePath);
[DllImport("gdi32.dll")]
public static extern bool RemoveFontResource(string filePath);
[return: MarshalAs(UnmanagedType.Bool)]
[DllImport("user32.dll", SetLastError = true, CharSet = CharSet.Auto)]
public static extern bool PostMessage(IntPtr hWnd, int Msg, int wParam = 0, int lParam = 0);
"#
$broadcast = $False;
Foreach ($unregisterFontPath in $unregister) {
Write-Verbose "Unregistering font $unregisterFontPath"
# https://learn.microsoft.com/en-us/windows/win32/api/wingdi/nf-wingdi-removefontresourcea
$success = [Session]::RemoveFontResource($unregisterFontPath)
if (!$success) {
Throw "Cannot unregister font $unregisterFontPath"
}
$broadcast = $True
}
Foreach ($registerFontPath in $register) {
Write-Verbose "Registering font $registerFontPath"
# https://learn.microsoft.com/en-us/windows/win32/api/wingdi/nf-wingdi-addfontresourcea
$success = [Session]::AddFontResource($registerFontPath)
if (!$success) {
Throw "Cannot register font $registerFontPath"
}
$broadcast = $True
}
if ($broadcast) {
# HWND_BROADCAST https://learn.microsoft.com/en-us/windows/win32/api/winuser/nf-winuser-postmessagea
$HWND_BROADCAST = New-Object IntPtr 0xffff
# WM_FONTCHANGE https://learn.microsoft.com/en-us/windows/win32/gdi/wm-fontchange
$WM_FONTCHANGE = 0x1D
Write-Verbose "Broadcasting font change"
# Broadcast will let other programs know that fonts were changed https://learn.microsoft.com/en-us/windows/win32/api/winuser/nf-winuser-postmessagea
$success = [Session]::PostMessage($HWND_BROADCAST, $WM_FONTCHANGE)
if (!$success) {
Throw "Cannot broadcase font change"
}
}
The script was inspired by this gist https://gist.github.com/Jaykul/d53a16ce5e7d50b13530acb4f98aaabd
I have built a script that connects to an Oracle database and proceed to some various export.
It works perfectly when I launch powershell.exe from Windows start menu and run the script as follows:
.\OracleConnect
But, when I try to automatize the exact same script by launching it from a batch, I'm getting an error message:
"The type initializer for 'Oracle.DataAccess.Client.OracleConnection' threw an exception"
As I said the script is identical in both case.
My .bat file is as follows:
set path=%~dp0
set file=OracleConnect.ps1
C:\Windows\system32\WindowsPowerShell\v1.0\powershell.exe -ExecutionPolicy Bypass %file%
I've also tried with the alternative powershell.exe path:
C:\Windows\syswow64\WindowsPowerShell\v1.0\powershell.exe -ExecutionPolicy Bypass %file%
Without any success.
Here is my full script:
$scriptpath = Split-Path -Parent -Path $MyInvocation.MyCommand.Definition
Set-Location $scriptpath
[void][Reflection.Assembly]::LoadFile($scriptpath + "\Oracle.DataAccess.dll")
$logpath = $scriptpath + "\Export.txt"
$connectionpath = read-host 'connection file [optional]'
if($connectionpath)
{
$connectionstring = get-content $connectionpath
}
else
{
$server = read-host 'host name'
$user = read-host 'user name'
$pass = read-host 'password'
$database = read-host 'service'
$connectionstring = "Data Source=(DESCRIPTION=(ADDRESS_LIST=(ADDRESS=(PROTOCOL=TCP)(HOST=$server)(PORT=1521)))(CONNECT_DATA=(SERVER=DEDICATED)(SERVICE_NAME=$database)));User Id=$user;Password=$pass;"
}
$echoon = read-host 'echo on (y - n) [default off]'
function global:get-result($query)
{
$oracleconnection = new-object Oracle.DataAccess.Client.OracleConnection
$oracleconnection.connectionstring = $connectionstring
$oracleconnection.Open()
$oraclecommand = $oracleconnection.CreateCommand()
$oraclecommand.CommandText = $query
$reader = $oraclecommand.ExecuteReader()
$writer = new-object System.IO.StreamWriter($logpath)
$counter = 0
write-output ""
while ($reader.Read())
{
$columns = ""
$columnslog = ""
$tab = ""
$tablog = ""
if($counter -eq 0)
{
for ($i= 0; $i -lt $reader.FieldCount; $i++)
{
$columns = $columns + " | " + $reader.GetName($i)
$columnslog = $columnslog + "`t" + $reader.GetName($i).ToUpper()
}
$writer.WriteLine($columnslog)
if($echoon -eq "y")
{
write-output $columns
write-output ""
}
}
for ($i= 0; $i -lt $reader.FieldCount; $i++)
{
$tab = $tab + " | " + $reader.GetValue($i).ToString()
$tablog = $tablog + "`t" + $reader.GetValue($i).ToString()
}
$writer.WriteLine($tablog)
if($echoon -eq "y")
{
write-output $tab
write-output ""
}
$counter = $counter + 1
}
$oracleconnection.Close()
$writer.Close()
}
function global:update-query($query)
{
$oracleconnection = new-object Oracle.DataAccess.Client.OracleConnection
$oracleconnection.connectionstring = $connectionstring
$oracleconnection.Open()
$oraclecommand = $oracleconnection.CreateCommand()
$oraclecommand.CommandText = $query
$reader = $oraclecommand.ExecuteNonQuery()
}
function global:readscript($path)
{
$inenc = [System.Text.Encoding]::UTF7
$reader = new-object System.IO.StreamReader($path, $inenc)
$finalquery = ""
while ($line = $reader.ReadLine())
{
$finalquery += $line
}
$reader.close()
return $finalquery
}
write-output "Enter query or type 'exit' to quit..."
while($true)
{
$value = read-host " "
if($value -eq "exit")
{
$save = read-host "Save connection ? [Y:yes N:no]"
if($save.ToLower() -eq "y")
{
$path = read-host "Connection path"
if(test-path $path)
{
rm $path
}
new-item -type file -force $path
$writer = New-Object System.IO.StreamWriter $path
$writer.WriteLine($connectionstring)
$writer.Close()
}
else
{
}
return
}
else
{
if($value.Tolower().EndsWith(".sql") -eq $false)
{
if ($value.ToLower().StartsWith("select") -or $value.ToLower().StartsWith("show"))
{
get-result($value)
}
else
{
update-query($value)
}
}
else
{
$scriptquery = readscript $value
if ($scriptquery.ToLower().StartsWith("select") -or $scriptquery.ToLower().StartsWith("show"))
{
get-result($scriptquery)
}
else
{
update-query($scriptquery)
}
}
}
}
Edit:
I've now tried to catch the exception adding a try catch instruction here:
try
{
$oracleconnection = new-object Oracle.DataAccess.Client.OracleConnection
}
catch
{
write-host $_.Exception.ToString()
}
And I'm getting this message:
Oracle.DataAccess.Client.OracleException: The provider is not compatible with the version of Oracle client
I still don't understand how this can be an issue with the version of Oracle since it works fine when I run it from a powershell window.
I am trying to only allow a user to enter 2 letters when they rename a file if its exists.
It is not working as I wanted it. I am allowed to enter numbers.
if ($RenameLargeFiles.Length -gt '2') {
Write-Host " You may only enter 2 letters."
Pause
Clear-Host
Rename-LargeFiles
} else {
Rename-Item -Path $LargeFiles $RenameLargeFiles".txt"
$LargeFiles = $RenameLargeFiles
Set-Content -Value $Files -Path $LargeFiles
}
}
Set-StrictMode –Version Latest
$LargeFiles = "C:\PSScripts\LargeFiles.txt"
$PSScripts = "C:\PSScripts"
$TestPSScripts = Test-Path "C:\PSScripts"
switch ($TestPSScripts) {
'False' { New-Item -Type directory -Path $PSScripts }
}
function Test-Files {
$Files8 = ""
$Files8 = Read-Host " Please Enter the Complete Path. "
$TFiles8 = Test-Path $files8
if ($TFiles8 -eq 'True') {
Write-Host $Files8 "LOCATED."
} else {
Write-Host $Files8 "NOT FOUND"
Pause
Clear-Host
Test-Files
}
}
function Test-LargeFiles {
$LargeFiles = "C:\PSScripts\LargeFiles.txt"
$TestLargeFiles = Test-Path $LargeFiles
if ($TestLargeFiles -eq 'True') {
Write-Host $LargeFiles "already present"
Rename-LargeFiles
} else {
Write-Host $LargeFiles "NOT FOUND."
Write-Host $LargeFiles "created"
}
}
function Rename-LargeFiles {
$LargeFiles = "C:\PSScripts\LargeFiles.txt"
[string] $RenameLargeFiles = Read-Host " Please Enter 2 letters to rename" $LargeFiles
if ($RenameLargeFiles.Length -gt '2') {
Write-Host " You may only enter 2 letters."
Pause
Clear-Host
Rename-LargeFiles
} else {
Rename-Item -Path $LargeFiles $RenameLargeFiles".txt"
$LargeFiles = $RenameLargeFiles
Set-Content -Value $Files -Path $LargeFiles
}
}
Test-Files
$Files = Get-ChildItem -Recurse $Files8 | Sort-Object -Descending -Property Length | Select-Object -First 10
Test-LargeFiles
Add-Content -Value $Files -Path $LargeFiles
pause
Use a regex like so:
if ($RenameLargeFiles -notmatch '[aA-zZ]{2}') {
... display error message
}
I have a powershell script that creates some DotNetZip ZIP files on a persistent connection on multiple servers, then uses Start-BitsTransfer to move the ZIP files from the remote servers to the local.
I run pretty much the same script on two different servers, on one it barely prints anything to the screen. On the other, it outputs a LOT - binary looking stuff. Is this because there is some kind of debug setting that is turned on on the server that is outputting all of this info? Is there a way I can turn it off? I'd rather it be more clean like the first server that runs the script.
Thank you!
-Jim
Here is almost the entire script (without my servernames in the $webServers array:
Import-Module BitsTransfer
foreach($i in $webServers) {
if (!(Test-Path -path \\$i\d$\newDeploy)) {
New-Item \\$i\d$\newDeploy -type directory
}
if (!(Test-Path -path \\$i\d$\newDeploy\backup)) {
New-Item \\$i\d$\newDeploy\backup -type directory
}
if(!(Test-Path \\$i\d$\newDeploy\Ionic.Zip.dll)) {
Start-BitsTransfer -Source \\$webDeployServer\d$\newDeploy\Ionic.Zip.dll -Destination \\$i\d$\newDeploy
}
}
foreach($i in $webServers) {
$sessionForI = New-PSSession -computername $i
Invoke-Command -Session $sessionForI -ScriptBlock {
if ((Test-Path D:\\newDeploy\\backup\\OffM.zip)) {
Remove-Item D:\\newDeploy\\backup\\OffM.zip
}
[System.Reflection.Assembly]::LoadFrom("D:\\newDeploy\\Ionic.Zip.dll");
$zipfile = new-object Ionic.Zip.ZipFile
$e = $zipfile.AddSelectedFiles("name != '*.e2e'","D:\inetpub\wwwroot\OffM", "OffM",1)
$e = $zipfile.AddSelectedFiles("name != '*.e2e'","D:\inetpub\wwwroot\PaEnterprise", "PaEnterprise",1)
$zipfile.Save("D:\\newDeploy\\backup\\OffM.zip")
$zipfile.Dispose()
if ((Test-Path D:\\newDeploy\\backup\\Others.zip)) {
Remove-Item D:\\newDeploy\\backup\\Others.zip
}
[System.Reflection.Assembly]::LoadFrom("D:\\newDeploy\\Ionic.Zip.dll");
$zipfile = new-object Ionic.Zip.ZipFile
$e = $zipfile.AddSelectedFiles("name != '*.e2e'","D:\inetpub\wwwroot\MstrInt-PO", "MstrInt-PO",1)
$e = $zipfile.AddSelectedFiles("name != '*.e2e'","D:\inetpub\wwwroot\Maint", "Maint",1)
$zipfile.Save("D:\\newDeploy\\backup\\Others.zip")
$zipfile.Dispose()
if ((Test-Path D:\\newDeploy\\backup\\PPO.zip)) {
Remove-Item D:\\newDeploy\\backup\\PPO.zip
}
[System.Reflection.Assembly]::LoadFrom("D:\\newDeploy\\Ionic.Zip.dll");
$zipfile = new-object Ionic.Zip.ZipFile
$e = $zipfile.AddSelectedFiles("name != '*.e2e'","D:\inetpub\wwwroot\HC", "HC",1)
$e = $zipfile.AddSelectedFiles("name != '*.e2e'","D:\inetpub\wwwroot\PaOn", "PaOn",1)
if($i -eq 'PYRALNWSP02V') {
$e = $zipfile.AddSelectedFiles("name != '*.e2e'","D:\inetpub\wwwroot\HearPl", "HearPl",1)
} else {
$e = $zipfile.AddSelectedFiles("name != '*.e2e'","D:\inetpub\wwwroot\HearPaPlu", "HearPaPlu",1)
}
$zipfile.Save("D:\\newDeploy\\backup\\PPO.zip")
$zipfile.Dispose()
if ((Test-Path D:\\newDeploy\\backup\\TiMan.zip)) {
Remove-Item D:\\newDeploy\\backup\\TiMan.zip
}
[System.Reflection.Assembly]::LoadFrom("D:\\newDeploy\\Ionic.Zip.dll");
$zipfile = new-object Ionic.Zip.ZipFile
$e = $zipfile.AddSelectedFiles("name != '*.e2e'","D:\inetpub\wwwroot\TiManView", "TiManView",1)
$e = $zipfile.AddSelectedFiles("name != '*.e2e'","D:\inetpub\wwwroot\TiManOnline", "TiManOnline",1)
$e = $zipfile.AddSelectedFiles("name != '*.e2e'","D:\inetpub\wwwroot\TiManPOne", "TiManPOne",1)
$zipfile.Save("D:\\newDeploy\\backup\\TiMan.zip")
$zipfile.Dispose()
}
remove-PSSession -session $sessionForI
}
foreach($i in $webServers) {
if(!(Test-Path -path D:\newDeploy\backup\$i)) {
New-Item D:\newDeploy\backup\$i -type directory
}
Start-BitsTransfer -Source \\$i\d$\newDeploy\backup\OffM.zip -Destination D:\newDeploy\backup\$i
Start-BitsTransfer -Source \\$i\d$\newDeploy\backup\Others.zip -Destination D:\newDeploy\backup\$i
Start-BitsTransfer -Source \\$i\d$\newDeploy\backup\PPO.zip -Destination D:\newDeploy\backup\$i
Start-BitsTransfer -Source \\$i\d$\newDeploy\backup\TiMan.zip -Destination D:\newDeploy\backup\$i
}
foreach($i in $webServers) {
Remove-Item \\$i\d$\newDeploy\backup\OffM.zip
Remove-Item \\$i\d$\newDeploy\backup\Others.zip
Remove-Item \\$i\d$\newDeploy\backup\PPO.zip
Remove-Item \\$i\d$\newDeploy\backup\TiMan.zip
}
[System.Reflection.Assembly]::LoadFrom("D:\\newDeploy\\Ionic.Zip.dll");
$directoryToZip = "D:\newDeploy\backup"
$date = get-date -format "M-d-yyyy"
$zipfile = new-object Ionic.Zip.ZipFile
$e = $zipfile.AddSelectedFiles("name != '*.e2e'",$directoryToZip, "",1)
$zipfile.Save("D:\\newDeploy\\backup\\"+$date+"_WEBbackup.zip")
$zipfile.Dispose()
There is a debug messages setting like that - $DebugPreference
It's default is SilentlyContinue. See if it is set to something else.
It would help if you also showed the difference in output. It could also be a verbose output as controlled by the $VerbosePreference
Look here to know about the preference varibales - http://technet.microsoft.com/en-us/library/dd347731.aspx
Update:
Add a [void] before [System.Reflection.Assembly]::LoadFrom statements so that the output doesn't pollute the script output.